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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.CacheConstants;
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.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.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 等级配置表 服务实现类
 */
@Service
public class BdGradeServiceImpl extends ServiceImpl<BdGradeMapper, BdGrade> implements IBdGradeService {

    @Autowired
    private IBdGradeScopeService iBdGradeScopeService;
    @Autowired
    private IBdBonusExpandService iBdBonusExpandService;
    @Autowired
    private RedisService redisService;

    @DubboReference
    ITransactionServiceApi iTransactionServiceApi;

    @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) {
        LambdaQueryWrapper<BdGrade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdGrade::getPkCountry, pkCountry);
        queryWrapper.eq(BdGrade::getGradeValue, gradeValue);
        queryWrapper.orderByAsc(BdGrade::getStartValue);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<BdGrade> queryGradeConfigByCondition(Integer pkCountry) {
        LambdaQueryWrapper<BdGrade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdGrade::getPkCountry, pkCountry);
        queryWrapper.eq(BdGrade::getEnableState, EnableStatus.ENABLE.getValue());
        queryWrapper.le(BdGrade::getGradeValue, EGrade.S_VIP.getValue());
        queryWrapper.orderByDesc(BdGrade::getGradeValue);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<BdGrade> queryHaiFunGradeConfigByCondition(Integer pkCountry) {
        LambdaQueryWrapper<BdGrade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdGrade::getPkCountry, pkCountry);
        queryWrapper.eq(BdGrade::getEnableState, EnableStatus.ENABLE.getValue());
        queryWrapper.le(BdGrade::getGradeValue, EGrade.HAI_FAN.getValue());
        queryWrapper.orderByDesc(BdGrade::getGradeValue);
        return baseMapper.selectList(queryWrapper);
    }

    @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());
            LambdaQueryWrapper<BdGrade> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BdGrade::getGradeValue, value.getValue());
            List<BdGrade> list = baseMapper.selectList(queryWrapper);
            if (CollectionUtil.isEmpty(list)) {
                baseMapper.insert(grade);
            }
        }
        return true;
    }

    @Override
    public boolean saveBdGrade(BdGradeExt gradeExt) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        LambdaQueryWrapper<BdGrade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdGrade::getPkCountry, pkCountry);
        queryWrapper.eq(BdGrade::getGradeValue, 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());
                    iBdGradeScopeService.save(gradeScope);
                }
            }
        }
        return true;
    }

    @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();
        LambdaUpdateWrapper<BdGradeScope> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BdGradeScope::getPkGrade, gradeExt.getPkId());
        updateWrapper.set(BdGradeScope::getDelFlag, EYesNo.NO.getIntValue());
        iBdGradeScopeService.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());
                iBdGradeScopeService.save(gradeScope);
            }
        }
        return true;
    }

    @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());
                iBdBonusExpandService.save(bee);
            } else {
                bee.setPkModified(SecurityUtils.getUserId());
                bee.setModifiedTime(new Date());
                iBdBonusExpandService.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> queryRetailGrade() {
        QueryWrapper<BdGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("PK_ID,GRADE_VALUE,GRADE_NAME,BOX_NUMBER,BOX_TOTAL,BOX_SMALL_TOTAL,BUY_PRICE,ALGEBRA,FIRST_ALGEBRA,SECOND_ALGEBRA,THIRD_ALGEBRA");
        queryWrapper.eq("SYSTEM_TYPE", ESystemType.DEFAULT.getValue());
        queryWrapper.orderByAsc("GRADE_VALUE");
        return baseMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateGrade(Long pkId, Long userId) {
        LambdaUpdateWrapper<BdGrade> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BdGrade::getPkId, pkId);
        updateWrapper.set(BdGrade::getDelFlag, EDelFlag.DELETE.getValue());
        updateWrapper.set(BdGrade::getPkModified, userId);
        updateWrapper.set(BdGrade::getModifiedTime, new Date());
        baseMapper.update(null, updateWrapper);
        redisService.deleteObjectByKey(CacheConstants.BD_GRADE + pkId);
        LambdaUpdateWrapper<BdGradeScope> gradeScope = new LambdaUpdateWrapper<>();
        gradeScope.eq(BdGradeScope::getPkGrade, pkId);
        gradeScope.set(BdGradeScope::getDelFlag, EDelFlag.DELETE.getValue());
        gradeScope.set(BdGradeScope::getPkModified, userId);
        gradeScope.set(BdGradeScope::getModifiedTime, new Date());
        iBdGradeScopeService.update(gradeScope);
        return true;
    }

    @Override
    public List<BdGrade> selectGradeAll(Integer pkCountry) {
        LambdaQueryWrapper<BdGrade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdGrade::getPkCountry, pkCountry);
        queryWrapper.eq(BdGrade::getEnableState, EnableStatus.ENABLE.getValue());
        queryWrapper.orderByAsc(BdGrade::getGradeValue);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public BdGrade getLastGrade(BigDecimal achieve, Integer pkCountry) {
        return baseMapper.getLastGrade(achieve, pkCountry);
    }

}
