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

import com.alibaba.fastjson.JSONObject;
import com.td.boss.common.controller.*;
import com.td.boss.common.pojo.Result;
import com.td.boss.config.enums.ResultEnum;
import com.td.boss.game.commallseed.pojo.ComMallSeed;
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.ComPlayerGoodsSimpleVo;
import com.td.boss.game.complayergoods.vo.ComPlayerGoodsVo;
import com.td.boss.game.complayerlog.pojo.ComPlayerLog;
import com.td.boss.game.complayerlog.service.ComPlayerLogService;
import com.td.boss.game.complayerlog.vo.ComPlayerLogVo;
import com.td.boss.game.complayers.controller.ComPlayersController;
import com.td.boss.game.complayers.pojo.ComPlayers;
import com.td.boss.game.complayers.service.ComPlayersService;
import com.td.boss.game.comsnbtran.service.ComSnbTranService;
import com.td.boss.game.comsnbtran.vo.ComSnbTranVo;
import com.td.boss.game.comusers.service.ComUsersService;
import com.td.boss.game.comusers.vo.ComUsersVo;
import com.td.boss.util.CopyUtil;
import com.td.boss.util.RedisData;
import com.td.boss.util.RedisLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/game/comMallSeed/")
public class ComMallSeedController extends CommonController<ComMallSeedVo, ComMallSeed, Integer> {
    @Autowired
    private ComMallSeedService comMallSeedService;

    @Autowired
    private ComPlayerGoodsService comPlayerGoodsService;

    @Autowired
    private ComUsersService comUsersService;

    @Autowired
    private ComSnbTranService comSnbTranService;

    @Autowired
    private ComPlayerLogService comPlayerLogService;

    @Autowired
    private ComPlayersService comPlayersService;

    @Autowired
    private RedisLock redisLock;
    /**
     * 获取商城种子
     *
     * @param userId
     * @return
     */
    @GetMapping("getMallSeed")
    public Result<List<ComMallSeedVo>> getSNBFunction(@RequestParam(value = "userId") String userId) {
        //log.info(userId);
        ComMallSeedVo comMallSeedVo = new ComMallSeedVo();
        Result result = comMallSeedService.list(comMallSeedVo);
        return result;
    }

