package com.td.WaDa.game.complayerscore.service;

import com.td.WaDa.common.pojo.Result;
import com.td.WaDa.common.service.CommonServiceImpl;
import com.td.WaDa.game.commallseed.service.ComMallSeedService;
import com.td.WaDa.game.commallseed.vo.ComMallSeedVo;
import com.td.WaDa.game.complayergoods.pojo.ComPlayerGoods;
import com.td.WaDa.game.complayergoods.service.ComPlayerGoodsService;
import com.td.WaDa.game.complayergoods.vo.ComPlayerGoodsVo;
import com.td.WaDa.game.complayerscore.pojo.ComPlayerScore;
import com.td.WaDa.game.complayerscore.repository.ComPlayerScoreRepository;
import com.td.WaDa.game.complayerscore.vo.ComPlayerScoreVo;
import com.td.WaDa.game.comusers.service.ComUsersService;
import com.td.WaDa.game.comusers.vo.ComUsersVo;
import com.td.WaDa.util.CopyUtil;
import com.td.WaDa.util.DappUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ComPlayerScoreServiceImpl extends CommonServiceImpl<ComPlayerScoreVo, ComPlayerScore, Integer> implements ComPlayerScoreService {

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private ComPlayerScoreRepository comPlayerScoreRepository;
    @Autowired
    private ComUsersService comUsersService;
    @Autowired
    private ComMallSeedService comMallSeedService;
    @Autowired
    private ComPlayerGoodsService comPlayerGoodsService;

    /**
     * 积分兑换种子
     *
     * @param userId 用户ID
     * @param amount 本次兑换数量
     * @param seedId 种子id
     * @return {@link Result}<{@link String}>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Map> exchange(String userId,
                                   Integer amount,
                                   Integer seedId) {
        ComUsersVo comUsersVo = comUsersService.findByUserId(userId);
        if (comUsersVo == null) {
            return Result.of(null, false, "用户不存在");
        }
        // 链端获取cnt总数
        Integer totalCount = DappUtil.getChildrenBuyLandAmount(userId);
        if (totalCount <= 0) {
            return Result.of(null, false, "消费土地的总cnt不足");
        }
        ComMallSeedVo mallSeed = comMallSeedService.findById(seedId);
        // 固定积分兑换种子,使用的是已存在的种子
        if (mallSeed == null || mallSeed.getAmount().equals(0) || !mallSeed.getMallType().equals(0)) {
            return Result.of(null, false, "种子不存在或已被下架");
        }
        // 本次总消费
        int totalCnt = mallSeed.getPriceCnt() * amount;
        if (totalCnt <= 0) {
            return Result.of(null, false, "种子数据异常");
        }
        if (totalCount < totalCnt) {
            return Result.of(null, false, "消费土地的总cnt不足");
        }
        // 以往兑换消费总cnt
        Integer oldTotalCnt = comPlayerScoreRepository.findAllByUserId(userId).stream()
                .map(ComPlayerScore::getTotalCnt).reduce(0, Integer::sum);
        if (totalCount < oldTotalCnt + totalCnt) {
            return Result.of(null, false, "消费土地的总cnt不足");
        }

        // 记录本次兑换信息
        ComPlayerScore comPlayerScore = new ComPlayerScore();
        comPlayerScore.setUserId(userId);
        comPlayerScore.setTotalCnt(totalCnt);
        comPlayerScore.setAmount(amount);
        comPlayerScore.setPriceCnt(mallSeed.getPriceCnt());
        comPlayerScore.setCreateTime(new Date());
        comPlayerScoreRepository.save(comPlayerScore);
        // 保存进仓库,处理种子

        ComPlayerGoods  comPlayerGoods = comPlayerGoodsService.findByUserIdAndIndexAndType(userId, seedId, 0);
        if(comPlayerGoods == null){
            comPlayerGoods = new ComPlayerGoods();
            comPlayerGoods.setGoodsIndex(seedId);
            comPlayerGoods.setGoodsType(0);
            comPlayerGoods.setUserId(userId);
            comPlayerGoods.setName(mallSeed.getName());
            comPlayerGoods.setPictureName(mallSeed.getPicture());
            comPlayerGoods.setAmount(amount);
            comPlayerGoods.setAmountPart(0d);
            comPlayerGoods.setMallType(0);
        }else{
            Integer _amount = comPlayerGoods.getAmount() + amount;
            comPlayerGoods.setAmount(_amount);
        }
        comPlayerGoodsService.save(CopyUtil.copy(comPlayerGoods,ComPlayerGoodsVo.class));

        Map map = new HashMap();
        map.put("score", getScore(userId));
        return Result.of( map,true, "兑换成功");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map getScore(String userId) {
        // 链端获取cnt总数
        Integer totalCount = DappUtil.getChildrenBuyLandAmount(userId);
        Integer oldTotalCnt = comPlayerScoreRepository.findAllByUserId(userId).stream()
                .map(ComPlayerScore::getTotalCnt).reduce(0, Integer::sum);

        Map map = new HashMap();
        map.put("totalCount",totalCount);
        map.put("oldTotalCnt",oldTotalCnt);
        return map;
    }
}
