package com.gyee.wisdom.alarm.sharding.cache;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.gyee.wisdom.alarm.sharding.entity.DeviceMetrics;
import com.gyee.wisdom.alarm.sharding.entity.DeviceModel;
import com.gyee.wisdom.alarm.sharding.entity.DeviceModelMetrics;
import com.gyee.wisdom.alarm.sharding.mapper.DeviceMetricsMapper;
import com.gyee.wisdom.alarm.sharding.mapper.DeviceModelMapper;
import com.gyee.wisdom.alarm.sharding.mapper.DeviceModelMetricsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 缓存风机型号，统一编码，测点值单位等
 * @auther: Wanghs
 * @date: 2022-02-28
 */
@Component
public class PointUnitCache {

    @Autowired
    private DeviceModelMetricsMapper deviceModelMetricsMapper;
    @Autowired
    private DeviceMetricsMapper deviceMetricsMapper;

    //key1=风机型号，valye1=测点集合，key2为测点统一编码，value2 DeviceMetrics
    private Map<String, Map<String, DeviceMetrics>> modelMap = new HashMap<>();

    public Map<String, DeviceMetrics> getMapByModel(String model) {
        if (modelMap.size() <= 0) {

            //获取所有风机型号以及统一编码
            List<DeviceModelMetrics> modelList = deviceModelMetricsMapper.getAll();
            //根据风机型号分组
            Map<String, List<DeviceModelMetrics>> collect = modelList.stream().collect(Collectors.groupingBy(DeviceModelMetrics::getDevicemodel));
            for (String key :
                    collect.keySet()) {
                List<String> metricCodeList = collect.get(key).stream().map(s -> s.getMetriccode()).collect(Collectors.toList());

                List<List<String>> partition = Lists.partition(metricCodeList, 800);
                List<DeviceMetrics> list=new ArrayList<>();
                for (List<String> codeList:
                     partition) {
                    QueryWrapper wrapper = new QueryWrapper<DeviceMetrics>();
                    wrapper.in("METRICCODE", codeList);
                    list.addAll(deviceMetricsMapper.selectList(wrapper))  ;

                }

                Map<String, DeviceMetrics> metricsMap = new HashMap<>();
                for (DeviceModelMetrics metrics :
                        collect.get(key)) {

                    Optional<DeviceMetrics> first = list.stream().filter(s -> s.getMetriccode().equals(metrics.getMetriccode())).findFirst();
                    if (first.isPresent())
                        metricsMap.put(metrics.getUniformcode(), first.get());

                }
                if (!modelMap.containsKey(key))
                    modelMap.put(key, metricsMap);
            }

        }

        if (modelMap.containsKey(model))
            return modelMap.get(model);
        else
            return null;

    }
}
