package cn.wise.sc.energy.power.plant.business.utils.poi;

import cn.hutool.core.collection.CollectionUtil;
import cn.wise.sc.energy.power.plant.business.domain.AutoInspection;
import cn.wise.sc.energy.power.plant.business.service.ICharacterParamService;
import cn.wise.sc.energy.power.plant.business.task.async.ReportParamsTask;
import cn.wise.sc.energy.power.plant.business.task.async.TimeConsumingOperation;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.opentsdb.client.api.query.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import static cn.wise.sc.energy.power.plant.business.task.async.TimeConsumingOperation.REPORT_TASKS_MAP;

/**
 * 报告参数处理类
 *
 * @author neo.shu
 * @since 2020/10/7 08:22
 */
@Service
@Slf4j
public class ReportParamProcessor {

    @Autowired
    ICharacterParamService iCharacterParamService;
    @Autowired
    private ReportParamsTask reportParamsTask;

    String[] subsidiaryParams = new String[]{
            "CBA00MKF26S101",
            "MKW05CP101",
            "MKW05CP001",
            "MKF16CF101",
            "MKD12CT603A",
            "MKD11CT603A",
            "MKF23CQ101A",
            "MKF23CQ101B",
            "MKF26S102",
            "MKG35CQ101",
            "MKG30CQ112",
            "MKW17CP001",
            "MKW18CP001",
            "MKW02CP001",
            "MKW03CP001",
            "MKW14CT001",
            "MKW24CT001",
            "MKA32CQ901A",
            "MKA32CQ901B",
            "MKG50CM102",
            "MKA32CQ901C",
            "MKA32CQ902",
            "MKA32CQ903",
    };

    String[] electricParams = new String[]{
            "MKA62CE601",
            "MKA62CE602",
            "MKA62CE603",
            "MKA62CE604",
            "MKA62CE605",
            "MKA62CE705",
            "MKA62CE704",
            "MKA62CE604",
            "MKA62CE605",
    };

    String[] environParams = new String[]{
            "MKA51CQ101A",
            "MKA51CQ101B",
            "MKA51CQ101C",
            "MKA51CQ102A",
            "MKA51CQ102B",
            "MKA51CQ102C",
            "MKA52CQ101",
            "MKA52CQ102",
            "MKA52CQ103",
            "MKA52CQ104",
            "MKA52CQ105",
            "MKA41CL001",
            "MKA42CL001",
            "MKA43CL001",
            "MKA44CL001"

    };
    String[] stateParams = new String[]{
            "MKA01CE003A",
            "MKA16CS101",
            "MKA01CE002A",
            "MKA01CE001A",
            "MKC20CE001",
            "MKC20CE002",
    };

