package com.gyee.alarm.init.Cache;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.gyee.alarm.mapper.auto.ProBasicDeviceMetricsMapper;
import com.gyee.alarm.mapper.auto.ProBasicDeviceModelMetricsMapper;
import com.gyee.alarm.model.auto.ProBasicDeviceMetrics;
import com.gyee.alarm.model.auto.ProBasicDeviceModelMetrics;
import com.gyee.alarm.service.auto.impl.ProBasicDeviceModelMetricsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class PointUnitCache {
    @Resource
    private ProBasicDeviceMetricsMapper proBasicDeviceMetricsMapper;

    @Resource
    private ProBasicDeviceModelMetricsServiceImpl proBasicDeviceModelMetricsService;

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

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

            //获取所有风机型号以及统一编码
            List<ProBasicDeviceModelMetrics> modelList = proBasicDeviceModelMetricsService.getAll();
            //根据风机型号分组
            Map<String, List<ProBasicDeviceModelMetrics>> collect = modelList.stream().collect(Collectors.groupingBy(ProBasicDeviceModelMetrics::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<ProBasicDeviceMetrics> list=new ArrayList<>();
                for (List<String> codeList:
                        partition) {
                    QueryWrapper wrapper = new QueryWrapper<ProBasicDeviceMetrics>();
                    wrapper.in("metric_code", codeList);
                    list.addAll(proBasicDeviceMetricsMapper.selectList(wrapper))  ;

                }

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

                    Optional<ProBasicDeviceMetrics> 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;

    }
}
