package cn.pluss.platform.level.impl;

import cn.hutool.core.date.DateUtil;
import cn.pluss.platform.dict.DictService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.jft.JftAuditService;
import cn.pluss.platform.level.ExtraLevelBenefitService;
import cn.pluss.platform.level.LevelOperateRecordService;
import cn.pluss.platform.mapper.LevelOperateRecordMapper;
import cn.pluss.platform.user.UserLevelService;
import cn.pluss.platform.userApp.UserAppService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 等级变更记录表 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2022-02-08
 */
@Service
public class LevelOperateRecordServiceImpl extends ServiceImpl<LevelOperateRecordMapper, LevelOperateRecord> implements LevelOperateRecordService {

    @Autowired
    private DictService dictService;

    @Autowired
    private UserAppService uaService;

    @Autowired
    private ExtraLevelBenefitService extraLevelBenefitService;

    @Autowired
    private JftAuditService jftAuditService;

    @Autowired
    private UserLevelService ulService;

    @Override
    public Map<String, Object> apiLevelBound(String userId) {
        LambdaQueryWrapper<UserApp> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(UserApp::getUserId, userId);
        UserApp chosenUa = uaService.getOne(qWrapper);
        UserApp tokenUa = uaService.queryUserAppByToken();

        String minLevel = (Integer.parseInt(chosenUa.getLevelCode().replace("LV", "")) + 1) + "";
        int maxLevelInt = Integer.parseInt(tokenUa.getLevelCode().replace("LV", "")) - 1;
        if (maxLevelInt == 9) {
            maxLevelInt = 8;
        }

        String maxLevel = maxLevelInt + "";

        Map<String, Object> result = new HashMap<>(4);
        result.put("minLevel", minLevel);
        result.put("maxLevel", maxLevel);

        return result;
    }

    @Override
    public Map<String, Object> apiLevelBenefitData() {
        UserApp tokenUa = uaService.queryUserAppByToken();
        return levelData(tokenUa);
    }

