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

import cn.hutool.core.convert.Convert;
import com.td.boss.common.pojo.Result;
import com.td.boss.config.enums.ResultEnum;
import com.td.boss.game.comexplainland.service.ComExplainLandService;
import com.td.boss.game.comexplainland.vo.ComExplainLandVo;
import com.td.boss.game.commallseed.service.ComMallSeedService;
import com.td.boss.game.commallseed.vo.ComMallSeedVo;
import com.td.boss.game.complayergoods.pojo.ComPlayerGoods;
import com.td.boss.game.complayergoods.service.ComPlayerGoodsService;
import com.td.boss.game.complayergoods.vo.ComPlayerGoodsVo;
import com.td.boss.game.complayerland.pojo.ComPlayerLand;
import com.td.boss.game.complayerland.service.ComPlayerDisasterLogService;
import com.td.boss.game.complayerland.service.ComPlayerDisasterProtectedService;
import com.td.boss.game.complayerland.service.ComPlayerLandService;
import com.td.boss.game.complayerland.vo.ComPlayerLandAndPlantVo;
import com.td.boss.game.complayerland.vo.ComPlayerLandVo;
import com.td.boss.game.complayerlog.service.ComPlayerLogService;
import com.td.boss.game.complayerlog.vo.ComPlayerLogVo;
import com.td.boss.game.complayerprofit.service.ComPlayerProfitService;
import com.td.boss.util.CopyUtil;
import com.td.boss.util.DateUtil;
import com.td.boss.util.RedisLock;
import com.td.boss.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;


/**
 * 放牧\养殖\渔场
 */
@RestController
@Slf4j
@RequestMapping("/game/comPlayerCultivate/")
public class ComPlayerCultivateController {
    @Autowired
    private ComPlayerLandService comPlayerLandService;

    @Autowired
    private ComMallSeedService comMallSeedService;

    @Autowired
    private ComPlayerGoodsService comPlayerGoodsService;

    @Autowired
    private ComPlayerLogService comPlayerLogService;

    @Autowired
    private ComExplainLandService comExplainLandService;

