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 = "indexRealTimeTask")
public class IndexRealTimeTask extends ScheduleTask {


    @Autowired
    ICharacterParamService iCharacterParamService;
    @Autowired
    IEventInfoService iEventInfoService;

    @Autowired
    TaskCacheDataService taskCacheDataService;

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

    @Override
    public void run() {
        ConcurrentHashMap<String, IndexRealTimeWebSocket> webSocketMap =
                IndexRealTimeWebSocket.webSocketMap;
        ConcurrentHashMap<String, String> deviceMap = IndexRealTimeWebSocket.deviceMap;
        //给每个deviceid分组，然后统一查询，进行推送
        Map<String, List<Map.Entry<String, String>>> groupMap = deviceMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
        //需要区分的测点
        String[] points = new String[]{
                "发电机定子A相电流",
                "发电机定子B相电流",
                "发电机定子C相电流",
                "发电机定子AB线电压",
                "发电机定子BC线电压",
                "发电机定子CA线电压",
                "汽端座振X",
                "汽端轴振X",
                "励端座振X",
                "励端轴振X",
                "排油温度",
        };

        //向每个webSocket推送系统实时数据
        List<CharacterParamInfoVo> characterParamInfoList = taskCacheDataService.cacheIndexCPI();
        for (String deviceId : groupMap.keySet()) {
            //获取kkscode
            List<CharacterParamInfoVo> characterParamInfoVos ;
            //全场
            if ("total".equals(deviceId)) {
                characterParamInfoVos = characterParamInfoList;
            }else{
                characterParamInfoVos = characterParamInfoList.stream().filter(item -> item.getDeviceId().equals(deviceId)).collect(Collectors.toList());
            }
            Map<String, String> KKsCodes = characterParamInfoVos.stream().filter(item ->
                    IS_CONTAINS(item.getCpName(), points))
                    .collect(Collectors.toMap(CharacterParamInfoVo::getKksCode, CharacterParamInfoVo::getCpName));
            //获取最后一个数据点的最近一个时间
            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()));
                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[]{
                        "发电机定子A相电流",
                        "发电机定子B相电流",
                        "发电机定子C相电流",
                        "发电机定子AB线电压",
                        "发电机定子BC线电压",
                        "发电机定子CA线电压",
                })) {
                    //右上图
                    DataPower dataPower = map.getOrDefault("rightTop", new DataPower());
                    dataPower.setXAxis(xAxis);
                    dataPower.getDataList().add(powerPoints);
                    map.putIfAbsent("rightTop", dataPower);
                }
                if (IS_CONTAINS(KKsCodes.get(queryResult.getMetric()), new String[]{
                        "汽端座振X",
                        "汽端轴振X",
                        "励端座振X",
                        "励端轴振X",
                })) {
                    //右上图
                    DataPower dataPower = map.getOrDefault("rightMiddle", new DataPower());
                    dataPower.setXAxis(xAxis);
                    dataPower.getDataList().add(powerPoints);
                    map.putIfAbsent("rightMiddle", 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);
                }
            }
            try {
                List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(deviceId);
                //根据deviceid统一发送
                for (Map.Entry<String, String> entry : deviceGroupMap) {
                    final IndexRealTimeWebSocket webSocket = webSocketMap.get(entry.getKey());
                    webSocket.sendMessage(JSON.toJSONString(map));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
