package com.td.boss.game.complayercultivate.serivce;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.td.boss.common.pojo.Result;
import com.td.boss.config.enums.ResultEnum;
import com.td.boss.game.comconfigland.pojo.ComConfigLand;
import com.td.boss.game.comconfigland.service.ComConfigLandService;
import com.td.boss.game.complayerland.pojo.ComPlayerLand;
import com.td.boss.game.complayerland.service.ComPlayerLandService;
import com.td.boss.util.DappUtil;
import com.td.boss.util.RedisData;
import com.td.boss.util.RedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
@Transactional
public class ComPlayerCultivateSerivceImpl implements ComPlayerCultivateSerivce {

    @Autowired
    private ComPlayerLandService comPlayerLandService;
    @Autowired
    private ComConfigLandService comConfigLandService;
//    @Autowired
//    private ComPlayerCultivateRepository cultivateRepository;
//    @Autowired
//    private ComPlayerCultivateDetailRepository cultivateDetailRepository;

    @Autowired
    private RedisLock redisLock;

    @Transactional
    @Override
    public Result<?> zulin(String userId, Integer configLandId) {
        long time = System.currentTimeMillis() + RedisData.getPlayerCultivateZuLinTimeout();
        String _redisKey = "LOCK:COM_PLAYER_CULTIVATE_ZULIN:" + userId;
        if (redisLock.lock(_redisKey, String.valueOf(time))) {
            log.info("锁住key：" + _redisKey);
            return ErrorResult("操作频繁！");
        }
        try {
            //根据土地config id查找，对应ConfigLandId ,
            ComConfigLand comConfigLand = comConfigLandService.findById(configLandId);
            //如果土地等于不能初始化，或者已经种植，不能进行购买
            if (comConfigLand == null || comConfigLand.getIsInit().equals(0) || comConfigLand.getIsPlant().equals(1)) {
                return Result.of(null, false, ResultEnum.LAND_DATA_ERROR.getMessage(), ResultEnum.LAND_DATA_ERROR.getCode());
            }
            if (getTimes(userId) <= 0) {
                return ErrorResult("次数不足！");
            }
            ComPlayerLand comPlayerLand = comPlayerLandService.findByUserIdAndLandId(userId, configLandId);

            if (comPlayerLand == null) {
                //创建新土地
                comPlayerLand = new ComPlayerLand();
                comPlayerLand.setConfigLandId(comConfigLand.getId());
                comPlayerLand.setUserId(userId);
                comPlayerLand.setName(comConfigLand.getName());
                //todo 续租问题，如果用户续租，保留之前的状态
                //初始化一下未种植参数
                comPlayerLand.setIsPlant(0);
                comPlayerLand.setCreateTime(new Date());
                comPlayerLand.setPlantSteal(1);
                comPlayerLand.setMallType(comConfigLand.getMallType());

                comPlayerLand.setLandDescribe("每次租赁1个月");
                comPlayerLand.setLeaseMultiple(1);
                comPlayerLand.setLeaseDate(1);
                //设置租赁日期
                comPlayerLand.setLeaseTime(DateUtil.offset(new Date(), DateField.MONTH, 1));
                //租赁土地
                comPlayerLand.setIsLease(1);
                comPlayerLand.setUpdateTime(new Date());
                //记录一下租赁费用
                comPlayerLand.setRentalExpenses(1.0d);
                comPlayerLandService.AddComPlayerLand(comPlayerLand);
            }
            return Result.of(null, true, "租赁成功");
        } catch (Exception e) {
        } finally {
            redisLock.unlock(_redisKey, String.valueOf(time));
        }
        return ErrorResult("租赁失败！");
    }

//    @Transactional
//    @Override
//    public Result<?> toufang(String userId, String landId, String seedId, Integer seedNum) {
//        long time = System.currentTimeMillis() + RedisData.getPlayerCultivateTouFangTimeout();
//        String _redisKey = "LOCK:COM_PLAYER_CULTIVATE_TOUFANG:" + userId;
//        if (redisLock.lock(_redisKey, String.valueOf(time))) {
//            return ErrorResult("操作频繁！");
//        }
//        try {
//            ComPlayerCultivate comPlayerCultivate = cultivateRepository.findByUserId(userId);
//            if (comPlayerCultivate == null) {
//                return ErrorResult("该土地未被租赁！");
//            }
//            ComPlayerCultivateSeedVo seedVo = getSeedById(seedId);
//            if (seedVo == null) {
//                return ErrorResult("幼崽不存在！");
//            }
//            if (comPlayerCultivate != null && Integer.getInteger("1").equals(comPlayerCultivate.getIsActivity())) {
//                return ErrorResult("该土地正在使用中！");
//            }
//            //计算一下成熟的时间
//            DateTime maturityTime = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, seedVo.getMaturity());
//            if (maturityTime.after(comPlayerCultivate.getEndTime())) {
//                return ErrorResult("土地租赁时间不足！");
//            }
//            //判断一下种植最大数量
//            if (comPlayerCultivate.getLandLimit() > seedNum) {
//                return ErrorResult("最多可投放" + comPlayerCultivate.getLandLimit() + "！");
//            }
//            comPlayerCultivate.setIsActivity(1);
//            cultivateRepository.save(comPlayerCultivate);
//
//            ComPlayerCultivateDetail comPlayerCultivateDetailVo = new ComPlayerCultivateDetail();
//            comPlayerCultivateDetailVo.setCreateTime(new Date());
//            comPlayerCultivateDetailVo.setSeed(JSONUtil.toJsonStr(seedVo));
//            comPlayerCultivateDetailVo.setSeedId(seedVo.getSeedId());
//            comPlayerCultivateDetailVo.setSeedNum(seedNum);
//            comPlayerCultivateDetailVo.setIsMaturity(0);
//            comPlayerCultivateDetailVo.setMaturityTime(maturityTime);
//            comPlayerCultivateDetailVo.setIncomeNum(seedVo.getHarvest() * seedNum);
//            cultivateDetailRepository.save(comPlayerCultivateDetailVo);
//            return Result.of(null, true, "投放成功！");
//
//        } catch (Exception e) {
//        } finally {
//            redisLock.unlock(_redisKey, String.valueOf(time));
//        }
//        return ErrorResult("投放失败！");
//    }

    /**
     * 获取租赁机会
     *
     * @param userId
     * @return
     */
    @Override
    public Integer getTimes(String userId) {
        Integer totalcount = DappUtil.getChildrenBuyLandAmount(userId);
        long hascount = comPlayerLandService.findAllByUserId(userId).stream()
                .filter(a -> a.getMallType() > 0)
                .map(a -> a.getLeaseDate())
                .reduce(0, Integer::sum);
        return totalcount - Convert.toInt(hascount);
    }


    private Result<?> ErrorResult(String msg) {
        return Result.of(null, false, msg);
    }
}
