package com.persagy.dye.service.impl;

import com.persagy.common.utils.DateUtil;
import com.persagy.dye.constant.DyeConstant;
import com.persagy.dye.mapper.DyeRuleCustomMapper;
import com.persagy.dye.mapper.DyeRuleDefaultMapper;
import com.persagy.dye.pojo.dto.DyeRuleCustom;
import com.persagy.dye.pojo.dto.DyeRuleDefault;
import com.persagy.dye.pojo.vo.DyeScaleplateVO;
import com.persagy.dye.service.IDyeSdkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @description: SDK染色标尺维护接口
 * @author: YangWanYi
 * @create: 2021-10-25 18:08
 **/
@Service
@Slf4j
public class DyeSdkServiceImpl implements IDyeSdkService {

    @Autowired
    private DyeRuleCustomMapper dyeRuleCustomMapper;

    @Autowired
    private DyeRuleDefaultMapper dyeRuleDefaultMapper;


    /**
     * 查询空间对应的染色标尺
     *
     * @param dyeScaleplateVO
     * @return List<Map < String, Object>>
     */
    @Override
    public List<Map<String, Object>> listDyeScaleplateWithSpaceIds(DyeScaleplateVO dyeScaleplateVO) {
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        if (!dyeScaleplateVO.getDynamicArray().isEmpty()) {
            DyeRuleCustom customRule;
            DyeRuleDefault defaultRule;
            HashMap<String, Object> resultMap = new HashMap<>();
            /*
                1、优先获取自定义的染色标尺，没有再获取默认的
                2、根据当前日期判断属于哪个季
             */
            dyeScaleplateVO.setQueryDate(DateUtil.format(new Date(), DateUtil.FORMAT_DATE_YYYYMMDD));
            for (Map<String, Object> map : dyeScaleplateVO.getDynamicArray()) {
                customRule = this.dyeRuleCustomMapper.getDistrictDyeRuleCustom(dyeScaleplateVO, map.get(DyeConstant.REALTIME_NUM) == null ? 0 : Integer.parseInt(String.valueOf(map.get(DyeConstant.REALTIME_NUM))));
                if (customRule != null) {
                    resultMap = this.changeProperties(String.valueOf(customRule.getUpperLimit()), String.valueOf(customRule.getLowerLimit()), customRule.getName(), customRule.getColorValue(), customRule.getId());
                } else {
                    defaultRule = this.dyeRuleDefaultMapper.getDistrictDyeRuleDefault(dyeScaleplateVO, map.get(DyeConstant.REALTIME_NUM) == null ? 0 : Integer.parseInt(String.valueOf(map.get(DyeConstant.REALTIME_NUM))));
                    if (defaultRule != null) {
                        resultMap = this.changeProperties(String.valueOf(defaultRule.getUpperLimit()), String.valueOf(defaultRule.getLowerLimit()), defaultRule.getName(), defaultRule.getColorValue(), defaultRule.getId());
                    }
                }
                resultMap.put(DyeConstant.PROJECT_ID, dyeScaleplateVO.getProjectId()); // 项目ID
                resultMap.put(DyeConstant.GROUP_CODE, dyeScaleplateVO.getGroupCode()); // 集团编码
                resultMap.put(DyeConstant.TYPE_CODE, dyeScaleplateVO.getTypeCode()); // 染色类型
                resultMap.put(DyeConstant.SPACE_ID, map.get(DyeConstant.SPACE_ID)); // 空间ID
                resultMap.put(DyeConstant.REALTIME_NUM, map.get(DyeConstant.REALTIME_NUM)); // 动态检测值
                list.add(resultMap);
            }
        }
        return list;
    }


