package com.hzs.system.config.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.common.domain.system.config.BdGradeScope;
import com.hzs.common.domain.system.config.ext.BdBonusExpandExt;
import com.hzs.common.domain.system.config.ext.BdGradeExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.config.mapper.BdGradeMapper;
import com.hzs.system.config.service.IBdBonusExpandService;
import com.hzs.system.config.service.IBdGradeScopeService;
import com.hzs.system.config.service.IBdGradeService;
import org.apache.dubbo.config.annotation.DubboReference;
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.List;

/**
 * <p>
 * 等级配置表 服务实现类
 * </p>
 *
 * @author zhangjing
 * @since 2022-09-08
 */
@Service
public class BdGradeServiceImpl extends ServiceImpl<BdGradeMapper, BdGrade> implements IBdGradeService {

    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;
    private RedisService redisService;
    @Autowired
    IBdGradeScopeService gradeScopeService;
    @Autowired
    IBdBonusExpandService bonusExpandService;

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public BdGrade getBdGrade(Integer pkId) {
        BdGrade bdGrade = redisService.getCacheObject(CacheConstants.BD_GRADE + pkId);
        if (bdGrade == null) {
            bdGrade = baseMapper.selectById(pkId);
            if (bdGrade != null) {
                redisService.setCacheObject(CacheConstants.BD_GRADE + pkId, bdGrade);
            }
        }
        return bdGrade;
    }

