package com.inspect.analysis.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.inspect.analysis.constant.AnalyseConstants;
import com.inspect.analysis.domain.*;
import com.inspect.analysis.service.IAnalyseResponseService;
import com.inspect.analysis.service.IResultAnalysisService;
import com.inspect.base.core.constant.Color;
import com.inspect.base.core.constant.RedisConst;
import com.inspect.base.core.domain.Response;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.redis.service.RedisService;
import com.inspect.message.MessageUtils;
import com.inspect.mqtt.services.Warn.IUploadServer;
import com.inspect.partrolresult.client.WebsocketService;
import com.inspect.partrolresult.domain.AnalyseRequest;
import com.inspect.partrolresult.domain.PatrolResult;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.resultmain.domain.PatrolTaskResultMain;
import com.inspect.resultmain.service.IPatrolTaskResultMainService;
import com.inspect.system.base.openDomain.BasedataEqpBookMoMain;

import com.inspect.task.domain.PatrolTask;
import com.inspect.task.service.IPatrolTaskService;

import com.inspect.taskinfo.domain.PatrolTaskInfo;
import com.inspect.taskinfo.service.IPatrolTaskInfoService;
import com.inspect.taskstatus.client.FeignTaskClient;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping({"/picAnalyseRetNotify"})
public class AnalysisController extends BaseController {
    private final IResultAnalysisService resultAnalysisService;
    private final IPatrolResultService patrolResultService;
    private final FeignTaskClient feignTaskClient;
    private final IPatrolTaskResultMainService patrolTaskResultMainService;
    private final IUploadServer iUploadServer;
    private final RedisService redisService;
    private final IPatrolTaskInfoService patrolTaskInfoService;
    private final WebsocketService WebsocketService;
    private final IPatrolTaskService patrolTaskService;

    @Autowired
    MessageUtils messageUtils;

    @Resource
    private IAnalyseResponseService analysisService;

    public AnalysisController(IResultAnalysisService resultAnalysisService, IPatrolResultService patrolResultService, FeignTaskClient feignTaskClient, IPatrolTaskResultMainService patrolTaskResultMainService, IUploadServer iUploadServer, RedisService redisService, IPatrolTaskInfoService patrolTaskInfoService, WebsocketService WebsocketService, IPatrolTaskService patrolTaskService) {
        this.resultAnalysisService = resultAnalysisService;
        this.patrolResultService = patrolResultService;
        this.feignTaskClient = feignTaskClient;
        this.patrolTaskResultMainService = patrolTaskResultMainService;
        this.iUploadServer = iUploadServer;
        this.redisService = redisService;
        this.patrolTaskInfoService = patrolTaskInfoService;
        this.WebsocketService = WebsocketService;
        this.patrolTaskService = patrolTaskService;
    }

