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

import cn.hutool.core.bean.BeanUtil;
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.Constants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.domain.system.config.BdRange;
import com.hzs.common.domain.system.config.BdRangeDetails;
import com.hzs.common.domain.system.config.ext.BdRangeExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.config.dto.RangeDTO;
import com.hzs.system.config.mapper.BdRangeMapper;
import com.hzs.system.config.service.IBdRangeDetailsService;
import com.hzs.system.config.service.IBdRangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 极差配置 服务实现类
 * </p>
 *
 * @author zhangjing
 * @since 2022-09-09
 */
@Slf4j
@Service
public class BdRangeServiceImpl extends ServiceImpl<BdRangeMapper, BdRange> implements IBdRangeService {

    @Autowired
    private IBdRangeDetailsService rangeDetailsService;
    @DubboReference
    private ITransactionServiceApi iTransactionServiceApi;

    private RedisService redisService;

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

    /**
     * @description: 新增极差
     * @author: zhang jing
     * @date: 2022/10/28 14:23
     * @param: [rangeExt]
     * @return: boolean
     **/
    @Override
    public boolean saveRange(BdRangeExt rangeExt) {
        //字段翻译保存到数据库
        R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(rangeExt.getPkCountry(), ETransactionKey.RANGE,
                rangeExt.getRangeName(), EYesNo.YES, EYesNo.NO);
        rangeExt.setPkTransaction(pkTransaction.getData());
        QueryWrapper<BdRange> queryWrapper = new QueryWrapper();
        queryWrapper.eq("PK_COUNTRY", rangeExt.getPkCountry());
        queryWrapper.eq("RANGE_VALUE", rangeExt.getRangeValue());
        List<BdRange> list = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            baseMapper.insert(rangeExt);
            List<Integer> gradeList = rangeExt.getGradeList();
            List<Integer> awardsList = rangeExt.getAwardsList();
            //等级
            for (Integer gr : gradeList) {
                BdRangeDetails rangeDetails = new BdRangeDetails();
                rangeDetails.setPkRange(rangeExt.getPkId());
                rangeDetails.setPkLevel(gr);
                rangeDetails.setRangeType(ERangeType.GRADE.getValue());
                rangeDetails.setPkCountry(SecurityUtils.getPkCountry());
                rangeDetails.setPkCreator(SecurityUtils.getUserId());
                rangeDetails.setCreationTime(new Date());
                rangeDetailsService.save(rangeDetails);
            }
            //奖衔
            for (Integer aw : awardsList) {
                BdRangeDetails rangeDetails = new BdRangeDetails();
                rangeDetails.setPkRange(rangeExt.getPkId());
                rangeDetails.setPkLevel(aw);
                rangeDetails.setRangeType(ERangeType.AWARDS.getValue());
                rangeDetails.setPkCountry(SecurityUtils.getPkCountry());
                rangeDetails.setPkCreator(SecurityUtils.getUserId());
                rangeDetails.setCreationTime(new Date());
                rangeDetailsService.save(rangeDetails);
            }
        }
        redisService.deleteObject(CacheConstants.BD_RANGE + rangeExt.getPkCountry());
        return true;
    }

    /**
     * @description: 修改极差
     * @author: zhang jing
     * @date: 2022/10/28 14:23
     * @param: [rangeExt]
     * @return: boolean
     **/
    @Override
    public boolean updateRange(BdRangeExt rangeExt) {
        //字段翻译保存到数据库
        R<Integer> pkTransaction = iTransactionServiceApi.createTransaction(rangeExt.getPkCountry(), ETransactionKey.RANGE,
                rangeExt.getRangeName(), EYesNo.YES, EYesNo.NO);
        rangeExt.setPkTransaction(pkTransaction.getData());
        baseMapper.updateById(rangeExt);
        UpdateWrapper<BdRangeDetails> updateWrapper = new UpdateWrapper();
        updateWrapper.set("DEL_FLAG", EYesNo.NO.getIntValue());
        updateWrapper.eq("PK_RANGE", rangeExt.getPkId());
        rangeDetailsService.update(updateWrapper);
        List<Integer> gradeList = rangeExt.getGradeList();
        List<Integer> awardsList = rangeExt.getAwardsList();
        //等级
        for (Integer gr : gradeList) {
            BdRangeDetails rangeDetails = new BdRangeDetails();
            rangeDetails.setPkRange(rangeExt.getPkId());
            rangeDetails.setPkLevel(gr);
            rangeDetails.setRangeType(ERangeType.GRADE.getValue());
            rangeDetails.setPkCountry(SecurityUtils.getPkCountry());
            rangeDetails.setPkCreator(SecurityUtils.getUserId());
            rangeDetails.setCreationTime(new Date());
            rangeDetailsService.save(rangeDetails);
        }
        //奖衔
        for (Integer aw : awardsList) {
            BdRangeDetails rangeDetails = new BdRangeDetails();
            rangeDetails.setPkRange(rangeExt.getPkId());
            rangeDetails.setPkLevel(aw);
            rangeDetails.setRangeType(ERangeType.AWARDS.getValue());
            rangeDetails.setPkCountry(SecurityUtils.getPkCountry());
            rangeDetails.setPkCreator(SecurityUtils.getUserId());
            rangeDetails.setCreationTime(new Date());
            rangeDetailsService.save(rangeDetails);
        }
        redisService.deleteObject(CacheConstants.BD_RANGE + rangeExt.getPkCountry());
        return true;
    }


    /**
     * @description: 根据国家查询极差配置列表
     * @author: zhang jing
     * @date: 2022/11/11 18:07
     * @param: [pkCountry]
     * @return: java.util.List<com.hzs.common.domain.system.config.BdRange>
     **/
    @Override
    public List<BdRangeExt> queryRange(Integer pkCountry) {
     //   redisService.deleteObject(CacheConstants.BD_RANGE + pkCountry);
        List<BdRangeExt> rangeList = redisService.getCacheList(CacheConstants.BD_RANGE + pkCountry);
        log.info("测试："+rangeList);
        List<BdRangeExt> rangeListNew = new ArrayList<>();
        if (CollectionUtil.isEmpty(rangeList)) {
            QueryWrapper<BdRange> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PK_COUNTRY", pkCountry);
            queryWrapper.orderByDesc("CREATION_TIME");
            List<BdRange> list = baseMapper.selectList(queryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(item -> rangeListNew.add(BeanUtil.copyProperties(item, BdRangeExt.class)));
                redisService.setCacheList(CacheConstants.BD_RANGE + pkCountry, rangeListNew);
            }
            return rangeListNew;
        } else {
            return rangeList;
        }
    }

    @Override
    public Map<String, RangeDTO> queryRangeDto() {
        Map<String, RangeDTO> rangeDtoMap = new HashMap<>(10);
        List<RangeDTO> rangeDtoS = baseMapper.queryRangeDto(null, null, null);
        rangeDtoS.forEach(rangeDto -> {
            String key = rangeDto.getPkCountry().toString() + rangeDto.getRangeType() + rangeDto.getPkLevel();
            rangeDtoMap.put(key, rangeDto);
        });
        return rangeDtoMap;
    }

    @Override
    public RangeDTO getRangeDTO(Integer pkCountry, Integer rangeType, Integer pkLevel) {
        String key = CacheConstants.BD_RANGE + pkCountry + rangeType + pkLevel;
        RangeDTO rangeDTO = redisService.getCacheObject(key);
        if (rangeDTO == null) {
            List<RangeDTO> rangeDTOList = baseMapper.queryRangeDto(pkCountry, rangeType, pkLevel);
            if (rangeDTOList != null && rangeDTOList.size() > 0) {
                rangeDTO = rangeDTOList.get(0);
                redisService.setCacheObject(key, rangeDTO, Constants.TIMEOUT_DAY, TimeUnit.DAYS);
            }
        }
        return rangeDTO;
    }
}