    @Override
    public Map<String, Object> levelData(UserApp ua) {
        Dict dictCondition = new Dict();
        dictCondition.setName(ua.getLevelCode());
        Dict levelDict = dictService.getByCode("TEAM_LEVEL_COUNT", dictCondition);

        Map<String, Object> result = new HashMap<>();
        if (levelDict == null) {
            result.put("levelMax", "0");
            result.put("levelLeft", "0");
            result.put("extraMax", "0");
            result.put("extraLeft", "0");

            return result;
        }

        result.put("levelMax", levelDict.getValue());

        // 查询当月已经修改等级的个数
        String currentMonth = DateUtil.format(new Date(), "yyyy-MM");
        QueryWrapper<LevelOperateRecord> qWrapper3 = new QueryWrapper<>();
        qWrapper3.eq("operator", ua.getUserId());
        qWrapper3.eq("createMonth", currentMonth);
        qWrapper3.select("DISTINCT userId");
        Integer count = baseMapper.selectCount(qWrapper3);

        if (count > Integer.parseInt(levelDict.getValue())) {
            result.put("levelLeft", "0");
        } else {
            result.put("levelLeft", (Integer.parseInt(levelDict.getValue()) - count) + "");
        }

        LambdaQueryWrapper<ExtraLevelBenefit> qWrapper2 = new LambdaQueryWrapper<>();
        qWrapper2.eq(ExtraLevelBenefit::getUserId, ua.getUserId());
        ExtraLevelBenefit one = extraLevelBenefitService.getOne(qWrapper2);

        if (one == null) {
            result.put("extraMax", "0");
            result.put("extraLeft", "0");
        } else {
            result.put("extraMax", one.getMaxCount() + "");
            result.put("extraLeft", (one.getMaxCount() - one.getUseCount()) + "");
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apiChangeLevel(long userId, String level) {
        UserApp tokenUa = uaService.queryUserAppByToken();
        LambdaQueryWrapper<UserApp> qWrapper = new LambdaQueryWrapper<>();
        qWrapper.eq(UserApp::getUserId, userId);
        UserApp ua = uaService.getOne(qWrapper);

        if (!Objects.equals(ua.getParentId(), tokenUa.getUserId())) {
            throw new MsgException("拒绝访问");
        }

        if (!Objects.equals(ua.getStatus(), 3) || !Objects.equals(ua.getBankStatus(), 3)) {
            throw new MsgException("请该用户实名再进行操作");
        }

        if (level == null || (!level.startsWith("LV") && !level.startsWith("VIP"))) {
            throw new MsgException("等级参数格式错误");
        }

        String minLevelStr = (Integer.parseInt(ua.getLevelCode().replace("LV", "")) + 1) + "";
        int maxLevelInt = Integer.parseInt(tokenUa.getLevelCode().replace("LV", "")) - 1;
        if (maxLevelInt == 9) {
            maxLevelInt = 8;
        }

        String maxLevelStr = maxLevelInt + "";
        String newLevelStr = level.replaceAll("LV|VIP", "");

        if (Integer.parseInt(maxLevelStr) < Integer.parseInt(newLevelStr)
                || Integer.parseInt(newLevelStr) < Integer.parseInt(minLevelStr)) {
            throw new MsgException("等级应设置在VIP" + minLevelStr + "到VIP" + maxLevelStr + "之间");
        }

        LambdaQueryWrapper<LevelOperateRecord> qWrapper4 = new LambdaQueryWrapper<>();
        qWrapper4.eq(LevelOperateRecord::getUserId, userId).eq(LevelOperateRecord::getOperator, tokenUa.getUserId());
        qWrapper4.eq(LevelOperateRecord::getFlag, "1");
        LevelOperateRecord currentHistoryOperateRecord = baseMapper.selectOne(qWrapper4);

        // 如果当月没有修改过，需要检查是否有剩余名额
        if (currentHistoryOperateRecord == null) {
            // 查询当月已经修改等级的个数
            String currentMonth = DateUtil.format(new Date(), "yyyy-MM");
            LambdaQueryWrapper<LevelOperateRecord> qWrapper3 = new LambdaQueryWrapper<>();
            qWrapper3.eq(LevelOperateRecord::getOperator, tokenUa.getUserId());
            qWrapper3.eq(LevelOperateRecord::getCreateMonth, currentMonth);
            qWrapper3.eq(LevelOperateRecord::getFlag, "1");
            Integer count = baseMapper.selectCount(qWrapper3);

            Dict dictCondition = new Dict();
            dictCondition.setName(tokenUa.getLevelCode().replace("VIP", "LV"));
            Dict levelDict = dictService.getByCode("TEAM_LEVEL_COUNT", dictCondition);

            int monthCount = Integer.parseInt(levelDict.getValue());

            // 如果月免费个数已经消耗完毕
            if (monthCount < count) {
                LambdaQueryWrapper<ExtraLevelBenefit> qWrapper2 = new LambdaQueryWrapper<>();
                qWrapper2.eq(ExtraLevelBenefit::getUserId, tokenUa.getUserId());
                ExtraLevelBenefit one = extraLevelBenefitService.getOne(qWrapper2);

                if (one == null) {
                    throw new MsgException("当前没有修改下级等级额度");
                } else {
                    if (one.getMaxCount() <= one.getUseCount()) {
                        throw new MsgException("当前没有修改下级等级额度");
                    }
                }

                one.setUseCount(one.getUseCount() + 1);
                extraLevelBenefitService.updateById(one);
            }

            changeLevel(tokenUa.getUserId(), ua.getUserId(), level, "1");
        } else {
            changeLevel(tokenUa.getUserId(), ua.getUserId(), level, "0");
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeLevel(long operator, long userId, String level, String flag) {
        LevelOperateRecord levelOperateRecord = new LevelOperateRecord();
        levelOperateRecord.setLevelCode(level);
        levelOperateRecord.setOperator(operator);
        levelOperateRecord.setUserId(userId);
        levelOperateRecord.setFlag(flag);
        baseMapper.insert(levelOperateRecord);

        LambdaQueryWrapper<UserApp> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(UserApp::getUserId, userId);
        UserApp one = uaService.getOne(qWrapper);
        if ("LL".equals(one.getUserType())) {
            throw new MsgException("该商户类型禁止该操作");
        }

        String newLevel = level.replace("VIP", "LV");
        one.setLevelCode(newLevel);
        uaService.updateById(one);

        UserLevel userLevel = ulService.getLevelInfoByRoleLevel(one.getUserType(), newLevel);
        if (userLevel != null) {
            jftAuditService.changeRate(userId, userLevel.getJftRate());
        }
    }
}
