package cn.wise.sc.energy.power.plant.business.task;

import cn.wise.sc.energy.power.plant.business.bean.DataPower;
import cn.wise.sc.energy.power.plant.business.domain.vo.CharacterParamInfoVo;
import cn.wise.sc.energy.power.plant.business.opentsdb.OpentsdbOkHttpClient;
import cn.wise.sc.energy.power.plant.business.service.ICharacterParamService;
import cn.wise.sc.energy.power.plant.business.service.IEventInfoService;
import cn.wise.sc.energy.power.plant.business.task.schedule.ScheduleTask;
import com.alibaba.fastjson.JSON;
import net.opentsdb.client.api.query.response.QueryResponse;
import net.opentsdb.client.bean.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author neo.shu
 * @since 2020/9/17 17:30
 */
@Service(value = "hydrogeSystem3Task")
public class HydrogeSystem3Task extends ScheduleTask {


    @Autowired
    ICharacterParamService iCharacterParamService;
    @Autowired
    IEventInfoService iEventInfoService;

    @Autowired
    TaskCacheDataService taskCacheDataService;

    public HydrogeSystem3Task() {
        super(UUID.randomUUID().toString());
    }

    @Override
    public void run() {
        ConcurrentHashMap<String, HydrogenSystemWebSocket> webSocketMap =
                HydrogenSystemWebSocket.webSocketMap;
        ConcurrentHashMap<String, String> deviceMap = HydrogenSystemWebSocket.deviceMap;
        if (webSocketMap.size() == 0 || deviceMap.size() == 0) {
            return;
        }
        //给每个deviceid分组，然后统一查询，进行推送
        Map<String, List<Map.Entry<String, String>>> groupMap = deviceMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
        String[] measure_points = new String[]{"发电机机内氢压", "机内氢气湿度", "漏氢含量"};
        //向每个webSocket推送系统实时数据
        for (String deviceId : groupMap.keySet()) {
            List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheHydrogeCha(deviceId);
            //获取kkscode
            Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item ->
                    IS_CONTAINS(item.getCpName(), measure_points))
                    .collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
            //获取最后一个数据点的最近一个时间
            Long lastTime = OpentsdbOkHttpClient.queryLast(characterParamInfoVos);

            QueryResponse response = iCharacterParamService
                    .getRealTimeDataByKksCode(new ArrayList<>(KKsCodes.keySet()), (lastTime - 24 * 3600 * 1000) + "", lastTime + "", "1h-avg-zero");

            //获取横坐标
            List<Object> xAxis = response.getResults().get(0).getDps().keySet().stream().map(item -> item.toString()).collect(Collectors.toList());
            //组装数据
            Map<String, DataPower> map = new HashMap<>();
            for (QueryResult queryResult : response.getResults()) {
                DataPower.PowerPoints powerPoints = new DataPower.PowerPoints();
                powerPoints.setKksCode(queryResult.getMetric());
                powerPoints.setName(KKsCodes.get(queryResult.getMetric()));
                List<String> finalList = new ArrayList<>();
                queryResult.getDps().values().stream().forEach(item -> {
                    finalList.add(item.toString());
                });
                powerPoints.setValue(finalList);
                if (KKsCodes.get(queryResult.getMetric()).contains("发电机机内氢压")) {
                    //左上图
                    DataPower dataPower = map.getOrDefault("leftTop",new DataPower());
                    dataPower.setXAxis(xAxis);
                    dataPower.getDataList().add(powerPoints);
                    map.putIfAbsent("leftTop", dataPower);
                }
                if (KKsCodes.get(queryResult.getMetric()).contains("机内氢气湿度")) {
                    DataPower dataPower = map.getOrDefault("leftBottom",new DataPower());
                    dataPower.setXAxis(xAxis);
                    dataPower.getDataList().add(powerPoints);
                    map.putIfAbsent("leftBottom", dataPower);
                }
                if (KKsCodes.get(queryResult.getMetric()).contains("漏氢含量")) {
                    DataPower dataPower = map.getOrDefault("rightTop",new DataPower());
                    dataPower.setXAxis(xAxis);
                    dataPower.getDataList().add(powerPoints);
                    map.putIfAbsent("rightTop", dataPower);
                }
            }

            try {
                List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(deviceId);
                //根据deviceid统一发送
                for (Map.Entry<String, String> entry : deviceGroupMap) {
                    final HydrogenSystemWebSocket webSocket = webSocketMap.get(entry.getKey());
                    webSocket.sendMessage(JSON.toJSONString(map));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