    /**
     * 查询指定集团、项目和类型的染色标尺列表
     *
     * @param dyeScaleplateVO
     * @return List<Map < String, Object>>
     */
    @Override
    public List<Map<String, Object>> listDyeScaleplateByType(DyeScaleplateVO dyeScaleplateVO) {
        /*
            1、如果自定义表中没有数据，则获取默认表的数据
            2、根据当前日期判断属于哪个季
         */
        List<Map<String, Object>> list = new ArrayList<>();
        dyeScaleplateVO.setQueryDate(DateUtil.format(new Date(), DateUtil.FORMAT_DATE_YYYYMMDD));
        List<DyeRuleCustom> customList = this.dyeRuleCustomMapper.listDyeRuleCustomByType(dyeScaleplateVO);
        log.debug("com.persagy.dye.service.impl.DyeSdkServiceImpl.listDyeScaleplateByType，自定义染色标尺数据:{}", customList);
        if (!customList.isEmpty()) {
            for (DyeRuleCustom customRule : customList) {
                list.add(this.changeProperties(String.valueOf(customRule.getUpperLimit()), String.valueOf(customRule.getLowerLimit()), customRule.getName(), customRule.getColorValue(), customRule.getId()));
            }
            return list;
        }
        List<DyeRuleDefault> defaultList = this.dyeRuleDefaultMapper.listDyeRuleDefaultByType(dyeScaleplateVO);
        log.debug("com.persagy.dye.service.impl.DyeSdkServiceImpl.listDyeScaleplateByType，默认染色标尺数据:{}", defaultList);
        if (!defaultList.isEmpty()) {
            for (DyeRuleDefault defaultRule : defaultList) {
                list.add(this.changeProperties(String.valueOf(defaultRule.getUpperLimit()), String.valueOf(defaultRule.getLowerLimit()), defaultRule.getName(), defaultRule.getColorValue(), defaultRule.getId()));
            }
        }
        return list;
    }


    /**
     * 把两个不同对象转换为前台需要的数据
     *
     * @param upperLimit 上限
     * @param lowerLimit 下限
     * @param name       名称
     * @param colorValue 色值
     * @param id         染色标尺ID（可能是默认标尺ID也可能是自定义标尺ID 主要是给SDK使用）
     * @return HashMap<String, Object>
     */
    private HashMap<String, Object> changeProperties(String upperLimit, String lowerLimit, String name, String colorValue, String id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put(DyeConstant.UPPER_LIMIT, this.replace99ToBoundless(upperLimit)); // 上限
        map.put(DyeConstant.LOWER_LIMIT, this.replace99ToBoundless(lowerLimit)); // 下限
        map.put(DyeConstant.NAME, name); // 名称
        map.put(DyeConstant.COLOR_VALUE, colorValue); // 色值
        map.put(DyeConstant.DYE_ID, id); // 染色标尺ID
        return map;
    }

    /**
     * 把上下限的99替换为∞（数据库存99是为了方便数值对比）
     *
     * @param limit 上限或下限
     * @return String
     */
    public String replace99ToBoundless(String limit) {
        final String numLimit = "99";

         /*if (limit.indexOf(numLimit) != -1) {
            limit = limit.replace(numLimit, "∞");
            if (limit.indexOf("-") == -1) { // 正无穷拼接加号
                limit = "+" + limit;
            }
        }*/

        // SDK不需要返回无穷 但凡是无穷的给空就行
        if (limit.indexOf(numLimit) != -1) {
            return StringUtils.EMPTY;
        }
        return limit;
    }

    /**
     * 与WEB交互时，把上下限值转换为数值类型（数据库存99是为了方便数值对比）
     *
     * @param tempLimit 与WEB交互的上限或下限字段
     * @return Integer
     */
    public Integer replaceBoundlessTo99(String tempLimit) {
        final String boundless = "∞";
        if (tempLimit.indexOf(boundless) == -1) {
            return Integer.valueOf(tempLimit); // 非无穷限值直接转换为数值类型返回
        }
        int limitValue = 99; // 无穷限值替换为99
        if (tempLimit.indexOf("-") != -1) {  // 负无穷限值把99转换为负数
            limitValue = -limitValue;
        }
        return limitValue;
    }
}