    /**
     * 神农呗购买种子
     *
     * @param userId
     * @return
     */
    @PostMapping("snbBuySeeds")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<Map> snbBuySeedsFunction(
            @RequestParam(value = "userId") String userId,
            @RequestParam(value = "payAmount") Integer payAmount,
            @RequestParam(value = "seedId") Integer seedId
    ) {

        // 处理itemType,种子id ,获取种子类型，设置种子不同的数据
        Integer itemType = seedId;
        ComMallSeedVo seedVo = comMallSeedService.findById(seedId);
        Map map = new HashMap();
        if (seedVo == null) {

            map.put("msg", "非法操作:所修改的种子不存在服务器中!");
            //return Result.of(map);
            return Result.of(map, false, ResultEnum.SEED_DATA_ERROR.getMessage(), ResultEnum.SEED_DATA_ERROR.getCode());
        }
        if (!StringUtils.hasText(payAmount.toString())||payAmount.equals(0) || payAmount % seedVo.getPriceSnb() != 0 ) {
            //支付价格不能为零，如果价格 不和种子相当，也不是种子的倍数，也是不行的
            map.put("msg", "订单非法操作，已记录相关信息！");
            //return Result.of(map);
            return Result.of(map, false, ResultEnum.SEED_PLAY_ERROR.getMessage(), ResultEnum.SEED_PLAY_ERROR.getCode());
        }

        //todo snb冻结加锁
        long time = System.currentTimeMillis() + RedisData.getSnbTimeout();
        String _redisKey = "SNB_SAVE_" + userId;

        try{
            //todo snb冻结加锁
            if (!redisLock.lock(_redisKey, String.valueOf(time))) {
                return Result.of(null, false, ResultEnum.SEED_SALE_SAVE_LOCK.getMessage(), ResultEnum.SEED_SALE_SAVE_LOCK.getCode());
            }

            //todo 操作snb数量
            ComUsersVo comUsersVo = comUsersService.findByUserId(userId);
            if (comUsersVo.getSnb() < payAmount) {
                map.put("msg", "账户snb不足");
                //WALLET_SNB_INSUFFICIENT_QUANTITY(602,"snb不足以支付！")
                return Result.of(map, false, ResultEnum.WALLET_SNB_INSUFFICIENT_QUANTITY.getMessage(), ResultEnum.WALLET_SNB_INSUFFICIENT_QUANTITY.getCode());
            }
            //如果数量够，写入修改对应操作
            Integer _oldSnb = comUsersVo.getSnb();
            Integer _snb = comUsersVo.getSnb() - payAmount;
            comUsersVo.setSnb(_snb);
            comUsersService.save(comUsersVo);

            //合法操作记录到仓库中
            ComPlayerGoods entityVo = comPlayerGoodsService.findByUserIdAndIndexAndType(userId, itemType, 0);
            //这里计算一个购买种子的数量，用种子除去单价
            int _paySeedAmount = (int) (payAmount / seedVo.getPriceSnb());
            if (entityVo == null) {
                //创建一个新种子
                entityVo = new ComPlayerGoods();
                entityVo.setGoodsIndex(itemType);
                entityVo.setGoodsType(0);
                entityVo.setAmount(_paySeedAmount);
                entityVo.setAmountPart(0d);
                entityVo.setName(seedVo.getName());
                entityVo.setPictureName(seedVo.getPicture());
                entityVo.setUserId(userId);
            } else {
                Integer _amount = entityVo.getAmount() + _paySeedAmount;
                entityVo.setAmount(_amount);
            }
            /** 购买成功后，记录到仓库中*/
            ComPlayerGoodsVo comPlayerGoodsVo = CopyUtil.copy(entityVo, ComPlayerGoodsVo.class);
            comPlayerGoodsService.save(comPlayerGoodsVo);

            /**
             * todo 购买种子的交易记录
             */
            ComSnbTranVo _snbTran = new ComSnbTranVo();
            //记录兑换id
            _snbTran.setTranId(itemType.toString());
            _snbTran.setUserId(userId);
            _snbTran.setTranName("使用SNB购买种子");
            _snbTran.setTranType(3);
            _snbTran.setTranAmount(_paySeedAmount); //此数量会操作背包记录
            _snbTran.setTranPrice(payAmount);
            _snbTran.setTranDescribe("SNB购买种子的价格:"+seedVo.getPriceSnb()+"，支付金额:"+payAmount);
            _snbTran.setIsAdd(0);//减少snb
            _snbTran.setBeforeSnb(_oldSnb);
            _snbTran.setTranSnb(payAmount);
            _snbTran.setAfterSnb(_snb);
            //不涉及交易的设置为0
            _snbTran.setTranAmountPart(0d);
            _snbTran.setTranSnbPart(0d);
            _snbTran.setBeforeSnbPart(comUsersVo.getSnbPart());
            _snbTran.setAfterSnbPart(comUsersVo.getSnbPart());
            comSnbTranService.save(_snbTran);

            redisLock.unlock(_redisKey, String.valueOf(time));
            map.put("seed", entityVo.getGoodsIndex());
            map.put("snb",comUsersVo.getSnb());
            return Result.of(map);
        }catch (Exception e) {
            redisLock.unlock(_redisKey, String.valueOf(time));
            throw new RuntimeException(e.getMessage());
        }

    }



