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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
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 javafx.scene.shape.VLineTo;
import lombok.AllArgsConstructor;
import lombok.Data;
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 = "waterSystem3Task")
public class WaterSystem3Task extends ScheduleTask {


    @Autowired
    ICharacterParamService iCharacterParamService;
    @Autowired
    IEventInfoService iEventInfoService;

    @Autowired
    TaskCacheDataService taskCacheDataService;

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

    @Override
    public void run() {
        ConcurrentHashMap<String, WaterSystemWebSocket> webSocketMap =
                WaterSystemWebSocket.webSocketMap;
        ConcurrentHashMap<String, String> deviceMap = WaterSystemWebSocket.deviceMap;
        //给每个deviceid分组，然后统一查询，进行推送
        Map<String, List<Map.Entry<String, String>>> groupMap = deviceMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
        //需要区分的测点
        String[] points = new String[]{
                //左上
                "定子线圈进出水压差1",
                "定子冷却水进出口差压1",
                "定子补水进出口水差压1",
                //右上
                "冷却水泵A出口压力1",
                "冷却水泵B出口压力1",
                //右下
                "水箱液位高",
                "水箱液位低",
                "氢水压差低",
                "定子水箱压力",
        };
        //向每个webSocket推送系统实时数据
        for (String deviceId : groupMap.keySet()) {
            List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheWaterCPI(deviceId);
            //获取kkscode
            Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item ->
                    IS_CONTAINS(item.getCpName(), points))
                    .collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
            Map<String, String> KKsCodes_cunit = characterParamInfoVos.stream().filter(item ->
                    IS_CONTAINS(item.getCpName(), points))
                    .collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpUnit));
            //获取最后一个数据点的最近一个时间
            Long lastTime = OpentsdbOkHttpClient.queryLast(characterParamInfoVos);

            QueryResponse response = iCharacterParamService
                    .getRealTimeDataByKksCode(new ArrayList<>(KKsCodes.keySet()), (lastTime - 1) + "", lastTime + "", "");

            //获取横坐标
            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()));
                powerPoints.setCpunit(KKsCodes_cunit.get(queryResult.getMetric()));
                List<String> finalList = new ArrayList<>();
                queryResult.getDps().values().stream().forEach(item -> {
                    finalList.add(item.toString());
                });
                powerPoints.setValue(finalList);
                if (IS_CONTAINS(KKsCodes.get(queryResult.getMetric()), new String[]{
                        "定子线圈进出水压差1",
                        "定子冷却水进出口差压1",
                        "定子补水进出口水差压1",
                })) {
                    //左上图
                    DataPower dataPower = map.getOrDefault("leftTop", new DataPower());
                    dataPower.setXAxis(xAxis);
                    dataPower.getDataList().add(powerPoints);
                    map.putIfAbsent("leftTop", dataPower);
                }
                if (IS_CONTAINS(KKsCodes.get(queryResult.getMetric()), new String[]{
                        "水箱液位高",
                        "水箱液位低",
                        "氢水压差低",
                        "定子水箱压力",
                })) {
                    DataPower dataPower = map.getOrDefault("rightBottom", new DataPower());
                    dataPower.setXAxis(xAxis);
                    dataPower.getDataList().add(powerPoints);
                    map.putIfAbsent("rightBottom", dataPower);
                }
                if (IS_CONTAINS(KKsCodes.get(queryResult.getMetric()), new String[]{
                        //右上
                        "冷却水泵A出口压力1",
                        "冷却水泵B出口压力1",
                })) {
                    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 WaterSystemWebSocket webSocket = webSocketMap.get(entry.getKey());
                    webSocket.sendMessage(JSON.toJSONString(map));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