    @Override
    public BdGrade getGradeByGradeValue(Integer gradeValue, Integer pkCountry) {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.eq(SystemFieldConstants.GRADE_VALUE, gradeValue);
        queryWrapper.orderByAsc(SystemFieldConstants.START_VALUE);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<BdGrade> queryGradeConfigByCondition(Integer pkCountry) {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.eq("ENABLE_STATE", EnableStatus.ENABLE.getValue());
        queryWrapper.le(SystemFieldConstants.GRADE_VALUE, EGrade.S_VIP.getValue());
        queryWrapper.orderByDesc(SystemFieldConstants.GRADE_VALUE);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<BdGrade> queryHaiFunGradeConfigByCondition(Integer pkCountry) {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.eq("ENABLE_STATE", EnableStatus.ENABLE.getValue());
//        queryWrapper.le(SystemFieldConstants.GRADE_VALUE, EGrade.HAI_FAN.getValue());
        queryWrapper.orderByDesc(SystemFieldConstants.GRADE_VALUE);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * @description: 生成等级配置
     * @author: zhang jing
     * @date: 2022/10/18 16:43
     * @param: [grade]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean generate(BdGrade grade) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        for (EGrade value : EGrade.values()) {
            grade.setGradeName(value.getLabel());
            grade.setGradeValue(value.getValue());
            //字段翻译保存到数据库
            R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.GRADE,
                    value.getLabel(), EYesNo.YES, EYesNo.NO);
            grade.setPkTransaction(pkTransaction.getData());
            grade.setCensusValue(grade.getCensusValue());
            grade.setPkCountry(SecurityUtils.getPkCountry());
            grade.setPkCreator(SecurityUtils.getUserId());
            grade.setCreationTime(new Date());
            QueryWrapper<BdGrade> queryWrapper = new QueryWrapper();
            queryWrapper.eq("GRADE_VALUE", value.getValue());
            List<BdGrade> list = baseMapper.selectList(queryWrapper);
            if (CollectionUtil.isEmpty(list)) {
                baseMapper.insert(grade);
            }
        }
        return true;
    }

    /**
     * @description: 新增等级配置+增加等级（推荐）范围
     * @author: zhang jing
     * @date: 2022/10/26 11:58
     * @param: [gradeExt]
     * @return: boolean
     **/
    @Override
    public boolean saveBdGrade(BdGradeExt gradeExt) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", pkCountry);
        queryWrapper.eq("GRADE_VALUE", gradeExt.getGradeValue());
        List<BdGrade> list = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            //字段翻译保存到数据库
            R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.GRADE,
                    gradeExt.getGradeName(), EYesNo.YES, EYesNo.NO);
            gradeExt.setPkTransaction(pkTransaction.getData());
            baseMapper.insert(gradeExt);
            Integer gradeRang[] = gradeExt.getGradeRang();
            if (gradeRang.length > 0) {
                for (Integer integer : gradeRang) {
                    BdGradeScope gradeScope = new BdGradeScope();
                    gradeScope.setPkGrade(gradeExt.getPkId());
                    gradeScope.setPkScope(integer);
                    gradeScope.setPkCountry(SecurityUtils.getPkCountry());
                    gradeScope.setPkCreator(SecurityUtils.getUserId());
                    gradeScope.setCreationTime(new Date());
                    gradeScopeService.save(gradeScope);
                }
            }
        }
        return true;
    }

    /**
     * @description: 修改等级配置+增加等级（推荐）范围
     * @author: zhang jing
     * @date: 2022/10/26 14:00
     * @param: [gradeExt]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBdGrade(BdGradeExt gradeExt) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //字段翻译保存到数据库
        if(null!=gradeExt.getPkTransaction()){
            iTransactionServiceApi.updateTransaction(pkCountry,
                    gradeExt.getGradeName(), gradeExt.getPkTransaction(), true);
        }else{
            //字段翻译保存到数据库
            R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(pkCountry, ETransactionKey.GRADE,
                    gradeExt.getGradeName(), EYesNo.YES, EYesNo.NO);
            gradeExt.setPkTransaction(pkTransaction.getData());
        }
        baseMapper.updateById(gradeExt);
        Integer gradeRang[] = gradeExt.getGradeRang();
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("PK_GRADE", gradeExt.getPkId());
        updateWrapper.set("DEL_FLAG", EYesNo.NO.getIntValue());
        gradeScopeService.update(updateWrapper);
        if (gradeRang.length > 0) {
            for (Integer integer : gradeRang) {
                BdGradeScope gradeScope = new BdGradeScope();
                gradeScope.setPkGrade(gradeExt.getPkId());
                gradeScope.setPkScope(integer);
                gradeScope.setPkCountry(SecurityUtils.getPkCountry());
                gradeScope.setPkCreator(SecurityUtils.getUserId());
                gradeScope.setCreationTime(new Date());
                gradeScopeService.save(gradeScope);
            }
        }
        return true;
    }

    /**
     * @description: 修改拓展信息
     * @author: zhang jing
     * @date: 2022/10/31 16:46
     * @param: [gradeExt]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateExpand(BdGradeExt gradeExt) {
        //添加或修改4-N配置
        for (BdBonusExpandExt bee : gradeExt.getBonusExpands()) {
            bee.setPkCountry(SecurityUtils.getPkCountry());
            if (StringUtils.isNull(bee.getPkId())) {
                bee.setPkCreator(SecurityUtils.getUserId());
                bee.setCreationTime(new Date());
                bonusExpandService.save(bee);
            } else {
                bee.setPkModified(SecurityUtils.getUserId());
                bee.setModifiedTime(new Date());
                bonusExpandService.updateById(bee);
            }
        }
        //修改拓展信息
        for (BdGrade bg : gradeExt.getExpandList()) {
            bg.setPkCountry(SecurityUtils.getPkCountry());
            bg.setPkModified(SecurityUtils.getUserId());
            bg.setModifiedTime(new Date());
            baseMapper.updateById(bg);
        }
        return true;
    }

    @Override
    public List<BdGrade> queryBdGrade() {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper<>();
        String sql = "PK_ID,GRADE_VALUE,FIRST_CALCULATE,FIRST_ASSESS,EXPAND_CAPPING,EXPAND_RATIO,"
                + "REPURCHASE_CALCULATE,REPURCHASE_ASSESS,REPURCHASE_CAPPING,REPURCHASE_RATIO,PK_COUNTRY,"
                + "PUSH_RATIO,ALGEBRA,SEE_POINT_RATIO,RENEW_AMOUNT,TOUCH_PV,TOUCH_BONUS";
        queryWrapper.select(sql);
        queryWrapper.orderByAsc("GRADE_VALUE");
        return baseMapper.selectList(queryWrapper);
    }


    /**
     * @description: 删除等级配置
     * @author: zhang jing
     * @date: 2023/4/22 14:30
     * @param: [pkId]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateGrade(Long pkId) {
        UpdateWrapper<BdGrade> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_ID", pkId);
        updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        updateWrapper.set("PK_MODIFIED", SecurityUtils.getUserId());
        updateWrapper.set("MODIFIED_TIME", new Date());
        baseMapper.update(null,updateWrapper);
        redisService.deleteObjectByKey(CacheConstants.BD_GRADE + pkId);
        UpdateWrapper<BdGradeScope> gradeScope = new UpdateWrapper<>();
        gradeScope.eq("PK_GRADE",pkId);
        gradeScope.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        gradeScope.set("PK_MODIFIED", SecurityUtils.getUserId());
        gradeScope.set("MODIFIED_TIME", new Date());
        gradeScopeService.update(gradeScope);
        return true;
    }
    /**
     * 查询全部等级列表数据
     * @param pkCountry
     * @return
     */
    @Override
    public List<BdGrade> selectGradeAll(Integer pkCountry) {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.eq("ENABLE_STATE", EnableStatus.ENABLE.getValue());

        queryWrapper.orderByAsc(SystemFieldConstants.GRADE_VALUE);

        return baseMapper.selectList(queryWrapper);
    }
    /**
     * 根据国家查询等级配置列表
     * @param pkCountry 国家
     * @return: R<List<AreaCurrencyDTO>>
     * @Author: sui q
     * @Date: 2022/9/6 10:37
     */
    @Override
    public List<BdGrade> queryGrowUpFootmarkGrade(Integer pkCountry) {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.eq("ENABLE_STATE", EnableStatus.ENABLE.getValue());
        queryWrapper.le(SystemFieldConstants.GRADE_VALUE, EGrade.S_VIP.getValue());
        queryWrapper.orderByAsc(SystemFieldConstants.GRADE_VALUE);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据国家查询等级配置列表
     * @param pkCountry 国家
     * @return: R<List<AreaCurrencyDTO>>
     * @Author: sui q
     * @Date: 2022/9/6 10:37
     */
    @Override
    public List<BdGrade> queryNextGrade(Integer pkCountry) {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SystemFieldConstants.PK_COUNTRY, pkCountry);
        queryWrapper.eq("ENABLE_STATE", EnableStatus.ENABLE.getValue());
        queryWrapper.orderByAsc(SystemFieldConstants.GRADE_VALUE);
        return baseMapper.selectList(queryWrapper);
    }
}