    //@PostMapping("/new/picAnalyseRetNotify")
    @PostMapping
    public Response<Object> picAnalyseRetNotify(@RequestBody String picAnalyseResult) {
        try {
            AnalyseResult analyseResult = JSONObject.parseObject(picAnalyseResult, AnalyseResult.class);
            analysisService.picAnalyseRetNotify(analyseResult);
            return Response.ok();
        } catch (Exception e) {
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 跳过61上报，直接验证初筛、大模型流程
     * 该接口仅用于“调试”
     * @param analyseRequest
     * @return
     */
    @PostMapping("/sendRequest")
    public AjaxResult sendRequest(@RequestBody AnalyseRequest analyseRequest) {
        logger.info("sendRequest: {}", analyseRequest);
        String requestDataToRedis = new Gson().toJson(analyseRequest);
        redisService.redisTemplate.opsForList().rightPush(AnalyseConstants.ALGORITHM_REQUEST_QUEUE, requestDataToRedis);
        return AjaxResult.success();
    }

    @PostMapping("/old/picAnalyseRetNotify")
    public AjaxResult add(@RequestBody final String alarmDefect) {
        System.out.println(alarmDefect);
        logger.info("alarmDefect: {}", alarmDefect);
        try {
            AnalyseResult analyseResult = JSONObject.parseObject(alarmDefect, AnalyseResult.class);
            (new Thread(() -> {
                logger.info("[ANALYSIS] doAnalysis task start");
                try {
                    Thread.sleep(2000L);
                    doAlgorithmAnalysisOld(analyseResult);
                } catch (InterruptedException e) {
                    logger.error("[ANALYSIS] doAnalysis task EXCEPTION: {}", e.getMessage());
                }

                logger.info("[ANALYSIS] doAnalysis task finish");
            })).start();
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error(400, "格式错误");
        }

    }

    public void doAlgorithmAnalysisOld(AnalyseResult analyseResult) {
        logger.info("[ANALYSIS]: DO ANALYSIS BODY: {}", analyseResult);
        int size = 0;
        String taskId = "";
        String requestId = analyseResult.getRequestId();
        String taskPatrolId = redisService.getCacheObject(RedisConst.REQUEST_UUID + requestId);
        logger.info("[ANALYSIS] requestId: {}, taskPatrolId: {}", requestId, taskPatrolId);
        Map<String, Long> deviceIdLineIdMap = new HashMap<>();
        PatrolTaskResultMain taskResultMain = new PatrolTaskResultMain();
        taskResultMain.setTaskPatrolledId(taskPatrolId);
        List<PatrolTaskResultMain> patrolTaskResultMainList = patrolTaskResultMainService.selectPatrolTaskResultMainList(taskResultMain);
        if (!patrolTaskResultMainList.isEmpty()) {
            PatrolTaskResultMain patrolTaskResultMain = patrolTaskResultMainList.get(0);
            taskId = patrolTaskResultMain.getTaskId();
            PatrolResult patrolResult = new PatrolResult();
            patrolResult.setMainId(String.valueOf(patrolTaskResultMain.getLineId()));
            logger.info("[ANALYSIS] taskId: {}, lineId: {}", taskId, patrolTaskResultMain.getLineId());
            List<PatrolResult> patrolResultList = patrolResultService.selectPatrolResultList(patrolResult);
            size = patrolResultList.size();
            logger.info("[ANALYSIS] mainId {}, patrolResultList size: {}", patrolResult.getMainId(), size);
            for (PatrolResult result : patrolResultList) {
                //logger.info("[ANALYSIS] arr.getDeviceId(): {}, arr.getLineId(): {}", arr.getDeviceId(), arr.getLineId());
                deviceIdLineIdMap.put(result.getDeviceId(), result.getLineId());
            }
        }

        List<AnalyseResItem> resContentList = analyseResult.getResultList();
        logger.info(Color.GREEN + "<=============分析算法模块返回的表计识别结果old==================>" + Color.END);
        logger.info(Color.GREEN + "[ANALYSIS] meter algorithm resContentList: {}" + Color.END, resContentList);
        if (!resContentList.isEmpty()) {
            List<WebsocketData> websocketDataArrayList = new ArrayList<>();
            for (AnalyseResItem algorithmResult : resContentList) {
                Long lineId = deviceIdLineIdMap.get(algorithmResult.getObjectId());
                logger.info("[ANALYSIS] resultList lineId: {}, objectId: {}", lineId, algorithmResult.getObjectId());
                ResultAnalysis resultAnalysis = new ResultAnalysis();
                resultAnalysis.setBusinessId(String.valueOf(lineId));
                resultAnalysis.setResultContent(new Gson().toJson(analyseResult));
                resultAnalysis.setResultType("1");
                resultAnalysis.setObjectId(algorithmResult.getObjectId());
                List<AnalyseResPoint> resultsList = algorithmResult.getResults();
                String value = "";
                List<String> typeList = new ArrayList<>();
                String description;
                String objectId;
                for (Iterator<AnalyseResPoint> iterator = resultsList.iterator(); iterator.hasNext(); resultAnalysis.setDescription(description)) {
                    AnalyseResPoint algorithmInnerResult = iterator.next();
                    value = algorithmInnerResult.getValue();
                    String code = algorithmInnerResult.getCode();
                    description = algorithmInnerResult.getDesc();
                    objectId = algorithmInnerResult.getType();
                    if (StringUtils.isNotEmpty(objectId)) {
                        typeList.add(objectId);
                    }

                    logger.info("[ANALYSIS] RESULT CODE: {}, DESC: {}", code, description);
                    if ("meter normal".equals(description)) {
                        description = messageUtils.get("识别完成");
                    }

                    resultAnalysis.setCreateTime(new Date());
                    switch (value) {
                        case "0":
                            resultAnalysis.setPointStatus("1");
                            resultAnalysis.setResultType("1");
                            resultAnalysis.setResStatus("1");
                            break;
                        case "1":
                            resultAnalysis.setPointStatus("0");
                            resultAnalysis.setResultType("0");
                            resultAnalysis.setResStatus("0");
                            break;
                        case "-1":
                            resultAnalysis.setPointStatus("0");
                            resultAnalysis.setResultType("2");
                            resultAnalysis.setResStatus("0");
                            break;
                        default:
                            resultAnalysis.setPointStatus("1");
                            resultAnalysis.setResultType("1");
                            resultAnalysis.setResStatus("1");
                            break;
                    }

                    if (!code.equals("2000")) {
                        resultAnalysis.setResultType("3");
                        description = "GET PICTURE FAIL";
                    }
                }

                logger.info("[ANALYSIS] BEFORE resultAnalysis: {}", resultAnalysis);
                try {
                    setAllStatus(resultAnalysis);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                logger.info("[ANALYSIS] AFTER resultAnalysis: {}", resultAnalysis);
                if (StringUtils.isNotEmpty(resultAnalysis.getBusinessId())) {
                    ResultAnalysis analysis = new ResultAnalysis();
                    analysis.setBusinessId(resultAnalysis.getBusinessId());
                    List<ResultAnalysis> resultAnalyses = resultAnalysisService.selectResultAnalysisList(analysis);
                    if (resultAnalyses.isEmpty()) {
                        int analysisRes = resultAnalysisService.insertResultAnalysis(resultAnalysis);
                        logger.info(Color.GREEN + "[ANALYSIS] INSERT analysisRes: {}, lineId: {}" + Color.END, analysisRes, resultAnalysis.getLineId());
                    }
                }

                PatrolResult patrolResult = patrolResultService.selectPatrolResultByLineId(lineId);
                if (StringUtils.isNotEmpty(value) && patrolResult != null) {
                    patrolResult.setValue(value);
                }

                String isAlgType = "";
                if (!typeList.isEmpty()) {
                    List<String> typeListAgain = new ArrayList<>();
                    Iterator<String> iterator = typeList.iterator();
                    while (true) {
                        if (!iterator.hasNext()) {
                            if (!typeListAgain.isEmpty()) {
                                patrolResult.setRecognitionType(String.join(StringUtils.COMMA, typeListAgain));
                            }
                            break;
                        }

                        objectId = iterator.next();
                        String[] types = objectId.split(StringUtils.COMMA);
                        for (String type : types) {
                            Map<String, String> algType = patrolResultService.selectAlgTypeByCode(type);
                            if (StringUtils.isEmpty(isAlgType) && algType != null && algType.get("alg_name") != null && algType.get("alg_name").equals("缺陷识别")) {
                                isAlgType = "1";
                            }

                            System.out.println(type);
                            Map<String, String> algmap = patrolResultService.selectAlgTypeDataType(type);
                            if (algmap != null && StringUtils.isNotEmpty(algmap.get("remark"))) {
                                typeListAgain.add(algmap.get("remark"));
                            }
                        }
                    }
                }

                if (StringUtils.isNotEmpty(isAlgType) && isAlgType.equals("1")) {
                    if (resultAnalysis.getResultType().equals("1")) {
                        patrolResult.setValueUnit(messageUtils.get("无缺陷"));
                    } else {
                        patrolResult.setValueUnit(messageUtils.get("有缺陷"));
                    }
                }

                Map<String, String> valueMap = patrolResultService.getPatrolResultValue(patrolResult);
                if (null != valueMap && !valueMap.isEmpty()) {
                    if (valueMap.containsKey("value") && null != valueMap.get("value")) {
                        description = valueMap.get("value");
                        patrolResult.setValue(description);
                    }

                    if (valueMap.containsKey("value_unit") && null != valueMap.get("value_unit")) {
                        description = valueMap.get("value_unit");
                        patrolResult.setValueUnit(description);
                    }
                }

                patrolResultService.updatePatrolResult(patrolResult);
                WebsocketData webData = new WebsocketData();
                webData.setTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, new Date()));
                objectId = algorithmResult.getObjectId();
                webData.setDevId(objectId);
                webData.setDesc(resultAnalysis.getDescription());
                websocketDataArrayList.add(webData);
            }

            PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
            patrolTaskInfo.setTaskMajorId(taskId);
            List<PatrolTaskInfo> arr = patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
            Set<String> point = new HashSet<>();
            for (PatrolTaskInfo ass : arr) {
                if (StringUtils.isNotEmpty(ass.getDeviceId())) {
                    point.add(ass.getDeviceId());
                }
            }

            if (point.size() == size) {
                boolean bRes = redisService.deleteObject(requestId);
                logger.info("[ANALYSIS] CLEAR requestId FROM REDIS: {}", bRes);
            }
        }
    }

    public void setAllStatus(ResultAnalysis resultAnalysis) {
        Set<String> stringSet = new HashSet<>();
        Set<String> pointStatus = new HashSet<>();
        Set<String> restype = new HashSet<>();
        String devId = resultAnalysis.getObjectId();
        JSONObject parseObject = JSONObject.parseObject(resultAnalysis.getResultContent());
        Object jsonArray = parseObject.get("resultList");
        List<resultList> resContentList = JSONArray.parseArray(jsonArray + "", resultList.class);
        if (!resContentList.isEmpty()) {
            List<results> results = resContentList.get(0).getResults();
            if (!results.isEmpty()) {
                for (com.inspect.analysis.domain.results arr : results) {
                    arr.setType("meter");
                    logger.info("[ANALYSIS] ??????????????????????????arr: {}", arr);
                    String arrType = arr.getType();
                    String arrValue = arr.getValue();
                    String[] types = arrType.split(StringUtils.COMMA);
                    String[] values = arrValue.split(StringUtils.COMMA);

                    for (int i = 0; i < types.length; ++i) {
                        if (!StringUtils.isEmpty(types[i])) {
                            String type = types[i];
                            String value = values[i];
                            if (type.equals("isolator")) {
                                if (value.equals("3")) {
                                    stringSet.add("0");
                                    pointStatus.add("0");
                                    restype.add("0");
                                } else if (value.equals("4")) {
                                    stringSet.add("0");
                                    pointStatus.add("0");
                                    restype.add("0");
                                } else {
                                    stringSet.add("1");
                                    pointStatus.add("1");
                                    restype.add("1");
                                }
                            }

                            if (type.equals("switch")) {
                                stringSet.add("1");
                                pointStatus.add("1");
                                restype.add("1");
                            }

                            Map map;
                            String alarm_threshold;
                            double lower_value;
                            double upper_value;
                            JSONArray jsonArrayinfrared;
                            int a;
                            JSONObject jSONObjectinfrared;
                            double valuedoule;
                            if (type.equals("meter")) {
                                this.logger.info("===============(type.equals(\"meter\")=======1===========");
                                map = this.resultAnalysisService.selectPointInfoById(devId);
                                alarm_threshold = (String) map.get("alarm_threshold");
                                lower_value = 0.0D;
                                upper_value = 0.0D;
                                if (alarm_threshold != null) {
                                    jsonArrayinfrared = JSONArray.parseArray(alarm_threshold);

                                    for (a = 0; a < jsonArrayinfrared.size(); ++a) {
                                        jSONObjectinfrared = JSONObject.parseObject(jsonArrayinfrared.get(a) + "");
                                        if (jSONObjectinfrared.get("code") != null && "meter".equals(jSONObjectinfrared.get("code") + "")) {
                                            if (jSONObjectinfrared.get("upperValue") != null) {
                                                //upper_value = Double.parseDouble(jSONObjectinfrared.get("upperValue") + "");
                                                //qinyl
                                                upper_value = 10.0;
                                            }

                                            if (jSONObjectinfrared.get("lowerValue") != null) {
                                                //lower_value = Double.parseDouble(jSONObjectinfrared.get("lowerValue") + "");
                                                //qinyl
                                                upper_value = 100.0;
                                            }
                                        }
                                    }
                                }

                                logger.info("===============(type.equals(\"meter\")=======2=========== : {}", value);
                                if (upper_value != 0.0D) {
                                    valuedoule = 0.0D;
                                    if (StringUtils.isNotEmpty(value)) {
                                        valuedoule = Double.parseDouble(value);
                                        if (valuedoule > lower_value && valuedoule < upper_value) {
                                            stringSet.add("0");
                                            pointStatus.add("1");
                                            restype.add("1");
                                            resultAnalysis.setDescription(messageUtils.get("数值正常"));
                                        } else {
                                            stringSet.add("0");
                                            pointStatus.add("2");
                                            restype.add("0");
                                            if (valuedoule < lower_value) {
                                                resultAnalysis.setDescription(messageUtils.get("数值小于告警阈值最小值"));
                                            }

                                            if (valuedoule > upper_value) {
                                                resultAnalysis.setDescription(messageUtils.get("数值大于告警阈值最大值"));
                                            }
                                        }
                                    } else {
                                        stringSet.add("0");
                                        pointStatus.add("0");
                                        restype.add("2");
                                    }
                                }
                            }

                            if (type.equals("infrared")) {
                                map = resultAnalysisService.selectPointInfoById(devId);
                                alarm_threshold = (String) map.get("alarm_threshold");
                                lower_value = 0.0D;
                                upper_value = 0.0D;
                                if (alarm_threshold != null) {
                                    jsonArrayinfrared = JSONArray.parseArray(alarm_threshold);

                                    for (a = 0; a < jsonArrayinfrared.size(); ++a) {
                                        jSONObjectinfrared = JSONObject.parseObject(jsonArrayinfrared.get(a) + "");
                                        if (jSONObjectinfrared.get("code") != null && "infrared".equals(jSONObjectinfrared.get("code") + "")) {
                                            if (jSONObjectinfrared.get("upperValue") != null) {
                                                upper_value = Double.parseDouble(jSONObjectinfrared.get("upperValue") + "");
                                            }

                                            if (jSONObjectinfrared.get("lowerValue") != null) {
                                                lower_value = Double.parseDouble(jSONObjectinfrared.get("lowerValue") + "");
                                            }
                                        }
                                    }
                                }

                                if (lower_value == 0.0D && upper_value == 0.0D) {
                                    stringSet.add("1");
                                    pointStatus.add("1");
                                    restype.add("1");
                                } else {
                                    valuedoule = Double.parseDouble(value);
                                    if (valuedoule > lower_value && valuedoule < upper_value) {
                                        stringSet.add("1");
                                        pointStatus.add("1");
                                        restype.add("1");
                                    } else {
                                        stringSet.add("0");
                                        pointStatus.add("0");
                                        restype.add("0");
                                    }
                                }
                            }

                            if (type.equals("sound")) {
                                if (value.equals("1")) {
                                    stringSet.add("1");
                                    pointStatus.add("1");
                                    restype.add("1");
                                } else {
                                    stringSet.add("0");
                                    pointStatus.add("0");
                                    restype.add("0");
                                }
                            }

                            if (type.equals("light")) {
                                stringSet.add("1");
                                pointStatus.add("1");
                                restype.add("1");
                            }

                            if (type.equals("qrcode")) {
                                stringSet.add("1");
                                pointStatus.add("1");
                                restype.add("1");
                                if (StringUtils.isNotEmpty(resultAnalysis.getBusinessId())) {
                                    Long lineId = Long.valueOf(resultAnalysis.getBusinessId());
                                    PatrolResult patrolResult = patrolResultService.selectPatrolResultByLineId(lineId);
                                    if (patrolResult != null) {
                                        patrolResult.setMaterialId(value);
                                        patrolResultService.updatePatrolResult(patrolResult);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        String restypeStr;
        if (!stringSet.isEmpty()) {
            restypeStr = String.join(StringUtils.COMMA, stringSet);
            if (!resultAnalysis.getResultType().equals("0")) {
                if (restypeStr.contains("0")) {
                    resultAnalysis.setResStatus("0");
                } else {
                    resultAnalysis.setResStatus("1");
                }
            }
        }

        if (!pointStatus.isEmpty()) {
            restypeStr = String.join(StringUtils.COMMA, pointStatus);
            if (restypeStr.contains("0")) {
                resultAnalysis.setPointStatus("0");
            } else if (restypeStr.contains("1")) {
                resultAnalysis.setPointStatus("1");
            } else {
                resultAnalysis.setPointStatus("2");
            }
        }

        if (!restype.isEmpty()) {
            restypeStr = String.join(StringUtils.COMMA, restype);
            if (restypeStr.contains("0")) {
                resultAnalysis.setResultType("0");
            } else if (restypeStr.contains("1")) {
                resultAnalysis.setResultType("1");
            } else {
                resultAnalysis.setResultType("2");
            }
        }
    }

    public void SendToSJ(PatrolResult patrolResult, ResultAnalysis resultAnalysis) {
        String taskType = "";
        if (patrolResult.getTaskCode() != null) {
            PatrolTask patrolTask = new PatrolTask();
            patrolTask.setTaskCode(patrolResult.getTaskCode());
            List<PatrolTask> taskList = this.patrolTaskService.selectPatrolTaskList(patrolTask);
            if (!taskList.isEmpty()) {
                PatrolTask task = taskList.get(0);
                if (StringUtils.isNotEmpty(task.getType())) {
                    taskType = task.getType();
                }
            }
        }

        SendMsgToUpperLevel sendMsgToUpperLevel = new SendMsgToUpperLevel();
        String sendCode = "";
        Map<String, String> stringMap = this.patrolResultService.selectBasedataStation();
        String stationNo = stringMap.get("station_no");
        String stationName = stringMap.get("station_name");
        BasedataEqpBookMoMain based = new BasedataEqpBookMoMain();
        based.setType("20");
        List<BasedataEqpBookMoMain> basedataEqpBookMoMains = this.patrolResultService.selectBasedataEqpBookList(based);
        if (!basedataEqpBookMoMains.isEmpty()) {
            sendCode = basedataEqpBookMoMains.get(0).getPatrolDeviceCode();
        }

        sendMsgToUpperLevel.setSendCode(sendCode);
        ArrayList list;
        MsgToUpperLevel msgToUpperLevel;
        String alermType;
        String str;
        if (taskType.equals("6")) {
            sendMsgToUpperLevel.setType("63");
            list = new ArrayList<>();
            msgToUpperLevel = new MsgToUpperLevel();
            if (StringUtils.isNotEmpty(patrolResult.getPatrolDeviceCode())) {
                msgToUpperLevel.setPatrolDeviceCode(patrolResult.getPatrolDeviceCode());
            } else {
                msgToUpperLevel.setPatrolDeviceCode("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getPatrolDeviceName())) {
                msgToUpperLevel.setPatrolDeviceName(patrolResult.getPatrolDeviceName());
            } else {
                msgToUpperLevel.setPatrolDeviceName("");
            }

            msgToUpperLevel.setAlarmLevel("4");
            alermType = "201";
            alermType = this.silenceToAlarmType(resultAnalysis);
            msgToUpperLevel.setMonitorType(alermType);
            if (StringUtils.isNotEmpty(patrolResult.getFileType())) {
                msgToUpperLevel.setFileType(patrolResult.getFileType());
            } else {
                msgToUpperLevel.setFileType("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getFilePath())) {
                msgToUpperLevel.setFilePath(patrolResult.getFilePath());
            } else {
                msgToUpperLevel.setFilePath("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getTime())) {
                msgToUpperLevel.setTime(patrolResult.getTime());
            } else {
                msgToUpperLevel.setTime("");
            }

            if (StringUtils.isNotEmpty(resultAnalysis.getDescription())) {
                msgToUpperLevel.setContent(resultAnalysis.getDescription());
            } else {
                msgToUpperLevel.setContent("");
            }

            list.add(msgToUpperLevel);
            sendMsgToUpperLevel.setItem(list);
            str = JSONObject.toJSONString(sendMsgToUpperLevel);
            this.feignTaskClient.senMessageToZk("63", str);
        } else {
            sendMsgToUpperLevel.setCode(stationNo);
            sendMsgToUpperLevel.setType("62");
            list = new ArrayList<>();
            msgToUpperLevel = new MsgToUpperLevel();
            if (StringUtils.isNotEmpty(patrolResult.getPatrolDeviceCode())) {
                msgToUpperLevel.setPatrolDeviceCode(patrolResult.getPatrolDeviceCode());
            } else {
                msgToUpperLevel.setPatrolDeviceCode("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getPatrolDeviceName())) {
                msgToUpperLevel.setPatrolDeviceName(patrolResult.getPatrolDeviceName());
            } else {
                msgToUpperLevel.setPatrolDeviceName("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getTaskName())) {
                msgToUpperLevel.setTaskName(patrolResult.getTaskName());
            } else {
                msgToUpperLevel.setTaskName("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getTaskCode())) {
                msgToUpperLevel.setTaskCode(patrolResult.getTaskCode());
            } else {
                msgToUpperLevel.setTaskCode("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getDeviceNam())) {
                msgToUpperLevel.setDeviceName(patrolResult.getDeviceNam());
            } else {
                msgToUpperLevel.setDeviceName("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getDeviceId())) {
                msgToUpperLevel.setDeviceId(patrolResult.getDeviceId());
            } else {
                msgToUpperLevel.setDeviceId("");
            }

            msgToUpperLevel.setAlarmLevel("4");
            alermType = "6";
            alermType = this.toAlarmType(resultAnalysis);
            msgToUpperLevel.setAlarmType(alermType);
            if (StringUtils.isNotEmpty(patrolResult.getRecognitionType())) {
                if (patrolResult.getRecognitionType().contains("x")) {
                    msgToUpperLevel.setRecognitionType("3");
                } else {
                    msgToUpperLevel.setRecognitionType(patrolResult.getRecognitionType());
                }
            } else {
                msgToUpperLevel.setRecognitionType("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getFileType())) {
                msgToUpperLevel.setFileType(patrolResult.getFileType());
            } else {
                msgToUpperLevel.setFileType("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getFilePath())) {
                msgToUpperLevel.setFilePath(patrolResult.getFilePath());
            } else {
                msgToUpperLevel.setFilePath("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getValue())) {
                msgToUpperLevel.setValue(patrolResult.getValue());
            } else {
                msgToUpperLevel.setValue("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getValueUnit())) {
                msgToUpperLevel.setValueUnit(patrolResult.getValueUnit());
            } else {
                msgToUpperLevel.setValueUnit("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getUnit())) {
                msgToUpperLevel.setUnit(patrolResult.getUnit());
            } else {
                msgToUpperLevel.setUnit("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getTime())) {
                msgToUpperLevel.setTime(patrolResult.getTime());
            } else {
                msgToUpperLevel.setTime("");
            }

            if (StringUtils.isNotEmpty(patrolResult.getTaskPatrolledId())) {
                msgToUpperLevel.setTaskPatrolledId(patrolResult.getTaskPatrolledId());
            } else {
                msgToUpperLevel.setTaskPatrolledId("");
            }

            if (StringUtils.isNotEmpty(resultAnalysis.getDescription())) {
                msgToUpperLevel.setContent(resultAnalysis.getDescription());
            } else {
                msgToUpperLevel.setContent("");
            }

            list.add(msgToUpperLevel);
            sendMsgToUpperLevel.setItem(list);
            str = JSONObject.toJSONString(sendMsgToUpperLevel);
            this.feignTaskClient.senMessageToZk("62", str);
        }

    }

    public String toAlarmType(ResultAnalysis resultAnalysis) {
        String types = "";
        JSONObject parseObject = JSONObject.parseObject(resultAnalysis.getResultContent());
        Object jsonArray = parseObject.get("resultList");
        List<resultList> resContentList = JSONArray.parseArray(jsonArray.toString(), resultList.class);
        if (!resContentList.isEmpty()) {
            List<results> results = resContentList.get(0).getResults();
            if (!results.isEmpty()) {
                Iterator<com.inspect.analysis.domain.results> iterator = results.iterator();
                while (true) {
                    String type;
                    do {
                        if (!iterator.hasNext()) {
                            return types;
                        }

                        results arr = iterator.next();
                        type = arr.getType();
                    } while (!StringUtils.isNotEmpty(type));

                    String[] texts = type.split(StringUtils.COMMA);

                    for (String text : texts) {
                        types = this.ToAlarmTypeInfo(text);
                    }
                }
            }
        }

        return types;
    }

    public String ToAlarmTypeInfo(String type) {
        String str;
        byte algorithmId = -1;
        if (type.equals("bj_bpmh")) {
            algorithmId = 0;
        } else if (type.equals("bj_bpps")) {
            algorithmId = 1;
        } else if (type.equals("bj_wkps")) {
            algorithmId = 2;
        } else if (type.equals("jyz_pl")) {
            algorithmId = 3;
        } else if (type.equals("sly_bjbmyw")) {
            algorithmId = 4;
        } else if (type.equals("sly_dmyw")) {
            algorithmId = 5;
        } else if (type.equals("jsxs")) {
            algorithmId = 6;
        } else if (type.equals("hxq_gjtps")) {
            algorithmId = 7;
        } else if (type.equals("xmbhyc")) {
            algorithmId = 8;
        } else if (type.equals("yw_gkxfw")) {
            algorithmId = 9;
        } else if (type.equals("yw_nc")) {
            algorithmId = 10;
        } else if (type.equals("mcqdmsh")) {
            algorithmId = 11;
        } else if (type.equals("gbps")) {
            algorithmId = 12;
        } else if (type.equals("gjptwss")) {
            algorithmId = 13;
        } else if (type.equals("bmwh")) {
            algorithmId = 14;
        } else if (type.equals("yxcr")) {
            algorithmId = 15;
        } else if (type.equals("wcaqm")) {
            algorithmId = 16;
        } else if (type.equals("wcgz")) {
            algorithmId = 17;
        } else if (type.equals("xy")) {
            algorithmId = 18;
        } else if (type.equals("bjdsyc")) {
            algorithmId = 19;
        } else if (type.equals("ywzt_yfyc")) {
            algorithmId = 20;
        } else if (type.equals("hxq_gjbs")) {
            algorithmId = 21;
        } else if (type.equals("kgg_ybh")) {
            algorithmId = 22;
        } else if (type.equals("kgg_ybf")) {
            algorithmId = 23;
        } else if (type.equals("dthtps")) {
            algorithmId = 24;
        } else if (type.equals("yxdghsg")) {
            algorithmId = 25;
        } else if (type.equals("wpdaqs")) {
            algorithmId = 26;
        } else if (type.equals("rydd")) {
            algorithmId = 27;
        } else if (type.equals("hzyw")) {
            algorithmId = 28;
        } else if (type.equals("sndmjs")) {
            algorithmId = 29;
        } else if (type.equals("qmls")) {
            algorithmId = 30;
        } else if (type.equals("wdls")) {
            algorithmId = 31;
        } else if (type.equals("xdwcr")) {
            algorithmId = 32;
        } else if (type.equals("ywzt_ywzsjyc")) {
            algorithmId = 33;
        } else if (type.equals("hxq_yfps")) {
            algorithmId = 34;
        } else if (type.equals("dxdg")) {
            algorithmId = 35;
        } else if (type.equals("sly_jhbyw")) {
            algorithmId = 36;
        } else if (type.equals("hkgnl")) {
            algorithmId = 37;
        } else if (type.equals("pzqcd")) {
            algorithmId = 38;
        } else if (type.equals("drqgd")) {
            algorithmId = 39;
        } else if (type.equals("tx_pb")) {
            algorithmId = 40;
        } else if (type.equals("tx_yzwpy")) {
            algorithmId = 41;
        } else if (type.equals("isolator")) {
            algorithmId = 42;
        } else if (type.equals("switch")) {
            algorithmId = 43;
        } else if (type.equals("meter")) {
            algorithmId = 44;
        } else if (type.equals("infrared")) {
            algorithmId = 45;
        } else if (type.equals("sound")) {
            algorithmId = 46;
        } else if (type.equals("light")) {
            algorithmId = 47;
        }

        switch (algorithmId) {
            case 0:
                str = "6";
            case 1:
                str = "6";
            case 2:
                str = "6";
            case 3:
                str = "6";
            case 4:
                str = "6";
            case 5:
                str = "6";
            case 6:
                str = "6";
            case 7:
                str = "6";
            case 8:
                str = "6";
            case 9:
                str = "6";
            case 10:
                str = "6";
            case 11:
                str = "6";
            case 12:
                str = "6";
            case 13:
                str = "6";
            case 14:
                str = "6";
            case 15:
                str = "6";
            case 16:
                str = "6";
            case 17:
                str = "6";
            case 18:
                str = "6";
            case 19:
                str = "9";
            case 20:
                str = "8";
            case 21:
                str = "6";
            case 22:
                str = "10";
            case 23:
                str = "10";
            case 24:
                str = "6";
            case 25:
                str = "6";
            case 26:
                str = "6";
            case 27:
                str = "6";
            case 28:
                str = "6";
            case 29:
                str = "6";
            case 30:
                str = "6";
            case 31:
                str = "6";
            case 32:
                str = "6";
            case 33:
                str = "8";
            case 34:
                str = "6";
            case 35:
                str = "6";
            case 36:
                str = "6";
            case 37:
                str = "6";
            case 38:
                str = "6";
            case 39:
                str = "6";
            case 40:
                str = "6";
            case 41:
                str = "10";
            case 42:
                str = "10";
            case 43:
                str = "10";
            case 44:
                str = "8";
            case 45:
                str = "2";
            case 46:
                str = "5";
            case 47:
                str = "6";
            default:
                str = "6";
                return str;
        }
    }

    public String silenceToAlarmType(ResultAnalysis resultAnalysis) {
        String types = "";
        JSONObject parseObject = JSONObject.parseObject(resultAnalysis.getResultContent());
        Object jsonArray = parseObject.get("resultList");
        List<resultList> resContentList = JSONArray.parseArray(jsonArray.toString(), resultList.class);
        if (!resContentList.isEmpty()) {
            List<results> results = resContentList.get(0).getResults();
            if (!results.isEmpty()) {
                Iterator<com.inspect.analysis.domain.results> iterator = results.iterator();
                while (true) {
                    String type;
                    do {
                        if (!iterator.hasNext()) {
                            return types;
                        }

                        results arr = iterator.next();
                        type = arr.getType();
                    } while (!StringUtils.isNotEmpty(type));

                    String[] texts = type.split(StringUtils.COMMA);

                    for (String text : texts) {
                        types = this.toSilenceAlarmTypeInfo(text);
                    }
                }
            }
        }

        return types;
    }

    public String toSilenceAlarmTypeInfo(String type) {
        String str = "";
        byte var4 = -1;
        switch (type.hashCode()) {
            case -2030904188:
                if (type.equals("tx_yzwpy")) {
                    var4 = 41;
                }
                break;
            case -1388323807:
                if (type.equals("bjdsyc")) {
                    var4 = 19;
                }
                break;
            case -1321710433:
                if (type.equals("dthtps")) {
                    var4 = 24;
                }
                break;
            case -1309035312:
                if (type.equals("sly_bjbmyw")) {
                    var4 = 4;
                }
                break;
            case -1144801872:
                if (type.equals("jyz_pl")) {
                    var4 = 3;
                }
                break;
            case -979057518:
                if (type.equals("hxq_gjbs")) {
                    var4 = 21;
                }
                break;
            case -978524690:
                if (type.equals("hxq_yfps")) {
                    var4 = 34;
                }
                break;
            case -897940371:
                if (type.equals("sndmjs")) {
                    var4 = 29;
                }
                break;
            case -889473228:
                if (type.equals("switch")) {
                    var4 = 43;
                }
                break;
            case -819175162:
                if (type.equals("sly_dmyw")) {
                    var4 = 5;
                }
                break;
            case -781588040:
                if (type.equals("wpdaqs")) {
                    var4 = 26;
                }
                break;
            case -774479159:
                if (type.equals("kgg_ybf")) {
                    var4 = 23;
                }
                break;
            case -774479157:
                if (type.equals("kgg_ybh")) {
                    var4 = 22;
                }
                break;
            case -760747946:
                if (type.equals("ywzt_ywzsjyc")) {
                    var4 = 33;
                }
                break;
            case -755782075:
                if (type.equals("xmbhyc")) {
                    var4 = 8;
                }
                break;
            case -750181990:
                if (type.equals("yxdghsg")) {
                    var4 = 25;
                }
                break;
            case -285994666:
                if (type.equals("hxq_gjtps")) {
                    var4 = 7;
                }
                break;
            case -93497344:
                if (type.equals("bj_bpmh")) {
                    var4 = 0;
                }
                break;
            case -93497240:
                if (type.equals("bj_bpps")) {
                    var4 = 1;
                }
                break;
            case -92876434:
                if (type.equals("bj_wkps")) {
                    var4 = 2;
                }
                break;
            case 3841:
                if (type.equals("xy")) {
                    var4 = 18;
                }
                break;
            case 3028060:
                if (type.equals("bmwh")) {
                    var4 = 14;
                }
                break;
            case 3097623:
                if (type.equals("dxdg")) {
                    var4 = 35;
                }
                break;
            case 3166238:
                if (type.equals("gbps")) {
                    var4 = 12;
                }
                break;
            case 3219376:
                if (type.equals("hzyw")) {
                    var4 = 28;
                }
                break;
            case 3272196:
                if (type.equals("jsxs")) {
                    var4 = 6;
                }
                break;
            case 3474595:
                if (type.equals("qmls")) {
                    var4 = 30;
                }
                break;
            case 3515655:
                if (type.equals("rydd")) {
                    var4 = 27;
                }
                break;
            case 3643583:
                if (type.equals("wcgz")) {
                    var4 = 17;
                }
                break;
            case 3644692:
                if (type.equals("wdls")) {
                    var4 = 31;
                }
                break;
            case 3723214:
                if (type.equals("yxcr")) {
                    var4 = 15;
                }
                break;
            case 65296784:
                if (type.equals("gjptwss")) {
                    var4 = 13;
                }
                break;
            case 95860160:
                if (type.equals("drqgd")) {
                    var4 = 39;
                }
                break;
            case 99336322:
                if (type.equals("hkgnl")) {
                    var4 = 37;
                }
                break;
            case 102970646:
                if (type.equals("light")) {
                    var4 = 47;
                }
                break;
            case 103787401:
                if (type.equals("meter")) {
                    var4 = 44;
                }
                break;
            case 107180616:
                if (type.equals("pzqcd")) {
                    var4 = 38;
                }
                break;
            case 109627663:
                if (type.equals("sound")) {
                    var4 = 46;
                }
                break;
            case 110798221:
                if (type.equals("tx_pb")) {
                    var4 = 40;
                }
                break;
            case 112945137:
                if (type.equals("wcaqm")) {
                    var4 = 16;
                }
                break;
            case 113919162:
                if (type.equals("xdwcr")) {
                    var4 = 32;
                }
                break;
            case 115385974:
                if (type.equals("yw_nc")) {
                    var4 = 10;
                }
                break;
            case 181105857:
                if (type.equals("infrared")) {
                    var4 = 45;
                }
                break;
            case 380744003:
                if (type.equals("sly_jhbyw")) {
                    var4 = 36;
                }
                break;
            case 575780445:
                if (type.equals("isolator")) {
                    var4 = 42;
                }
                break;
            case 895384761:
                if (type.equals("mcqdmsh")) {
                    var4 = 11;
                }
                break;
            case 1483606916:
                if (type.equals("yw_gkxfw")) {
                    var4 = 9;
                }
                break;
            case 1596063710:
                if (type.equals("ywzt_yfyc")) {
                    var4 = 20;
                }
        }

        switch (var4) {
            case 0:
                str = "201";
            case 1:
                str = "201";
            case 2:
                str = "201";
            case 3:
                str = "201";
            case 4:
                str = "201";
            case 5:
                str = "202";
            case 6:
                str = "201";
            case 7:
                str = "201";
            case 8:
                str = "201";
            case 9:
                str = "201";
            case 10:
                str = "103";
            case 11:
                str = "101";
            case 12:
                str = "201";
            case 13:
                str = "201";
            case 14:
                str = "202";
            case 15:
                str = "2";
            case 16:
                str = "1";
            case 17:
                str = "3";
            case 18:
                str = "4";
            case 19:
                str = "201";
            case 20:
                str = "202";
            case 21:
                str = "201";
            case 22:
                str = "201";
            case 23:
                str = "201";
            case 24:
                str = "201";
            case 25:
                str = "201";
            case 26:
                str = "1";
            case 27:
                str = "4";
            case 28:
                str = "101";
            case 29:
                str = "102";
            case 30:
                str = "102";
            case 31:
                str = "102";
            case 32:
                str = "103";
            case 33:
                str = "202";
            case 34:
                str = "202";
            case 35:
                str = "201";
            case 36:
                str = "202";
            case 37:
                str = "201";
            case 38:
                str = "201";
            case 39:
                str = "201";
            case 40:
                str = "201";
            case 41:
                str = "101";
            case 42:
                str = "201";
            case 43:
                str = "201";
            case 44:
                str = "201";
            case 45:
                str = "101";
            case 46:
                str = "101";
            case 47:
                str = "101";
            default:
                str = "201";
                return str;
        }
    }

    @GetMapping({"/send"})
    public AjaxResult getInfo(String taskCode, String analysisId) {
        if (StringUtils.isEmpty(taskCode)) {
            return this.error("taskCode empty!");
        }
        if (StringUtils.isEmpty(analysisId)) {
            return this.error("analysisId empty!");
        }
        PatrolResult patrolResult = new PatrolResult();
        patrolResult.setTaskCode(taskCode);
        ResultAnalysis resultAnalysis =
                this.resultAnalysisService.selectResultAnalysisByLineId(Long.valueOf(analysisId));
        this.SendToSJ(patrolResult, resultAnalysis);
        return this.toAjax(1);
    }
}
