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


    @Autowired
    ICharacterParamService iCharacterParamService;
    @Autowired
    IEventInfoService iEventInfoService;

    @Autowired
    TaskCacheDataService taskCacheDataService;

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

    @Override
    public void run() {
        ConcurrentHashMap<String, OilSystemWebSocket> webSocketMap =
                OilSystemWebSocket.webSocketMap;
        ConcurrentHashMap<String, String> deviceMap = OilSystemWebSocket.deviceMap;
        //给每个deviceid分组，然后统一查询，进行推送
        Map<String, List<Map.Entry<String, String>>> groupMap = deviceMap.entrySet().stream().collect(Collectors.groupingBy(c -> c.getValue()));
        //需要区分的测点
        String[] points = new String[]{
                //左上
                "汽轮机备用油差压阀进口压力",
                "排油烟机1号进口压力",
                "排油烟机2号进口压力",
        };

        //向每个webSocket推送系统实时数据
        for (String deviceId : groupMap.keySet()) {
            List<CharacterParamInfoVo> characterParamInfoVos = taskCacheDataService.cacheOilCPI(deviceId);
            //获取kkscode
            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 - 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 (IS_CONTAINS(KKsCodes.get(queryResult.getMetric()), points)) {
                    //左上图
                    DataPower dataPower = map.getOrDefault("leftTop", new DataPower());
                    dataPower.setXAxis(xAxis);
                    dataPower.getDataList().add(powerPoints);
                    map.putIfAbsent("leftTop", dataPower);
                }
            }
            try {
                List<Map.Entry<String, String>> deviceGroupMap = groupMap.get(deviceId);
                //根据deviceid统一发送
                for (Map.Entry<String, String> entry : deviceGroupMap) {
                    final OilSystemWebSocket webSocket = webSocketMap.get(entry.getKey());
                    webSocket.sendMessage(JSON.toJSONString(map));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