    public JSONObject paramJson(JSONObject allin, List<AutoInspection> list, String endTime) {
        String deviceCode = list.get(0).getDeviceid();
        List<AutoInspection> newLiset = list.stream().filter(item -> item.getDeviceid().equals(deviceCode)).collect(Collectors.toList());
        //辅助参数
        REPORT_TASKS_MAP.put("fuzhu_subsidiary" + endTime + deviceCode, reportParamsTask.executeTimeConsumingOperation(new Subsidiaryparam(), "fuzhu", allin, subsidiaryParams, deviceCode, endTime));
        //电气参数
        REPORT_TASKS_MAP.put("dianqi_subsidiary" + endTime + deviceCode, reportParamsTask.executeTimeConsumingOperation(new Subsidiaryparam(), "dianqi", allin, electricParams, deviceCode, endTime));
        //环境参数
        REPORT_TASKS_MAP.put("huanjing_subsidiary" + endTime + deviceCode, reportParamsTask.executeTimeConsumingOperation(new Subsidiaryparam(), "huanjing", allin, environParams, deviceCode, endTime));
        //总体状态
        REPORT_TASKS_MAP.put("zhuangtai_subsidiary" + endTime + deviceCode, reportParamsTask.executeTimeConsumingOperation(new Subsidiaryparam(), "state", allin, stateParams, deviceCode, endTime));
        REPORT_TASKS_MAP.put("resultanalysis_subsidiary" + endTime + deviceCode, reportParamsTask.executeTimeConsumingOperation(new ResultAnalysis(), allin, newLiset));

        REPORT_TASKS_MAP.forEach((k, v) -> {
            if (k.contains("_subsidiary" + endTime + deviceCode)) {
                try {
                    v.get();
                    TimeConsumingOperation.REPORT_TASKS_MAP.remove(k);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
        return allin;
    }

    /**
     * 处理autoinspection 结论
     */
    class ResultAnalysis implements TimeConsumingOperation {

        @Override
        public void operate(Object... args) throws IOException {
            log.error("-----结论开始");
            JSONObject jsonObject = (JSONObject) args[0];
            List<AutoInspection> list = (List<AutoInspection>) args[1];
            JSONObject results = new JSONObject();
            Map<String, List<AutoInspection>> groupMap = list.stream().collect(Collectors.groupingBy(c -> c.getTyped()));
            groupMap.forEach((k, v) -> {
                List<AutoInspection> result_1 = v.stream().filter(item -> item.getResult().equals(1)).collect(Collectors.toList());
                //非M的获取相应的结论
                if (!k.equals("M")) {
                    if (!CollectionUtil.isEmpty(result_1)) {
                        //获取所有的报警结论
                        String result = "";
                        for (AutoInspection a : result_1) {
                            result += JSONObject.parseObject(a.getDiagnosis()).get("diagnosis") + " ";
                        }
                        results.put(k, result);
                    } else {
                        results.put(k, "根据系统智能诊断结果，本体温升正常、无报警");
                    }
                }
                if (k.equals("M")) {
                    for (AutoInspection a : v) {
                        JSONObject diagnosis = JSONObject.parseObject(a.getDiagnosis());
                        String name = (String) diagnosis.get("name");
                        String result = (String) diagnosis.get("diagnosis");
                        switch (name) {
                            case "励端":
                                //轴振
                                results.put("MZ", a.getResult() == 1 ? result : "根据系统智能诊断结果，5\\6\\7轴振振均在优秀运行范围");
                                break;
                            case "汽端":
                                //瓦振
                                results.put("MW", a.getResult() == 1 ? result : "根据系统智能诊断结果，5\\6\\7瓦振均在优秀运行范围");
                                break;
                            case "集电环":
                                //端振
                                results.put("MD", a.getResult() == 1 ? result : "根据系统智能诊断结果，汽、励端端部振动均在合格运行范围");
                                break;

                        }
                        jsonObject.put(name + "RunoutX", (JSONObject) diagnosis.get("RunoutX"));
                        jsonObject.put(name + "RunoutY", (JSONObject) diagnosis.get("RunoutY"));
                    }
                }
                if (k.equals("P")) {
                    ArrayList<HashMap<String, String>> plist = new ArrayList<>();
                    for (AutoInspection a : v) {
                        HashMap<String, String> temp = new HashMap<>(3);
                        temp.put("unitname", a.getUnitname());
                        temp.put("result", a.getResult().equals(0) ? "正常" : "异常");
                        temp.put("diagnosis", (String) JSONObject.parseObject(a.getDiagnosis()).get("diagnosis"));
                        plist.add(temp);
                    }
                    //获取最小值
                    int grade = v.stream().map(AutoInspection::getGrade).collect(Collectors.toList()).stream().min(Comparator.naturalOrder()).orElse(0);

                    jsonObject.put("plist", plist);
                    jsonObject.put("grade", grade);
                }
            });
            jsonObject.put("result", results);
            log.error("-----结论完成");
        }
    }

    /**
     * 获取参数相关值
     *
     * @return
     */

    class Subsidiaryparam implements TimeConsumingOperation {

        @Override
        public void operate(Object... args) throws IOException {
            String keyname = (String) args[0];
            JSONObject jsonObject = (JSONObject) args[1];
            String[] kkscode = (String[]) args[2];
            String deviceCode = (String) args[3];
            String endTime = (String) args[4];
            log.error(keyname + "-----开始");
            //拼接kkscode
            List<String> listWithDevicode = Arrays.stream(kkscode).map(item -> {
                return deviceCode + item;
            }).collect(Collectors.toList());
            //查询opentsdb
            QueryResponse response = iCharacterParamService.getRealTimeDataByKksCode(listWithDevicode, (Long.parseLong(endTime) - 1) + "", endTime, null);
            //组装参数
            JSONObject fuzhu = new JSONObject();
            if (!CollectionUtil.isEmpty(response.getResults())) {
                response.getResults().forEach(item -> {
                    LinkedHashMap result = item.getDps();
                    if (!CollectionUtil.isEmpty(result)) {
                        fuzhu.put(item.getMetric().split(deviceCode)[1], result.values().toArray()[0]);
                    } else {
                        fuzhu.put(item.getMetric().split(deviceCode)[1], 0.0);
                    }
                });
            }
            jsonObject.put(keyname, fuzhu);
            log.error(keyname + "-----结束");

        }
    }

}