    /**
     * 种植土地，要先有土地才能种植
     *
     * @param userId
     * @return
     */
    @GetMapping("plant")
    @Transactional(rollbackFor = Exception.class)
    public Result<ComPlayerLandAndPlantVo> plantFunction(
            @RequestParam(value = "userId") String userId,
            @RequestParam(value = "landId") Integer landId,
            @RequestParam(value = "seedId") Integer seedId,
            @RequestParam(value = "count") Integer count) {

        try {
            ComPlayerLand comPlayerLand = comPlayerLandService.findByUserIdAndLandId(userId, landId);
            //土地数据不存在
            if (comPlayerLand == null) {
                return Result.of(null, false, ResultEnum.LAND_DATA_ERROR.getMessage(), ResultEnum.LAND_DATA_ERROR.getCode());
            }
            if (!comPlayerLand.getIsLease().equals(1)) {
                return Result.of(null, false, ResultEnum.LAND_NOT_LEASE.getMessage(), ResultEnum.LAND_NOT_LEASE.getCode());
            }
            //土地已种植
            if (comPlayerLand.getIsPlant().equals(1)) {
                return Result.of(null, false, ResultEnum.LAND_IS_PLANT.getMessage(), ResultEnum.LAND_IS_PLANT.getCode());
            }
            //todo 用户没刷新时候，土地还存在。判定一下时间是否到期，到期不给收获
            //租赁的剩余天数 。
            Long leaseDaysMill = comPlayerLand.getLeaseTime().getTime() - DateUtil.getNowDate().getTime();
            if (leaseDaysMill <= 0) {
                //todo 清除记录的数据
                //    1.土地租赁到期，删除土地租赁数据
                comPlayerLandService.delete(comPlayerLand.getId());
                //todo 2.把删除的这个土地的数据记录到com_explain_land中去
                ComExplainLandVo comExplainLandVo = new ComExplainLandVo();
                comExplainLandVo = CopyUtil.copy(comPlayerLand, ComExplainLandVo.class);
                comExplainLandVo.setLandId(comPlayerLand.getConfigLandId());
                comExplainLandVo.setLandCreate(comPlayerLand.getCreateTime());
                comExplainLandVo.setExplainType(0);
                comExplainLandVo.setExplainDescribe("播种种子时:土地租赁过期回收");
                comExplainLandVo.setCreateTime(new Date());
                comExplainLandVo.setUpdateTime(new Date());
                comExplainLandService.save(comExplainLandVo);
                return Result.of(null, false, ResultEnum.LAND_LEASE_EXPIRED.getMessage(), ResultEnum.LAND_LEASE_EXPIRED.getCode());
            }

            //获得种子信息
            ComMallSeedVo comMallSeedVo = comMallSeedService.findById(seedId);
            if (comMallSeedVo == null) {
                return Result.of(null, false, ResultEnum.SEED_DATA_ERROR.getMessage(), ResultEnum.SEED_DATA_ERROR.getCode());
            }
            //[xst] 如果剩余时间<成熟时间 不允许种子
            if (Convert.toInt(comMallSeedVo.getMallType()) > 0 && leaseDaysMill < comMallSeedVo.getMaturity()) {
                return Result.of(null, false, ResultEnum.SEED_LAND_TIME_ERROR.getMessage(), ResultEnum.SEED_LAND_TIME_ERROR.getCode());
            }
            //[xst] 需要判断种子和土地类型是否匹配
            if (comMallSeedVo.getMallType().equals(comPlayerLand.getMallType()) == false) {
                return Result.of(null, false, ResultEnum.SEED_NO_LAND_ERROR.getMessage(), ResultEnum.SEED_NO_LAND_ERROR.getCode());
            }

            //todo 背包种子减去 土地当前的倍数，需要多倍播种，即消耗多个种子
            ComPlayerGoods comPlayerGoodsSimpleVo = comPlayerGoodsService.findByUserIdAndIndexAndType(userId, comMallSeedVo.getHarvestId(), 0);
            //先拿到一个 before
            Integer _beforeAmount = comPlayerGoodsSimpleVo.getAmount();
            //操作一个种子的倍数
            if (comPlayerGoodsSimpleVo.getAmount() < count || count > 500 || count < 0) {
                return Result.of(null, false, ResultEnum.PLAYER_GOODS_SEEDS_AMOUNT_ERROR.getMessage(), ResultEnum.PLAYER_GOODS_SEEDS_AMOUNT_ERROR.getCode());

            } else if (comPlayerGoodsSimpleVo.getAmount().equals(count)) {
                //数量一样清除背包数据
                comPlayerGoodsService.delete(comPlayerGoodsSimpleVo.getGoodsId());
            } else {
                //_beforeAmount = comPlayerGoodsSimpleVo.getAmount();
                //否则减去土地倍数
                comPlayerGoodsSimpleVo.setAmount(comPlayerGoodsSimpleVo.getAmount() - count);
                ComPlayerGoodsVo comPlayerGoodsVo = CopyUtil.copy(comPlayerGoodsSimpleVo, ComPlayerGoodsVo.class);
                comPlayerGoodsService.save(comPlayerGoodsVo);
            }

            //todo 种植
            comPlayerLand.setIsPlant(1);
            //记录一个植物的种植id
            comPlayerLand.setPlantId(seedId);
            comPlayerLand.setPlantStart(new Date());
            //种植天数,成熟天数
            comPlayerLand.setPlantMature(comMallSeedVo.getMaturity());

            //生成一个标识,用来识别种植
            comPlayerLand.setPlantFlag(UUIDUtil.getUUID());

            //重新种植后，重新设置一个可以偷的标识
            comPlayerLand.setPlantSteal(1);

            //comPlayerLand.setLandDescribe();
            ComPlayerLandVo comPlayerLandVo = CopyUtil.copy(comPlayerLand, ComPlayerLandVo.class);
            comPlayerLandService.save(comPlayerLandVo);

            //todo 记录一个种植 操作信息
            ComPlayerLogVo _playerLogVo = new ComPlayerLogVo();
            _playerLogVo.setUserId(userId);
            _playerLogVo.setTId(comMallSeedVo.getId());
            _playerLogVo.setTName(comMallSeedVo.getName());
            _playerLogVo.setTType(1);//设置一个操作种子的id
            _playerLogVo.setTAmount(comPlayerLand.getLeaseMultiple());
            //交易后的数据
            _playerLogVo.setBeforeAmount(_beforeAmount);
            Integer _afterAmount = _beforeAmount - comPlayerLand.getLeaseMultiple();
            _afterAmount = _afterAmount < 0 ? 0 : _afterAmount;
            _playerLogVo.setAfterAmount(_afterAmount);
            _playerLogVo.setLMultiple(comPlayerLand.getLeaseMultiple());

            //收取时候信息记录
            _playerLogVo.setTPart(0d);
            _playerLogVo.setTLoss(0d); //损失的部分
            _playerLogVo.setBeforePart(0d);
            _playerLogVo.setAfterPart(0d);
            comPlayerLogService.save(_playerLogVo);

            ComPlayerLandAndPlantVo comPlayerLandAndPlantVo = CopyUtil.copy(comPlayerLand, ComPlayerLandAndPlantVo.class);
            comPlayerLandAndPlantVo.setSeedInfo(comMallSeedVo);

            //todo 返回一个计算的天数和小时，解决跨时区的问题
            //土地时间
            //租赁的总时间 = 租赁时间 - 土地数据的创建时间
            Long leaseAllMill = comPlayerLandAndPlantVo.getLeaseTime().getTime() - comPlayerLandAndPlantVo.getCreateTime().getTime();
            Integer allDays = DateUtil.getDays(leaseAllMill).intValue() <= 0 ? 0 : DateUtil.getDays(leaseAllMill).intValue();
            comPlayerLandAndPlantVo.setLeaseDays(allDays);
            //租赁的剩余天数
            Integer leaseDays = DateUtil.getDays(leaseDaysMill).intValue() <= 0 ? 0 : DateUtil.getDays(leaseDaysMill).intValue();
            comPlayerLandAndPlantVo.setLeaseDaysRemaining(leaseDays);

            //返回一个租赁时间毫秒
            comPlayerLandAndPlantVo.setLeaseDaysMill(leaseDaysMill);

            //种子时间
            //当前时间 > 种植时间+成熟期  = 说明可以收获了
            //获取当前时间 - 植物的成熟期 = 收获时间，收获时间 >= 种植时间，即可以收获
            Date _harvestTime = DateUtil.getNowDateMinusDay(comMallSeedVo.getMaturity());
            // 两个时间差, 逻辑是_harvestTime 时间慢慢接近种植时间
            long diff = comPlayerLandAndPlantVo.getPlantStart().getTime() - _harvestTime.getTime();
            //种植的剩余时间毫秒
            comPlayerLandAndPlantVo.setPlantDaysMill(diff);

            if (diff <= 0) {
                //说明可以收获了
                comPlayerLandAndPlantVo.setPlantDaysRemaining(0);
                comPlayerLandAndPlantVo.setPlantHoursRemaining(0);
            } else {
                comPlayerLandAndPlantVo.setPlantDaysRemaining(DateUtil.getDays(diff).intValue());
                comPlayerLandAndPlantVo.setPlantHoursRemaining(DateUtil.getHours(diff).intValue());
            }
            return Result.of(comPlayerLandAndPlantVo);

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
