package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.ugp.api.Enum.GenStageEnum;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProblemCodeLibDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProblemCodeLib;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProblemCodeLibMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IProblemCodeLibService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProblemCodeLibServiceImpl extends BaseService<ProblemCodeLibDto, ProblemCodeLib, ProblemCodeLibMapper> implements IProblemCodeLibService {

    @Resource
    private ProblemCodeLibMapper problemCodeLibMapper;

    @Value("${dict.code.unit:UNIT_MANAGE}")
    private String unitManage;

    public IPage<ProblemCodeLib> queryProblemCodeInfoPage(Page<ProblemCodeLib> page, ProblemCodeLib problemCodeLib) {
        LambdaQueryWrapper<ProblemCodeLib> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProblemCodeLib::getIsDelete, Boolean.FALSE);
        lambdaQueryWrapper.orderByDesc(ProblemCodeLib::getRecDate);
        createWarpper(lambdaQueryWrapper,problemCodeLib);
        Map<String, String> dictValueMap = getDictInfoMapByCode(unitManage);
        IPage<ProblemCodeLib> problemCodeLibIPage = problemCodeLibMapper.selectPage(page, lambdaQueryWrapper);
        problemCodeLibIPage.getRecords().forEach(item -> {
            item.setIdxThresholds(doDataToString(item.getIdxThresholds(), item.getIdxType()));
            item.setGenStage(GenStageEnum.getTypeByCode(item.getGenStage()));
            item.setIdxType(GenStageEnum.getTypeByCode(item.getIdxType()));
            item.setIdxUnit(dictValueMap.get(item.getIdxUnit()));
        });
        return problemCodeLibIPage;
    }

    public void createWarpper(LambdaQueryWrapper<ProblemCodeLib> lambdaQueryWrapper, ProblemCodeLib problemCodeLib){
        if(!ValidationUtil.isEmpty(problemCodeLib)) {
            if (!ValidationUtil.isEmpty(problemCodeLib.getGenStage())) {
                lambdaQueryWrapper.like(ProblemCodeLib::getGenStage, problemCodeLib.getGenStage());
            }
            if (!ValidationUtil.isEmpty(problemCodeLib.getContent())) {
                lambdaQueryWrapper.like(ProblemCodeLib::getContent, problemCodeLib.getContent());
            }
            if (!ValidationUtil.isEmpty(problemCodeLib.getCode())) {
                lambdaQueryWrapper.like(ProblemCodeLib::getCode, problemCodeLib.getCode());
            }
            if (!ValidationUtil.isEmpty(problemCodeLib.getRecUserName())) {
                lambdaQueryWrapper.like(ProblemCodeLib::getRecUserName, problemCodeLib.getRecUserName());
            }
            if (!ValidationUtil.isEmpty(problemCodeLib.getRecDate())) {
                lambdaQueryWrapper.like(ProblemCodeLib::getRecDate, problemCodeLib.getRecDate());
            }
        }
    }

    /**
     * 处理监管指标类型列表展示问题
     * @param idxThresholds 子表单提交的数据
     * @param idxType 监管指标类型
     * @return 组装好字符串【列表展示】
     */
    private String doDataToString (String idxThresholds, String idxType) {
        StringBuilder resultString = new StringBuilder();
        if (StringUtils.isNotEmpty(idxThresholds)) {
            List<Map<String, String>> listObject = JSON.parseObject(idxThresholds, List.class);
            for (Map<String, String> map : listObject) {
                String startValue = map.get("startValue");
                String endValue = map.get("endValue");
                if (idxType.equals(GenStageEnum.NUM_TYPE.getCode())) {
                    resultString.append(GenStageEnum.NUM_TYPE_START.getName()).append(startValue).append(",").append(GenStageEnum.NUM_TYPE_END.getName()).append(endValue);
                } else if (idxType.equals(GenStageEnum.SYMBOL_TYPE.getCode())) {
                    resultString.append(GenStageEnum.SYMBOL_TYPE_START.getName()).append(startValue).append(",").append(GenStageEnum.SYMBOL_TYPE_END.getName()).append(endValue);
                }
            }
        }
        return resultString.toString();
    }

    /**
     * 列表查询全量数据
     * @return 数据查询
     */
    public List<ProblemCodeLib> queryProblemCodeInfoList() {
        LambdaQueryWrapper<ProblemCodeLib> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProblemCodeLib::getIsDelete, Boolean.FALSE);
        lambdaQueryWrapper.orderByDesc(ProblemCodeLib::getRecDate);
        List<ProblemCodeLib> problemCodeLibs = problemCodeLibMapper.selectList(lambdaQueryWrapper);
        Map<String, String> dictValueMap = getDictInfoMapByCode(unitManage);
        problemCodeLibs.forEach(item -> {
            item.setIdxThresholds(doDataToString(item.getIdxThresholds(), item.getIdxType()));
            item.setGenStage(GenStageEnum.getTypeByCode(item.getGenStage()));
            item.setIdxType(GenStageEnum.getTypeByCode(item.getIdxType()));
            item.setIdxUnit(dictValueMap.get(item.getIdxUnit()));
        });
        return problemCodeLibs;
    }

    /**
     * 获取不重复的code
     * @return 返回不重复的code
     */
    public String getProblemCode() {
        LambdaQueryWrapper<ProblemCodeLib> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProblemCodeLib::getIsDelete, Boolean.FALSE);
        lambdaQueryWrapper.orderByDesc(ProblemCodeLib::getCreateDate);
        lambdaQueryWrapper.last("limit 1");
        ProblemCodeLib problemCodeLib = problemCodeLibMapper.selectOne(lambdaQueryWrapper);
        String resultCode;
        if (!ObjectUtils.isEmpty(problemCodeLib)) {
            if (problemCodeLib.getCode() != null) {
                String[] codeNum = problemCodeLib.getCode().split("QD");
                long num = Long.parseLong(codeNum[1]) + 1;
                resultCode = "QD" + num;
            } else {
                resultCode = "QD" + "100001";
            }
        } else {
            resultCode = "QD" + "100001";
        }
        return resultCode;
    }

    /**
     * 根据字典code获取字典值信息
     *
     * @param dictCode 字典值编码
     * @return key:字典值的key value：字典值的名称
     */
    private Map<String, String> getDictInfoMapByCode(String dictCode) {
        FeignClientResult<List<DictionarieValueModel>> adminCommonlyUsed = Systemctl.dictionarieClient.dictValues(dictCode);
        return adminCommonlyUsed.getResult().stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataValue));
    }
}