    /**
     * 用钻石兑换一份辣椒种子
     *
     * @param userId
     * @return
     */
    @PostMapping("exchangeSeeds")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result<Map> exchangeSeedsFunction(
            @RequestParam(value = "userId") String userId,
            @RequestParam(value = "diamondAmount") Integer diamondAmount,
            @RequestParam(value = "seedId") Integer seedId
    ) {
        // 处理itemType,种子id ,获取种子类型，设置种子不同的数据
        Integer itemType = seedId;
        ComMallSeedVo seedVo = comMallSeedService.findById(seedId);
        Map map = new HashMap();
        if (seedVo == null) {
            map.put("msg", "非法操作:所修改的种子不存在服务器中!");
            //return Result.of(map);
            return Result.of(map, false, ResultEnum.SEED_DATA_ERROR.getMessage(), ResultEnum.SEED_DATA_ERROR.getCode());
        }

        ComPlayers player = comPlayersService.findByUserId(userId);
        if(player.getIsExchange().equals(1)){
            map.put("msg", "非法操作:已兑换过种子!");
            return Result.of(map, false, ResultEnum.SEED_IS_EXCHANGE.getMessage(), ResultEnum.SEED_IS_EXCHANGE.getCode());
        }

        JSONObject jsonObject = JSONObject.parseObject(player.getData());
        Integer _diamond = Integer.parseInt(jsonObject.getString("Diamond"));
        if(_diamond<diamondAmount){
            return Result.of(map, false, ResultEnum.SEED_PLAY_DIAMOND_ERROR.getMessage(), ResultEnum.SEED_PLAY_DIAMOND_ERROR.getCode());
        }
        jsonObject.put("Diamond",_diamond - diamondAmount);
        //设置已经兑换的状态
        player.setIsExchange(1);
        //更新游戏状态
        player.setData(jsonObject.toString());
        comPlayersService.addComPlayers(player);
        //合法操作记录到仓库中
        //todo 添加一个辣椒种子
        ComPlayerGoods entityVo = comPlayerGoodsService.findByUserIdAndIndexAndType(userId, itemType, 0);
        Integer _selfBeforeAmount = 0;
        if (entityVo == null) {
            //创建一个新种子
            entityVo = new ComPlayerGoods();
            entityVo.setGoodsIndex(itemType);
            entityVo.setGoodsType(0);
            entityVo.setAmount(1);
            entityVo.setAmountPart(0d);
            entityVo.setName(seedVo.getName());
            entityVo.setPictureName(seedVo.getPicture());
            entityVo.setUserId(userId);
        } else {
            _selfBeforeAmount = entityVo.getAmount();
            Integer _amount = entityVo.getAmount() + 1;
            entityVo.setAmount(_amount);
        }
        /** 购买成功后，记录到仓库中*/
        ComPlayerGoodsVo comPlayerGoodsVo = CopyUtil.copy(entityVo, ComPlayerGoodsVo.class);
        comPlayerGoodsService.save(comPlayerGoodsVo);

        /**
         * todo 记录 PlayerLog
         */
        //当前用户
        ComPlayerLog _selfPlayerLog = new ComPlayerLog();
        _selfPlayerLog.setUserId(userId);
        _selfPlayerLog.setTId(entityVo.getGoodsIndex());
        _selfPlayerLog.setTName(entityVo.getName());
        _selfPlayerLog.setTType(4);//兑换种子
        _selfPlayerLog.setTAmount(1);
        _selfPlayerLog.setBeforeAmount(_selfBeforeAmount);
        ////交易后的数据
        _selfPlayerLog.setAfterAmount(entityVo.getAmount());
        _selfPlayerLog.setLMultiple(0);//收获时候，会有一个倍数
        ComPlayerLogVo _selfPlayerLogVo = CopyUtil.copy(_selfPlayerLog, ComPlayerLogVo.class);
        comPlayerLogService.save(_selfPlayerLogVo);

        map.put("seed", entityVo.getGoodsIndex());
        map.put("playerData",player.getData());
        map.put("isExchange",player.getIsExchange());

        return Result.of(map);
    }

}
