package com.inspect.partrolresult.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.ResultAnalysis;
import com.inspect.analysis.service.IResultAnalysisService;
import com.inspect.base.core.constant.AlgConstants;
import com.inspect.base.core.constant.Color;
import com.inspect.base.core.constant.RedisConst;
import com.inspect.base.core.domain.DataMsg;
import com.inspect.base.core.domain.maintain.MaintainRegion;
import com.inspect.base.core.enums.StaEnum;
import com.inspect.base.core.enums.TaskStatus;
import com.inspect.base.core.enums.TaskType;
import com.inspect.base.core.exception.ServiceException;
import com.inspect.base.core.sftp.SftpClient;
import com.inspect.base.core.sftp.SftpUploadEntity;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.base.core.utils.SFTPUtil;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.bean.BeanUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.utils.xml.GenXmlByBean;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.base.redis.service.RedisService;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.fegin.FeignMinioService;
import com.inspect.fegin.MultipartFileUtils;
import com.inspect.fegin.UploadResponse;
import com.inspect.infrared.InfraredImageParser;
import com.inspect.infrared.InfraredRequestParam;
import com.inspect.infrared.InfraredResponse;
import com.inspect.maintain.domain.MaintainAreaXML;
import com.inspect.maintain.domain.PatrolMaintainModuleXml;
import com.inspect.maintain.service.IMaintainRegionService;
import com.inspect.message.MessageUtils;
import com.inspect.partrolresult.client.BaseDataClient;
import com.inspect.partrolresult.client.WebsocketService;
import com.inspect.partrolresult.domain.*;
import com.inspect.partrolresult.mapper.DeviceStateMapper;
import com.inspect.partrolresult.mapper.PatrolResultMapper;
import com.inspect.partrolresult.service.IAnalyseRequestService;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.partrolresultAux.domain.PatrolResultAux;
import com.inspect.partrolresultAux.service.IPatrolResultAuxService;
import com.inspect.resultmain.domain.PatrolTaskResultMain;
import com.inspect.resultmain.service.IPatrolTaskResultMainService;
import com.inspect.statistics.ResultStatistics;
import com.inspect.system.base.openDomain.BasedataEqpBookMoMain;
import com.inspect.system.base.openDomain.BasedataEqpBookXml;
import com.inspect.system.base.openDomain.PatrolDeviceXml;
import com.inspect.task.domain.PatrolTask;
import com.inspect.task.domain.PatrolTaskModuleXml;
import com.inspect.task.domain.PatrolTaskXML;
import com.inspect.task.service.IPatrolTaskService;
import com.inspect.taskftp.domain.PatrolTaskFtp;
import com.inspect.taskftp.service.IPatrolTaskFtpService;
import com.inspect.taskstatus.domain.PatrolTaskStatus;
import com.inspect.taskstatus.service.IPatrolTaskStatusService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping({"/partrolresult"})
public class PatrolResultController extends BaseController {
    private static final ExecutorService executor = Executors.newFixedThreadPool(100);
    @Resource
    DeviceStateMapper deviceStateMapper;
    @Resource
    ResultStatistics resultStatistics;
    @Value("${sftp.ip}")
    private String ip;
    @Value("${sftp.port}")
    private String port;
    @Value("${sftp.username}")
    private String username;
    @Value("${sftp.password}")
    private String password;
    @Value("${INTRANET_FTP_VIEW_ADDRESS}")
    private String intranetFtpAddress;
    @Resource
    private IPatrolResultService patrolResultService;
    @Resource
    private IPatrolResultAuxService iPatrolResultAuxService;
    @Resource
    private WebsocketService websocketService;
    @Resource
    private IPatrolTaskService patrolTaskService;
    @Resource
    private IPatrolTaskStatusService patrolTaskStatusService;
    @Resource
    private IPatrolTaskStatusService iPatrolTaskStatusService;
    @Resource
    private IResultAnalysisService resultAnalysisService;
    @Resource
    private IPatrolTaskResultMainService iPatrolTaskResultMainService;
    @Resource
    private IPatrolTaskFtpService patrolTaskFtpService;
    @Resource
    private InfraredImageParser infraredImageParser;
    @Resource
    private RedisService redisService;
    @Resource
    private SftpClient sftpClient;
    @Resource
    private IPatrolTaskResultMainService patrolTaskResultMainService;
    @Resource
    private IMaintainRegionService maintainRegionService;
    @Resource
    private BaseDataClient baseDataClient;
    @Resource
    private PatrolResultMapper patrolResultMapper;

    @Resource
    private IAnalyseRequestService analyseRequestService;

    @Resource
    private MessageUtils messageUtils;

    @Resource
    private FeignMinioService feignMinioService;

    @GetMapping({"/list"})
    public TableDataInfo list(PatrolResult patrolResult) {
        String mainId = patrolResult.getMainId();
        List<PatrolResult> list = new ArrayList<>();
        if (StringUtils.isNotBlank(mainId)) {
            List<Long> lineIds = patrolTaskResultMainService.selectLineIds(Long.parseLong(mainId));
            startPage();
            if (lineIds != null && lineIds.size() > 0) {
                patrolResult.setMainIds(lineIds);
                logger.info("----------------------list query params1: " + JSONObject.toJSONString(patrolResult));
                list = patrolResultService.selectPatroByAllDevByMainIds(patrolResult);
                logger.info("----------------------list query return size1: " + list.size());
            } else {
                logger.info("----------------------list query params2: " + JSONObject.toJSONString(patrolResult));
                list = patrolResultService.selectPatroByAllDev(patrolResult);
                logger.info("----------------------list query return size2 : " + list.size());
            }
            for (PatrolResult result : list) {
                PatrolResultAux pra = new PatrolResultAux();
                pra.setResultId(result.getLineId() + "");
                List<PatrolResultAux> pra1 = iPatrolResultAuxService.selectPatrolResultAuxList(pra);
                if (!pra1.isEmpty()) {
                    result.setValue(pra1.get(0).getValue());
                }

                if ("0".equals(result.getValue())) {
                    result.setValue(messageUtils.get("正常"));
                }

                if ("-1".equals(result.getValue()) || "1".equals(result.getValue())) {
                    result.setValue(messageUtils.get("异常"));
                }
            }

        }

        return getDataTable(list);
    }

    @GetMapping({"/pointResult"})
    public AjaxResult pointResult(String deviceId, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime, @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        if (StringUtils.isBlank(deviceId)) {
            throw new ServiceException("点位编码不能为空");
        } else if (null == startTime) {
            throw new ServiceException("开始时间不能为空");
        } else if (null == endTime) {
            throw new ServiceException("结束时间不能为空");
        } else {
            List<PatrolResult> list = patrolResultMapper.queryPatrolResultByPointID(deviceId, startTime, endTime);
            return AjaxResult.success(list);
        }
    }

    @Log(
            title = "巡视结果",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, PatrolResult patrolResult) {
        List<PatrolResult> list = patrolResultService.selectPatrolResultList(patrolResult);
        ExcelUtil<PatrolResult> util = new ExcelUtil<>(PatrolResult.class);
        util.exportExcel(response, list, "巡视结果数据");
    }

    @GetMapping({"/{lineId}"})
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId) {
        PatrolResult arr = patrolResultService.selectPatrolResultByLineId(lineId);
        return AjaxResult.success(arr);
    }

    @Log(
            title = "巡视结果",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody PatrolResult patrolResult) {
        return toAjax(patrolResultService.insertPatrolResult(patrolResult));
    }

    @Log(
            title = "巡视结果",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody PatrolResult patrolResult) {
        PatrolResult result = patrolResultService.selectPatrolResultByLineId(patrolResult.getLineId());
        if (!result.getValue().equals(patrolResult.getValue())) {
            PatrolResultAux patrolResultAux = new PatrolResultAux();
            BeanUtils.copyBeanProp(patrolResultAux, result);
            patrolResultAux.setResultId(result.getLineId() + "");
            patrolResultAux.setCreateTime(new Date());
            patrolResultAux.setValue(patrolResult.getValue());
            patrolResultAux.setLineId(null);
            iPatrolResultAuxService.insertPatrolResultAux(patrolResultAux);
        }

        return toAjax(1);
    }

    @Log(
            title = "巡视结果",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{lineIds}"})
    public AjaxResult remove(@PathVariable Long[] lineIds) {
        return toAjax(patrolResultService.deletePatrolResultByLineIds(lineIds));
    }

    @GetMapping({"/detail"})
    public Map<String, Object> detail(PatrolResult patrolResult) {
        Map<String, Object> map = new HashMap<>();
        List<PatrolResult> list = patrolResultService.selectPatrolResultList(patrolResult);
        if (!list.isEmpty()) {
            PatrolTaskResultMain patrolTaskResultMain = new PatrolTaskResultMain();
            if (list.get(0).getMainId() != null) {
                patrolTaskResultMain = patrolTaskResultMainService.selectPatrolTaskResultMainByLineId(Long.valueOf(list.get(0).getMainId()));
            }

            List<String> infraRedArray = new ArrayList<>();
            List<String> visibleArray = new ArrayList<>();
            List<String> audioArray = new ArrayList<>();
            List<String> videoArray = new ArrayList<>();
            List<String> photoArray = new ArrayList<>();
            PatrolResult patrolResultEx = list.get(0);
            if (patrolResultEx.getFileType() != null && patrolResultEx.getFilePath() != null) {
                String[] type = patrolResultEx.getFileType().split(StringUtils.COMMA);
                String[] filepath = patrolResultEx.getFilePath().split(StringUtils.COMMA);
                for (int i = 0; i < type.length; ++i) {
                    switch (type[i]) {
                        case "1":
                            infraRedArray.add(filepath[i]);
                            break;
                        case "2":
                            visibleArray.add(filepath[i]);
                            break;
                        case "3":
                            audioArray.add(filepath[i]);
                            break;
                        case "4":
                            videoArray.add(filepath[i]);
                            break;
                        case "5":
                            photoArray.add(filepath[i]);
                            break;
                    }
                }
            }

            patrolResultEx.setInfraRed(infraRedArray);
            patrolResultEx.setVisible(visibleArray);
            patrolResultEx.setAudio(audioArray);
            patrolResultEx.setVideo(videoArray);
            patrolResultEx.setPhoto(photoArray);
            if (StringUtils.isNotEmpty(patrolTaskResultMain.getTaskResult())) {
                patrolResultEx.setCheckResult(patrolTaskResultMain.getTaskResult());
            }

            if (StringUtils.isNotEmpty(patrolTaskResultMain.getCheckPerson())) {
                patrolResultEx.setCheckPerson(patrolTaskResultMain.getCheckPerson());
            }

            if (patrolTaskResultMain.getCheckTime() != null) {
                patrolResultEx.setCheckTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTaskResultMain.getCheckTime()));
            }

            map.put("original", patrolResultEx);
            Iterator<PatrolResult> iterator = list.iterator();
            while (!iterator.hasNext()) {
                List<PatrolResultAux> resultAuxList;
                PatrolResult brr = iterator.next();
                PatrolResultAux patrolResultAuxQuery = new PatrolResultAux();
                patrolResultAuxQuery.setResultId(brr.getLineId() + "");
                resultAuxList = iPatrolResultAuxService.selectPatrolResultAuxList(patrolResultAuxQuery);
                if (resultAuxList.isEmpty()) {
                    continue;
                }

                List<String> infraReda = new ArrayList<>();
                List<String> visibleList = new ArrayList<>();
                List<String> audioList = new ArrayList<>();
                List<String> videoList = new ArrayList<>();
                List<String> photoList = new ArrayList<>();
                PatrolResultAux patrolResultAux = resultAuxList.get(0);
                if (patrolResultAux.getFileType() != null && patrolResultAux.getFilePath() != null) {
                    String[] type = patrolResultAux.getFileType().split(StringUtils.COMMA);
                    String[] filepath = patrolResultAux.getFilePath().split(StringUtils.COMMA);
                    for (int i = 0; i < type.length; ++i) {
                        switch (type[i]) {
                            case "1":
                                infraReda.add(filepath[i]);
                                break;
                            case "2":
                                visibleList.add(filepath[i]);
                                break;
                            case "3":
                                audioList.add(filepath[i]);
                                break;
                            case "4":
                                videoList.add(filepath[i]);
                                break;
                            case "5":
                                photoList.add(filepath[i]);
                                break;
                        }
                    }
                }

                patrolResultAux.setInfraRed(infraReda);
                patrolResultAux.setVisible(visibleList);
                patrolResultAux.setAudio(audioList);
                patrolResultAux.setVideo(videoList);
                patrolResultAux.setPhoto(photoList);
                map.put("now", patrolResultAux);
            }
        }

        map.put("code", 200);
        map.put("msg", "操作成功");
        return map;
    }

    @GetMapping({"/test"})
    public AjaxResult test(String id) {
        PatrolResult patrolResult = new PatrolResult();
        patrolResult.setMainId(id);
        List<PatrolResult> list = patrolResultService.selectPatrolResultList(patrolResult);
        callLocalAlgorithm(list);
        return AjaxResult.success();
    }

    public String callLocalAlgorithm(List<PatrolResult> patrolResultList) {
        logger.info("[ANALYSIS] TO CALL ALGORITHM SIZE: {}", patrolResultList.size());
        String result = "";
        PatrolTaskFtp patrolTaskFtp = patrolTaskFtpService.selectPatrolTaskFtpByLineId(2L);
        String uuid = UUID.randomUUID().toString().trim().replaceAll(StringUtils.DASH, StringUtils.EMPTY);

        redisService.setCacheObject(RedisConst.REQUEST_UUID + uuid, patrolResultList.get(0).getTaskPatrolledId(), 1L, TimeUnit.DAYS);
        String ANALYSIS_URL = patrolTaskService.selectConfigByKey("ANALYSIS_URL");
        String BIG_ANALYSIS_URL = patrolTaskService.selectConfigByKey("BIG_ANALYSIS_URL");
        String MAJOR_URL = patrolTaskService.selectConfigByKey("MAJOR_URL");
        String TASK_PORT = patrolTaskService.selectConfigByKey("TASK_PORT");
        String ids = "";
        logger.info("");
        for (PatrolResult patrolResult : patrolResultList) {
            List<ObjectList> oblist = new ArrayList<>();
            List<ObjectList> bigOblist = new ArrayList<>();
            List<ObjectList> obToHww = new ArrayList<>();
            String image = patrolResult.getFilePath().replace(patrolTaskFtp.getFtpPath() + "/", StringUtils.EMPTY);
            String imageType = patrolResult.getFileType();
            ObjectList objectList = new ObjectList();
            objectList.setObjectId(patrolResult.getDeviceId());
            logger.info("[ANALYSIS] deviceId: {}", patrolResult.getDeviceId());
            Map<String, String> map = patrolResultService.selectAlgorithmType(patrolResult.getDeviceId());
            String[] strings = new String[1];
            List<String> algIds = new ArrayList<>();
            if (map != null) {
                String subIds = map.get("alg_subtype_ids");
                logger.info("[ANALYSIS] subIds: {}", subIds);
                if (subIds.contains(StringUtils.COMMA)) {
                    String[] subIdsList = subIds.split(StringUtils.COMMA);
                    for (String subId : subIdsList) {
                        if (StringUtils.isNotEmpty(subId)) {
                            algIds.add(subId);
                        }
                    }
                } else {
                    algIds.add(subIds);
                }
            }

            PatrolResult patrolResultTemp = new PatrolResult();
            if (!algIds.isEmpty()) {
                patrolResultTemp.setAlgId(algIds);
            }

            List<AlgInfo> algInfoList = new ArrayList<>();
            if (patrolResultTemp.getAlgId() != null && !patrolResultTemp.getAlgId().isEmpty()) {
                algInfoList = patrolResultService.selectAlgInfo(patrolResultTemp);
            }

            String algName;
            String filePanpath;
            if (!algInfoList.isEmpty()) {
                String algInfoName;
                String algSubtypeCode;
                if (algInfoList.size() == 1) {
                    algName = ((AlgInfo) ((List<?>) algInfoList).get(0)).getAlgName();
                    algSubtypeCode = ((AlgInfo) ((List<?>) algInfoList).get(0)).getAlgSubtypeCode();
                } else {
                    algName = ((AlgInfo) ((List<?>) algInfoList).get(algInfoList.size() - 1)).getAlgName();
                    algSubtypeCode = ((AlgInfo) ((List<?>) algInfoList).get(algInfoList.size() - 1)).getAlgSubtypeCode();
                }
                algInfoName = "meter"; //qinyl test
                logger.info("[ALG] patrolResult deviceId: {}, algInfoName: {}, image: {}, imageType: {}, algName: {}",
                        patrolResult.getDeviceId(),
                        algInfoName,
                        image,
                        imageType,
                        algName);
                if (algInfoName.equals("infrared")) {
                    Map<String, Object> device = resultAnalysisService.selectEqInfoByCode(patrolResult.getPatrolDeviceCode());
                    if (device != null && device.get("type") != null) {
                        String type = device.get("type") + "";
                        if ((type.equals("1") || type.equals("2") || type.equals("3")) && StringUtils.isNotEmpty(patrolResult.getValue())) {
                            ResultAnalysis resultAnalysis = new ResultAnalysis();
                            resultAnalysis.setBusinessId(patrolResult.getLineId() + "");
                            resultAnalysis.setResultContent("{\"requestId\": \"123\", \"resultList\": [{\"objectId\": \"" + patrolResult.getDeviceId() + "\", \"results\": [{\"type\": \"infrared\", \"value\": \"0\", \"code\": \"2000\", \"resImageUrl\": \"\", \"pos\": [], \"conf\": 0.8, \"desc\": \"\"}]}]}");
                            if (StringUtils.isNotEmpty(patrolResult.getDeviceId())) {
                                resultAnalysis.setObjectId(patrolResult.getDeviceId());
                            }

                            resultAnalysis.setDescription("");
                            resultAnalysis.setCreateTime(new Date());
                            resultAnalysis.setResStatus("1");
                            resultAnalysis.setPointStatus("1");
                            resultAnalysis.setResultType("1");
                            resultAnalysisService.insertResultAnalysis(resultAnalysis);
                            continue;
                        }
                    }

                    String[] images = new String[1];
                    if (image.contains(StringUtils.COMMA)) {
                        images[0] = image.split(StringUtils.COMMA)[0];
                    } else {
                        images[0] = image;
                    }

                    ids = patrolResult.getLineId() + "";
                    objectList.setImageUrlList(images);
                    objectList.setTypeList(strings);
                    obToHww.add(objectList);
                } else {
                    List<String> imagelist = new ArrayList<>();
                    List<String> typelist = new ArrayList<>();
                    String[] imageTypes;
                    if (image.contains(StringUtils.COMMA)) {
                        imageTypes = imageType.split(StringUtils.COMMA);
                        String[] imageList = image.split(StringUtils.COMMA);
                        for (int i = 0; i < imageTypes.length; ++i) {
                            if (imageTypes[i].equals("2") || imageTypes[i].equals("4")) {
                                typelist.add(imageTypes[i]);
                                imagelist.add(imageList[i]);
                            }
                        }
                    }

                    if (!imagelist.isEmpty()) {
                        image = String.join(StringUtils.COMMA, imagelist);
                        imageType = String.join(StringUtils.COMMA, typelist);
                    }

                    if (algName.contains("判别")) {
                        objectList.setTypeList(algSubtypeCode.split(StringUtils.COMMA));
                        filePanpath = "";
                        Map<String, String> pointInfoMap = resultAnalysisService.selectPointInfoById(patrolResult.getDeviceId());
                        if (pointInfoMap != null && StringUtils.isNotEmpty(pointInfoMap.get("dis_ref_picture_path"))) {
                            filePanpath = pointInfoMap.get("dis_ref_picture_path");
                        }

                        objectList.setImageNormalUrlPath(filePanpath);
                        if (image.contains(StringUtils.COMMA)) {
                            imageTypes = image.split(StringUtils.COMMA);
                            objectList.setImageUrlList(imageTypes);
                        } else {
                            imageTypes = new String[]{image};
                            objectList.setImageUrlList(imageTypes);
                        }

                        bigOblist.add(objectList);
                    } else {
                        if (!algName.equals("缺陷识别")) {
                            objectList.setTypeList(algSubtypeCode.split(StringUtils.COMMA));
                        } else {
                            List<String> judging = new ArrayList<>();
                            for (AlgInfo algInfo : algInfoList) {
                                if (algInfo.getAlgName().equals("缺陷识别") && StringUtils.isNotEmpty(algInfo.getAlgSubtypeCode())) {
                                    judging.add(algInfo.getAlgSubtypeCode());
                                }
                            }

                            if (!judging.isEmpty()) {
                                objectList.setTypeList(String.join(StringUtils.COMMA, judging).split(StringUtils.COMMA));
                            }
                        }

                        imageTypes = new String[1];
                        if (image.contains(StringUtils.COMMA)) {
                            imageTypes[0] = image.split(StringUtils.COMMA)[0];
                        } else {
                            imageTypes[0] = image;
                        }

                        objectList.setImageUrlList(imageTypes);
                        if (algInfoName.equals("meter")) {
                            oblist.add(objectList);
                        } else {
                            bigOblist.add(objectList);
                        }
                    }
                }
            } else {
                logger.info("[ANALYSIS] algInfoList.isEmpty with device: {}", patrolResult.getDeviceId());
            }

            SendData sendData;
            if (!obToHww.isEmpty()) {
                sendData = new SendData();
                sendData.setObjectList(obToHww);
                sendData.setRequestHostIp(MAJOR_URL);
                sendData.setRequestHostPort(TASK_PORT);
                sendData.setRequestId(uuid);
                algName = JSONObject.toJSONString(sendData);
                logger.info(algName);

                try {
                    InfraredRequestParam infraredRequestParam = JSONObject.parseObject(algName, InfraredRequestParam.class);
                    InfraredResponse infraredResponse = infraredImageParser.parse(infraredRequestParam);
                    if (infraredResponse != null) {
                        ResultAnalysis resultAnalysis = new ResultAnalysis();
                        if (infraredResponse.getResultList() != null && !infraredResponse.getResultList().isEmpty()) {
                            if (infraredResponse.getResultList().get(0).getResults() != null && !infraredResponse.getResultList().get(0).getResults().isEmpty()) {
                                if (StringUtils.isNotEmpty(infraredResponse.getResultList().get(0).getResults().get(0).getValue()) && infraredResponse.getResultList().get(0).getResults().get(0).getValue().equals("1")) {
                                    resultAnalysis.setBusinessId(ids);
                                    filePanpath = JSONObject.toJSONString(infraredResponse);
                                    resultAnalysis.setResultContent(filePanpath);
                                    if (StringUtils.isNotEmpty(infraredResponse.getResultList().get(0).getObjectId())) {
                                        resultAnalysis.setObjectId(infraredResponse.getResultList().get(0).getObjectId());
                                    }

                                    resultAnalysis.setDescription(infraredResponse.getResultList().get(0).getResults().get(0).getDesc());
                                    resultAnalysis.setCreateTime(new Date());
                                    resultAnalysis.setResStatus("0");
                                    resultAnalysis.setPointStatus("0");
                                    resultAnalysis.setResultType("0");
                                    resultAnalysisService.insertResultAnalysis(resultAnalysis);
                                    JSONObject websocketParam = new JSONObject();
                                    websocketParam.put("event", "task_statistics_notify");
                                    websocketParam.put("data", (new JSONObject()).fluentPut("taskName", "红外任务").fluentPut("msg", "高温告警"));
                                    websocketService.parseMessage(websocketParam.toString());
                                } else {
                                    resultAnalysis.setBusinessId(ids);
                                    filePanpath = JSONObject.toJSONString(infraredResponse);
                                    resultAnalysis.setResultContent(filePanpath);
                                    resultAnalysis.setResultType("1");
                                    if (StringUtils.isNotEmpty(infraredResponse.getResultList().get(0).getObjectId())) {
                                        resultAnalysis.setObjectId(infraredResponse.getResultList().get(0).getObjectId());
                                    }

                                    resultAnalysis.setDescription(infraredResponse.getResultList().get(0).getResults().get(0).getDesc());
                                    resultAnalysis.setCreateTime(new Date());
                                    resultAnalysis.setResStatus("1");
                                    resultAnalysis.setPointStatus("1");
                                    resultAnalysis.setResultType("1");
                                    resultAnalysisService.insertResultAnalysis(resultAnalysis);
                                }
                            }

                            double maxT = infraredResponse.getResultList().get(0).getResults().get(0).getInfraredT().getMaxT();
                            PatrolResult patrolResultAsd = patrolResultService.selectPatrolResultByLineId(Long.valueOf(ids));
                            patrolResultAsd.setValue(maxT + "");
                            patrolResultAsd.setRecognitionType("4");
                            patrolResultService.updatePatrolResult(patrolResultAsd);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (!oblist.isEmpty()) {
                sendData = new SendData();
                sendData.setObjectList(oblist);
                sendData.setRequestHostIp(MAJOR_URL);
                sendData.setRequestHostPort(TASK_PORT);
                sendData.setRequestId(uuid);
                sendData.setSftpHostIp(ip);
                sendData.setSftpHostPort(port);
                sendData.setSftpUsername(username);
                sendData.setSftpPassword(password);
                algName = JSONObject.toJSONString(sendData);
                logger.info("[RES] algName++++++++++++++++++++++++++ algName: {}, imageUrlList: {}", algName, oblist.get(0).getImageUrlList());
                if (oblist.get(0).getImageUrlList() != null && oblist.get(0).getImageUrlList().length > 0) {
                    try {
                        remoteAnalysisServiceStart(ANALYSIS_URL, algName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                logger.info("[RES] Not calling intelligent analysis platform!!!!!!!!!!!!! deviceId: {}", patrolResult.getDeviceId());
            }

            if (!bigOblist.isEmpty()) {
                sendData = new SendData();
                sendData.setObjectList(bigOblist);
                sendData.setRequestHostIp(MAJOR_URL);
                sendData.setRequestHostPort(TASK_PORT);
                sendData.setRequestId(uuid);
                sendData.setSftpHostIp(ip);
                sendData.setSftpHostPort(port);
                sendData.setSftpUsername(username);
                sendData.setSftpPassword(password);
                algName = JSONObject.toJSONString(sendData);
                if (bigOblist.get(0).getImageUrlList() != null && bigOblist.get(0).getImageUrlList().length > 0) {
                    try {
                        remoteAnalysisServiceStart(BIG_ANALYSIS_URL, algName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return result;

    }

    private void remoteAnalysisServiceStart(final String ANALYSIS_URL, final String params) {
        logger.info("[ALG] CALL ALG BIG MODEL, URL: {}, PARAM: {}", ANALYSIS_URL, params);
        executor.submit(() -> {
            try {
                String result = HttpClientUtils.sendPostAgain(ANALYSIS_URL + "/picAnalyse", params);
                logger.info("[RES] SMART ANALYSIS RESULT: {}", result);
            } catch (Exception e) {
                logger.error("error", e);
            }
        });
    }

    public String callRemoteAlgorithm(final int totalNumber, List<PatrolResult> patrolResultList) {
        String result = "";
        PatrolTaskFtp ftp = patrolTaskFtpService.selectPatrolTaskFtpByLineId(2L);
        String ANALYSIS_URL = patrolTaskService.selectConfigByKey("ANALYSIS_URL");// 小模型分析路径
        String BIG_ANALYSIS_URL = patrolTaskService.selectConfigByKey("BIG_ANALYSIS_URL"); // 初筛分析路径
        String MAJOR_URL = patrolTaskService.selectConfigByKey("MAJOR_URL");//requestHostIp 分析结果反馈ip地址 巡视主机路径
        String TASK_PORT = patrolTaskService.selectConfigByKey("TASK_PORT");//requestHostPort 分析结果反馈端口  巡视主机任务端口

        logger.info("callRemoteAlgorithm ftpInfo: {}, ANALYSIS_URL: {}, BIG_ANALYSIS_URL: {}, MAJOR_URL: {}, TASK_PORT: {}",
                ftp, ANALYSIS_URL, BIG_ANALYSIS_URL, MAJOR_URL, TASK_PORT);

        String ids = "";
        for (PatrolResult patrolResult : patrolResultList) {
            PatrolTask task = patrolTaskService.selectPatrolTaskByTaskId(Long.valueOf(patrolResult.getTaskCode()));
            logger.info("callRemoteAlgorithm taskPatrolledId: {}, patrolResult: {}", patrolResult.getTaskPatrolledId(), patrolResult);
            List<AnalyseReqItem> filterList = new ArrayList<>(); //初筛
            List<AnalyseReqItem> bigModelList = new ArrayList<>(); //大模型
            List<AnalyseReqItem> infraredList = new ArrayList<>();//古老的红外逻辑； 最新的红外逻辑另辟蹊径增加新的算法类型并且归入初筛逻辑-20250423
            String image = patrolResult.getFilePath().replace(ftp.getFtpPath() + "/", StringUtils.EMPTY);
            String imageType = patrolResult.getFileType();
            AnalyseReqItem analyseReqItem = new AnalyseReqItem();
            analyseReqItem.setObjectId(patrolResult.getDeviceId());

            List<AlgInfo> algInfoList;
            if (StringUtils.isNotEmpty(task.getSpecifiedAlg())) {
                // 任务指定算法类型：获取指定算法类型的对象
                algInfoList = patrolResultService.selectAlgInfoByCode(task.getSpecifiedAlg());
            } else {
                // 根据basedata_patrolpoint中的patrol_point_id(对应patrol_result表中的device_id)查询该预置位配置的算法列表
                algInfoList = patrolResultService.selectPointAlgInfo(patrolResult.getDeviceId());
            }
            logger.info("callRemoteAlgorithm algInfoList: {}", algInfoList);

            analyseReqItem.setImageUrlList(image.split(StringUtils.COMMA));
            String pictureFrame = patrolTaskService.selectConfigByKey("PICTURE_FRAME");
            logger.info("callRemoteAlgorithm pictureFrame: {}", pictureFrame);

            String[] strings = new String[1];
            String type;
            if (!algInfoList.isEmpty()) {
                // 最古老处理红外请求，暂且保留
                List<AlgInfo> infraredAlgInfoList = algInfoList.stream().filter((item) -> "infrared".equals(item.getAlgSubtypeCode())).collect(Collectors.toList());
                if (!infraredAlgInfoList.isEmpty() && "true".equals(pictureFrame)) {
                    logger.info("callRemoteAlgorithm infraredList: {}, patrolDeviceCode: {}", infraredAlgInfoList, patrolResult.getPatrolDeviceCode());
                    Map<String, Object> device = resultAnalysisService.selectEqInfoByCode(patrolResult.getPatrolDeviceCode());
                    if (device != null && device.get("type") != null) {
                        type = device.get("type") + "";
                        if (("1".equals(type) || "2".equals(type) || "3".equals(type)) && StringUtils.isNotEmpty(patrolResult.getValue())) {
                            logger.info("callRemoteAlgorithm type: {}, value: {}", type, patrolResult.getValue());
                            // 改变之前的处理流程，"infrared"继续调用算法
//                            ResultAnalysis resultAnalysis = ResultAnalysis.createInfrared(String.valueOf(patrolResult.getLineId()), patrolResult.getDeviceId());
//                            resultAnalysisService.insertResultAnalysis(resultAnalysis);
//                            continue;
                        }
                    }

                    String[] imageUrlArr = new String[1];
                    if (image.contains(StringUtils.COMMA) && image.split(StringUtils.COMMA).length > 1) {
                        // 之前默认取的第一张图片，钱塘江站云深处机器狗红外会传两张，第二张才会带值，所以现在改为取第二张图片
                        imageUrlArr[0] = image.split(StringUtils.COMMA)[1];
                    } else {
                        imageUrlArr[0] = image;
                    }

                    ids = patrolResult.getLineId() + "";
                    analyseReqItem.setImageUrlList(imageUrlArr);
                    analyseReqItem.setTypeList(strings);
                    //改为走初筛-20250827-qinyl
                    //infraredList.add(analyseReqItem.clone());


                    analyseReqItem.setTypeList(infraredAlgInfoList.stream().map(AlgInfo::getAlgSubtypeCode).toArray(String[]::new));
                    filterList.add(analyseReqItem.clone());
                }

                algInfoList.removeAll(infraredAlgInfoList);
                List<String> imagelist = new ArrayList<>();
                if (image.contains(StringUtils.COMMA)) {
                    String[] imageTypeArr = imageType.split(StringUtils.COMMA);
                    String[] imageArr = image.split(StringUtils.COMMA);
                    for (int i = 0; i < imageTypeArr.length; ++i) {
                        if ("2".equals(imageTypeArr[i]) || "4".equals(imageTypeArr[i])) {
                            imagelist.add(imageArr[i]);
                        }
                    }
                }

                if (!imagelist.isEmpty()) {
                    image = String.join(StringUtils.COMMA, imagelist);
                }

                Map<String, String> judgeMap = resultAnalysisService.selectPointInfoById(patrolResult.getDeviceId());
                logger.info("callRemoteAlgorithm judgeMap: {}", judgeMap.toString());//basedata_patrolpoint field->value map
                String filePanpath = "";
                if (StringUtils.isNotEmpty(judgeMap.get("dis_ref_picture_path"))) {//basedata_patrolpoint里该字段的意思是判别基准图片路径
                    filePanpath = judgeMap.get("dis_ref_picture_path");
                }

                analyseReqItem.setImageNormalUrlPath(filePanpath);//总是为空
                List<AlgInfo> judgeList = algInfoList.stream().filter(
                        (item) -> item.getAlgName().contains("判别")
                ).collect(Collectors.toList());

                // 将AlgName含有判别的点位加入大模型bigModelList列表
                if (!judgeList.isEmpty()) {
                    analyseReqItem.setTypeList(judgeList.stream().map(AlgInfo::getAlgSubtypeCode).toArray(String[]::new));
                    String[] images;
                    if (image.contains(StringUtils.COMMA)) {
                        images = image.split(StringUtils.COMMA);
                        analyseReqItem.setImageUrlList(images);
                    } else {
                        images = new String[]{image};
                        analyseReqItem.setImageUrlList(images);
                    }

                    bigModelList.add(analyseReqItem.clone());
                }

                //将已经加入bigModelList中的记录删除(算法名称为缺陷判别)
                algInfoList.removeAll(judgeList);

                // 将AlgSubtypeCode为以下几种类型的点位加入初筛filterList列表
                List<AlgInfo> meterList =
                        (algInfoList).stream().filter((item) ->
                                AlgConstants.METER.equals(item.getAlgSubtypeCode())
                                        || AlgConstants.XB.equals(item.getAlgSubtypeCode())
                                        || AlgConstants.INFRA_1800.equals(item.getAlgSubtypeCode())
                                        || AlgConstants.INFRA_YU3.equals(item.getAlgSubtypeCode())
                                        || AlgConstants.INFRA_CAMERA.equals(item.getAlgSubtypeCode())
                                        || AlgConstants.INFRA_CAMERA_REVERSE.equals(item.getAlgSubtypeCode())
                        ).collect(Collectors.toList());
                if (!meterList.isEmpty()) {
                    analyseReqItem.setTypeList(meterList.stream().map(AlgInfo::getAlgSubtypeCode).toArray(String[]::new));
                    filterList.add(analyseReqItem.clone());
                }

                //将已经加入filterList中的记录删除(算法编码为meter的记录)
                algInfoList.removeAll(meterList);
                List<AlgInfo> defectList = algInfoList.stream().filter((item) -> "缺陷识别".equals(item.getAlgName())).collect(Collectors.toList());
                if (!defectList.isEmpty()) {
                    analyseReqItem.setTypeList(defectList.stream().map(AlgInfo::getAlgSubtypeCode).toArray(String[]::new));
                    bigModelList.add(analyseReqItem.clone());
                }

                algInfoList.removeAll(defectList);
                if (!algInfoList.isEmpty()) {
                    analyseReqItem.setTypeList(algInfoList.stream().map(AlgInfo::getAlgSubtypeCode).toArray(String[]::new));
                    bigModelList.add(analyseReqItem.clone());
                }

                // 古老的红外逻辑处理
                logger.info("callRemoteAlgorithm infraredList taskPatrolId: {}, isEmpty: {}", patrolResult.getTaskPatrolledId(), infraredList.isEmpty());//永远为true
                if (!infraredList.isEmpty() && "true".equals(pictureFrame)) {
                    String uuid = UUID.randomUUID().toString().trim().replaceAll(StringUtils.DASH, StringUtils.EMPTY);
                    redisService.setCacheObject(RedisConst.REQUEST_UUID + uuid, patrolResultList.get(0).getTaskPatrolledId(), 1L, TimeUnit.DAYS);
                    AnalyseRequest sendData = new AnalyseRequest();
                    sendData.setObjectList(infraredList);
                    sendData.setRequestHostIp(MAJOR_URL);
                    sendData.setRequestHostPort(TASK_PORT);
                    sendData.setRequestId(uuid);
                    type = JSONObject.toJSONString(sendData);

                    try {
                        logger.info("callRemoteAlgorithm infraredRequest: {}", type);
                        InfraredRequestParam infraredRequestParam = JSONObject.parseObject(type, InfraredRequestParam.class);
                        InfraredResponse infraredResponse = infraredImageParser.parse(infraredRequestParam);
                        logger.info("callRemoteAlgorithm infraredResponse: {}", infraredResponse);
                        if (infraredResponse != null) {
                            ResultAnalysis resultAnalysis = new ResultAnalysis();
                            if (infraredResponse.getResultList() != null && !infraredResponse.getResultList().isEmpty()) {
                                if (infraredResponse.getResultList().get(0).getResults() != null && !infraredResponse.getResultList().get(0).getResults().isEmpty()) {
                                    String ww;
                                    if (StringUtils.isNotEmpty(infraredResponse.getResultList().get(0).getResults().get(0).getValue()) && infraredResponse.getResultList().get(0).getResults().get(0).getValue().equals("1")) {
                                        resultAnalysis.setBusinessId(ids);
                                        ww = JSONObject.toJSONString(infraredResponse);
                                        resultAnalysis.setResultContent(ww);
                                        if (StringUtils.isNotEmpty(infraredResponse.getResultList().get(0).getObjectId())) {
                                            resultAnalysis.setObjectId(infraredResponse.getResultList().get(0).getObjectId());
                                        }

                                        resultAnalysis.setDescription(infraredResponse.getResultList().get(0).getResults().get(0).getDesc());
                                        resultAnalysis.setCreateTime(new Date());
                                        resultAnalysis.setResStatus("0");
                                        resultAnalysis.setPointStatus("0");
                                        resultAnalysis.setResultType("0");
                                        resultAnalysisService.insertResultAnalysis(resultAnalysis);
                                        JSONObject websocketParam = new JSONObject();
                                        websocketParam.put("event", "task_statistics_notify");
                                        websocketParam.put("data", (new JSONObject()).fluentPut("taskName", "红外任务").fluentPut("msg", "高温告警"));
                                        //websocketService.parseMessage(websocketParam.toString());
                                    } else {
                                        resultAnalysis.setBusinessId(ids);
                                        ww = JSONObject.toJSONString(infraredResponse);
                                        resultAnalysis.setResultContent(ww);
                                        resultAnalysis.setResultType("1");
                                        if (StringUtils.isNotEmpty(infraredResponse.getResultList().get(0).getObjectId())) {
                                            resultAnalysis.setObjectId(infraredResponse.getResultList().get(0).getObjectId());
                                        }

                                        resultAnalysis.setDescription(infraredResponse.getResultList().get(0).getResults().get(0).getDesc());
                                        resultAnalysis.setCreateTime(new Date());
                                        resultAnalysis.setResStatus("1");
                                        resultAnalysis.setPointStatus("1");
                                        resultAnalysis.setResultType("1");
                                        resultAnalysisService.insertResultAnalysis(resultAnalysis);
                                    }
                                }

                                double maxT = infraredResponse.getResultList().get(0).getResults().get(0).getInfraredT().getMaxT();
                                PatrolResult patrolResultAsd = patrolResultService.selectPatrolResultByLineId(Long.valueOf(ids));
                                patrolResultAsd.setValue(maxT + "");
                                patrolResultAsd.setRecognitionType("4");
                                patrolResultService.updatePatrolResult(patrolResultAsd);
                            }
                        }
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                }

                logger.info(Color.CYAN + "callRemoteAlgorithm algInfoList2: {}" + Color.END, algInfoList);
                logger.info(Color.CYAN + "callRemoteAlgorithm filter size: {}, filterList: {}" + Color.END, filterList.size(), filterList);
                logger.info(Color.CYAN + "callRemoteAlgorithm bigModel size: {}, bigModelList: {}" + Color.END, bigModelList.size(), bigModelList);

                String drafter = task.getDrafter();
                //qinyl 初筛逻辑处理
                if (!filterList.isEmpty()) {
                    AnalyseRequest analyseReq = new AnalyseRequest();
                    analyseReq.setTaskPatrolId(patrolResultList.get(0).getTaskPatrolledId());
                    analyseReq.setObjectList(filterList);
                    analyseReq.setRequestHostIp(MAJOR_URL);
                    analyseReq.setRequestHostPort(TASK_PORT);
                    analyseReq.setSftpHostIp(ip);
                    analyseReq.setSftpHostPort(port);
                    analyseReq.setSftpUsername(username);
                    analyseReq.setSftpPassword(password);
                    analyseReq.setTotalNumber(totalNumber);
                    analyseReq.setDrafter(drafter);
                    if (filterList.get(0).getImageUrlList() != null && filterList.get(0).getImageUrlList().length > 0) {
                        // 初筛算法调用改为异步调用
                        final String meterFilter = patrolTaskService.selectConfigByKey(AnalyseConstants.ANALYSE_IS_METER_FILTER);
                        //analyseRemoteService.sendRequest(analyseReq, filterList.get(0).getTypeList(), "1".equals(meterFilter));
                        analyseReq.setAlgorithmType("filterAlgorithm");
                        analyseReq.setFilter("1".equals(meterFilter));
                        analyseReq.setValue(patrolResult.getValue());
                        analyseReq.setUnit(patrolResult.getUnit());
                        analyseReq.setValueUnit(patrolResult.getValueUnit());
                        analyseReq.setValueType(patrolResult.getValueType());
                        analyseReq.setTypeList(filterList.get(0).getTypeList());
                        analyseReq.setCoordinatePixel(patrolResult.getCoordinatePixel());
                        String requestDataToRedis = new Gson().toJson(analyseReq);
                        logger.info("callRemoteAlgorithm filterList requestDataToRedis: {}", requestDataToRedis);
                        redisService.redisTemplate.opsForList().rightPush(AnalyseConstants.ALGORITHM_REQUEST_QUEUE, requestDataToRedis);
                    }
                }

                //qinyl 大模型(目前也是走初篩)
                if (!bigModelList.isEmpty()) {
                    AnalyseRequest analyseReq = new AnalyseRequest();
                    analyseReq.setTaskPatrolId(patrolResultList.get(0).getTaskPatrolledId());
                    analyseReq.setObjectList(bigModelList);
                    analyseReq.setRequestHostIp(MAJOR_URL);
                    analyseReq.setRequestHostPort(TASK_PORT);
                    analyseReq.setSftpHostIp(ip);
                    analyseReq.setSftpHostPort(port);
                    analyseReq.setSftpUsername(username);
                    analyseReq.setSftpPassword(password);
                    analyseReq.setTotalNumber(totalNumber);
                    analyseReq.setDrafter(drafter);
                    if (bigModelList.get(0).getImageUrlList() != null && bigModelList.get(0).getImageUrlList().length > 0) {
                        // 大模型算法调用改为异步调用
                        //analyseRemoteService.sendRequest(analyseReq, bigModelList.get(0).getTypeList(), true);
                        analyseReq.setFilter(true);
                        analyseReq.setAlgorithmType("bigModelAlgorithm");
                        analyseReq.setTypeList(bigModelList.get(0).getTypeList());
                        analyseReq.setCoordinatePixel(patrolResult.getCoordinatePixel());
                        String requestDataToRedis = new Gson().toJson(analyseReq);
                        logger.info("callRemoteAlgorithm bigModelList requestDataToRedis: {}", requestDataToRedis);
                        redisService.redisTemplate.opsForList().rightPush(AnalyseConstants.ALGORITHM_REQUEST_QUEUE, requestDataToRedis);
                    }
                }
            }
        }

        return result;
    }

    public void sendWebsocket(PatrolTaskStatus patrolTaskStatus) {
        Map<String, Object> webSocketMap = new HashMap<>();
        webSocketMap.put("event", "devInfoTask");
        webSocketMap.put("data", patrolTaskStatus);
        JSONObject jsonObject = new JSONObject(webSocketMap);
        websocketService.parseMessage(jsonObject.toString());
    }

    @PostMapping({"/testInfo"})
    public AjaxResult testInfo(@RequestBody String msg) {
        return getInfo("61", msg);
    }

    public String toDevType(List<String> list) {
        String str = "";
        Set<String> setList = new HashSet<>();
        Iterator<String> iterator = list.iterator();
        while (true) {
            Map<String, Object> map;
            do {
                do {
                    String arr;
                    do {
                        if (!iterator.hasNext()) {
                            if (!setList.isEmpty()) {
                                str = String.join(StringUtils.COMMA, setList);
                            }

                            return str;
                        }

                        arr = iterator.next();
                    } while (!StringUtils.isNotEmpty(arr));
                    map = resultAnalysisService.selectEqInfoByCode(arr);
                } while (map == null);
            } while (map.get("type") == null);

            String type = String.valueOf(map.get("type"));
            if (type.equals("13")) {
                setList.add("0");
            } else if (!type.equals("1") && !type.equals("2") && !type.equals("3")) {
                if (type.equals("14")) {
                    setList.add("3");
                } else {
                    setList.add("2");
                }
            } else {
                setList.add("1");
            }
        }
    }

    public String sendCodeToDevType(String SendCode) {
        String str = "";
        Set<String> setlist = new HashSet<>();
        List<Map<String, Object>> map = resultAnalysisService.selectEqInfoBySendCode(SendCode);
        if (map != null && !map.isEmpty()) {
            Iterator iterator = map.iterator();

            label46:
            while (true) {
                while (true) {
                    Map arr;
                    do {
                        do {
                            if (!iterator.hasNext()) {
                                break label46;
                            }

                            arr = (Map) iterator.next();
                        } while (arr == null);
                    } while (arr.get("type") == null);

                    String type = arr.get("type") + "";
                    if (type.equals("13")) {
                        setlist.add("2");
                    } else if (!type.equals("1") && !type.equals("2") && !type.equals("3")) {
                        if (type.equals("14")) {
                            setlist.add("3");
                        } else {
                            setlist.add("0");
                        }
                    } else {
                        setlist.add("1");
                    }
                }
            }
        }

        if (!setlist.isEmpty()) {
            str = String.join(StringUtils.COMMA, setlist);
        }

        return str;
    }

    @PostMapping({"/sendMessage"})
    public AjaxResult getInfo(@RequestParam String type, @RequestBody String messageBody) {
        logger.info("[RESULT] type: {}, messageBody: {}", type, messageBody);
        PatrolTaskFtp patrolTaskFtp = patrolTaskFtpService.selectPatrolTaskFtpByLineId(2L);
        int i = 1;
        List<String> patrolDeviceCodeList = new ArrayList<>();
        //List listEqpBook;
        if (type.equals(StaEnum.RunState.getCode())) {
            logger.info(Color.CYAN + "###### RECEIVE DATA TO ANALYSIS [41] start ######" + Color.END);
            try {
                JSONObject parseObject = JSONObject.parseObject(messageBody);
                String sendCode = (String) parseObject.get("SendCode");

                Object jsonArray = parseObject.get("taskStateList");
                if (jsonArray == null) {
                    jsonArray = parseObject.get("Items");
                }

                final String jsonArrayStr = String.valueOf(jsonArray);
                List<PatrolTaskStatus> patrolTaskStatusListItems = JSONArray.parseArray(jsonArrayStr, PatrolTaskStatus.class);
                logger.info("GET_INFO_41 ROBOT_TASK_STATUS size: {}", patrolTaskStatusListItems.size());
                if (!patrolTaskStatusListItems.isEmpty()) {
                    for (PatrolTaskStatus patrolTaskStatusItem : patrolTaskStatusListItems) {
                        PatrolTask patrolTask = new PatrolTask();
                        patrolTask.setTaskCode(patrolTaskStatusItem.getTaskCode());
                        List<PatrolTask> patrolTaskListOfDb = patrolTaskService.selectPatrolTaskList(patrolTask);
                        if (StringUtils.isEmpty(patrolTaskStatusItem.getTaskCode()) || CollectionUtils.isEmpty(patrolTaskListOfDb)) {
                            logger.info("GET_INFO_41 ROBOT_TASK_STATUS CODE {} NO EXIST, SKIP IT!", patrolTaskStatusItem.getTaskCode());
                        } else {
                            try {
                                sendWebsocket(patrolTaskStatusItem);
                            } catch (Exception e) {
                                logger.error("error", e);
                            }
                            PatrolTask patrolTaskDb = patrolTaskListOfDb.get(0);
                            if (StringUtils.isNotEmpty(patrolTaskStatusItem.getTaskPatrolledId())) {

                                String str = "";
                                PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
                                patrolTaskStatus.setTaskPatrolledId(patrolTaskStatusItem.getTaskPatrolledId());
                                if (StringUtils.isNotEmpty(patrolTaskStatusItem.getPosType())) {
                                    patrolTaskStatus.setPosType(patrolTaskStatusItem.getPosType());
                                    str = patrolTaskStatusItem.getPosType();
                                } else if (StringUtils.isNotEmpty(sendCode)) {
                                    str = sendCodeToDevType(sendCode);
                                    patrolTaskStatus.setPosType(str);
                                    if ("1".equals(str) && "E100-001".equals(sendCode)) {
                                        //List<BasedataEqpBookChannel> listEqpBook = baseDataClient.queryEqpBookCode(sendCode);
                                        final String channelCode = baseDataClient.queryEqpBookCode(sendCode);
                                        patrolTaskStatusItem.setCode(channelCode);
                                    }
                                }
                                List<PatrolTaskStatus> patrolTaskStatusList = iPatrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
                                logger.info("GET_INFO_41 ROBOT_TASK_STATUS patrolTaskStatusList: {}", patrolTaskStatusList);
                                if (!patrolTaskStatusList.isEmpty()) {
                                    PatrolTaskStatus patrolTaskStatusOfDb = patrolTaskStatusList.get(0);
                                    // 除了db非完成或终止或暂停状态，当db状态与上报状态不一致时，更新db状态
                                    if (!Arrays.asList(TaskStatus.DONE.getCode(), TaskStatus.HALTED.getCode()).contains(patrolTaskStatusOfDb.getTaskState())
                                            && !Arrays.asList(TaskStatus.DONE.getCode(), patrolTaskStatusOfDb.getTaskState()).contains(patrolTaskStatusItem.getTaskState())
                                            && !sendCode.equals("摄像头")
                                    ) {
                                        logger.info("GET_INFO_41 UPDATE TASK_STATE old: {} TO new: {}", patrolTaskStatusOfDb.getTaskState(), patrolTaskStatusItem.getTaskState());
                                        patrolTaskStatusOfDb.setTaskState(patrolTaskStatusItem.getTaskState());
                                        iPatrolTaskStatusService.updateTaskProgress(patrolTaskStatusOfDb.getLineId(), patrolTaskStatusOfDb.getTaskProgress(), null, patrolTaskStatusOfDb.getTaskState());
                                    }
                                    double runProgress = 0.0;
                                    double dbProgress = 0.0;
                                    try {
                                        String runProgressStr = patrolTaskStatusItem.getTaskProgress().replaceAll("[^0-9.]", "");
                                        String taskProgressFromDb = patrolTaskStatusOfDb.getTaskProgress();
                                        logger.info("GET_INFO_41 ROBOT_TASK_STATUS taskProgress: {}", taskProgressFromDb);
                                        String dbProgressStr = taskProgressFromDb.replaceAll("[^0-9.]", "");
                                        runProgress = Double.parseDouble(runProgressStr);
                                        dbProgress = Double.parseDouble(dbProgressStr);
                                        logger.info("patrol_task_status calc number, taskPatrolledId: {}, runProgressStr: {}, dbProgressStr: {}, run_progress: {}, db_progress: {}, cal_progress: {}",
                                                patrolTaskStatusItem.getTaskPatrolledId(),
                                                runProgressStr,
                                                dbProgressStr,
                                                runProgress,
                                                dbProgress,
                                                patrolTaskStatusOfDb.getTaskEstimatedTime());
                                    } catch (Exception e) {
                                        logger.error("patrol_task_status error number, taskPatrolledId: {}, run_progress: {}, db_progress: {}, cal_progress: {}",
                                                patrolTaskStatusItem.getTaskPatrolledId(),
                                                patrolTaskStatusItem.getTaskProgress(),
                                                patrolTaskStatusOfDb.getTaskProgress(),
                                                patrolTaskStatusOfDb.getTaskEstimatedTime());
                                    }
                                    // 算法进度
                                    String calProgressInDb = patrolTaskStatusOfDb.getTaskEstimatedTime();
                                    logger.info("patrol_task_status taskPatrolledId: {}, run_progress: {}, db_progress: {}, cal_progress: {}",
                                            patrolTaskStatusItem.getTaskPatrolledId(),
                                            runProgress,
                                            dbProgress,
                                            calProgressInDb);
                                    if (runProgress > dbProgress) {
                                        patrolTaskStatusItem.setLineId(patrolTaskStatusOfDb.getLineId());
                                        logger.info(Color.CYAN + "updating patrol_task_status taskPatrolledId: {}, progress: {}, taskState: {}" + Color.END,
                                                patrolTaskStatusItem.getTaskPatrolledId(),
                                                runProgress,
                                                patrolTaskStatusItem.getTaskState());
                                        /*
                                         * 智能巡视任务下发完成100%, 在这个节点不能更新task_state字段, 原因如下:
                                         * 1. 不能更新task_state为已经完成状态, 因为整个任务的完成状态应该由算法任务是否完成来决定;
                                         * 2. 不能更新task_state为正在执行状态, 因为在测试环境下发现智巡任务比算法任务达到100进度还要晚,
                                         *    因此原本算法任务已经将状态置为已经完成的情况下为了防止智巡任务再把它改为执行中，所以此时只需要
                                         *    更新智巡的进度值为100即可
                                         */
                                        if ("100.0".equals(String.valueOf(runProgress))
//                                                && TaskStatus.RUNNING.getCode().equals(patrolTaskStatusItem.getTaskState())
                                        ) {
                                            List<PatrolTaskStatus> statusList = patrolTaskStatusService.selectPatrolTaskStatusList(PatrolTaskStatus.builder().taskPatrolledId(patrolTaskStatusItem.getTaskPatrolledId()).build());
                                            if (!statusList.isEmpty()) {
                                                logger.info(Color.CYAN + "updating patrol_task_status 100%, taskPatrolledId: {}, progress: {}, taskState: {}, taskCurCodeInRedis: {}" + Color.END,
                                                        patrolTaskStatusItem.getTaskPatrolledId(),
                                                        runProgress,
                                                        patrolTaskStatusItem.getTaskState(),
                                                        RedisConst.TASK_CURRENT_CODE + patrolTaskStatusItem.getTaskCode());
                                                PatrolTaskStatus taskStatus = statusList.get(0);
                                                taskStatus.setTaskProgress(String.valueOf(runProgress));
                                                // 仅当智巡进度100%+算法进度100%才更新任务状态为完成
                                                if ("100.0".equals(calProgressInDb)) {
                                                    logger.info("!!!!!!!!!!!!!!!!!! set task_status done!!!");
                                                    taskStatus.setTaskState(TaskStatus.DONE.getCode());
                                                }
                                                iPatrolTaskStatusService.updateTaskProgress(taskStatus.getLineId(), taskStatus.getTaskProgress(), null, taskStatus.getTaskState());
                                            }
                                        } else {
                                            List<PatrolTaskStatus> statusList = patrolTaskStatusService.selectPatrolTaskStatusList(PatrolTaskStatus.builder().taskPatrolledId(patrolTaskStatusItem.getTaskPatrolledId()).build());
                                            if (!statusList.isEmpty()) {
                                                PatrolTaskStatus taskStatus = statusList.get(0);
                                                // 仅当任务状态为正在执行状态时才更新进度
                                                if (TaskStatus.RUNNING.getCode().equals(taskStatus.getTaskState())) {
                                                    logger.info(Color.CYAN + "updating patrol_task_status state taskPatrolledId: {}, runProgress: {}, taskState: {}, taskCurCodeInRedis: {}, cal_progress_db: {}" + Color.END,
                                                            patrolTaskStatusItem.getTaskPatrolledId(),
                                                            runProgress,
                                                            patrolTaskStatusItem.getTaskState(),
                                                            RedisConst.TASK_CURRENT_CODE + patrolTaskStatusItem.getTaskCode(),
                                                            patrolTaskStatusOfDb.getTaskEstimatedTime());
                                                    patrolTaskStatusItem.setTaskState(TaskStatus.RUNNING.getCode());
                                                    patrolTaskStatusItem.setTaskProgress(String.valueOf(runProgress));
                                                    iPatrolTaskStatusService.updateTaskProgress(patrolTaskStatusItem.getLineId(), patrolTaskStatusItem.getTaskProgress(), null, patrolTaskStatusItem.getTaskState());
                                                }
                                            }
                                        }
                                        if ("E100-001".equals(sendCode)) {
                                            if (StringUtils.isNotEmpty(patrolTaskStatusItem.getTaskProgress()) &&
                                                    !patrolTaskStatusItem.getTaskProgress().contains("100")) {
                                                logger.info(Color.CYAN + "E100-001 directly save to result taskPatrolledId: {}, progress: {}, taskState: {}" + Color.END,
                                                        patrolTaskStatusItem.getTaskPatrolledId(),
                                                        patrolTaskStatusItem.getTaskProgress(),
                                                        patrolTaskStatusItem.getTaskState());
                                                saveDataToResultAnalysis(patrolTaskStatusItem.getTaskPatrolledId());
                                            }
                                        }
                                    }
                                } else {
                                    patrolTaskStatusItem.setPosType(str);
                                    patrolTaskStatusItem.setCreateTime(new Date());
                                    patrolTaskStatusItem.setStartTime(new Date());
                                    patrolTaskStatusItem.setTaskEstimatedTime("");
                                    patrolTaskStatusItem.setTaskType(TaskType.ORDINARY.getCode());
                                    String devType = patrolTaskDb.getDevType();
                                    String taskCode = patrolTaskDb.getTaskCode();
                                    String[] devTypeArray = Arrays.stream(devType.split(",")).distinct().toArray(String[]::new);
                                    // note 联合任务：任务包含多个设备类型 或者 单个非摄像头的设备类型有多个设备编码
                                    if (devTypeArray.length > 1 || (devTypeArray.length == 1 && !"2".equals(devTypeArray[0]) && patrolTaskDb.getDevNo().split(",").length > 1)) {
                                        // 当taskCode为多设备且redis中正在执行该taskCode的任务时，新增或ignore主任务
                                        final String taskCurrentCode = redisService.getCacheObjectOfTask(RedisConst.TASK_CURRENT_CODE, taskCode);
                                        logger.info(Color.CYAN + "task is union task, taskCode: {}, devType: {}, taskCurrentCode: {}" + Color.END, taskCode, devType, taskCurrentCode);
                                        if (StringUtils.isNotEmpty(taskCurrentCode)) {
                                            String execTime = taskCurrentCode.substring(taskCurrentCode.lastIndexOf("@") + 1);
                                            String taskPatrolledId = taskCode + "_" + execTime + "_uni";
                                            PatrolTaskStatus patrolTaskStatusMain = PatrolTaskStatus.builder()
                                                    .createTime(patrolTaskStatusItem.getCreateTime())
                                                    .startTime(patrolTaskStatusItem.getStartTime())
                                                    .taskPatrolledId(taskPatrolledId)
                                                    .taskCode(taskCode)
                                                    .posType("-1")
                                                    .taskState(TaskStatus.RUNNING.getCode())
                                                    .taskName(patrolTaskDb.getTaskName())
                                                    .taskProgress("0")
                                                    .taskEstimatedTime("0")
                                                    .taskType(TaskType.MAIN.getCode())
                                                    .build();

                                            patrolTaskStatusItem.setTaskName(sendCode + "@" + patrolTaskStatusItem.getTaskName());
                                            patrolTaskStatusItem.setMainId(patrolTaskStatusMain.getTaskPatrolledId());
                                            patrolTaskStatusItem.setTaskType(TaskType.SUB.getCode());

                                            int row = iPatrolTaskStatusService.insertIgnorePatrolTaskStatus(patrolTaskStatusMain);
                                            if (row > 0) {
                                                logger.info("主任务{}, patrolTaskStatusMain: {} 插入成功", patrolTaskStatusMain.getLineId(), patrolTaskStatusMain);
                                            } else {
                                                logger.info("主任务{}, taskPatrolledId: {} 已存在，忽略", patrolTaskStatusMain.getLineId(), patrolTaskStatusMain.getTaskPatrolledId());
                                            }
                                        }
                                    }

                                    // 普通任务或子任务
                                    i = iPatrolTaskStatusService.insertPatrolTaskStatus(patrolTaskStatusItem);
                                }
                            }
                        }
                    }
                    return toAjax(i);
                } else {
                    logger.info("GET_INFO_41 ROBOT_TASK_STATUS EMPTY");
                }
            } catch (Exception e) {
                logger.error("error", e);
            } finally {
                logger.info(Color.CYAN + "###### RECEIVE DATA TO ANALYSIS [41] end ######" + Color.END);
            }
        } else if (StaEnum.CtlModel.getCode().equals(type)) {
            logger.info(Color.CYAN + "###### RECEIVE DATA TO ANALYSIS [61] start ######" + Color.END);
            String Jqtype = "";
            HashSet<String> superiorFilePaths = new HashSet<>();
            JsonRootBean jsonRootBean;
            try {
                jsonRootBean = JSONObject.parseObject(messageBody, JsonRootBean.class);
                List<ItemsInfo> itemsInfoList = jsonRootBean.getItems();
                logger.info("点位数量: {}, 消息体: \n {}", itemsInfoList.size(), messageBody);
                for (ItemsInfo itemsInfo : itemsInfoList) {
                    if (StringUtils.isEmpty(itemsInfo.getMaterialId()) && StringUtils.isNotEmpty(itemsInfo.getDeviceId())) {
                        Map<String, String> deviceInfoMap = resultAnalysisService.selectDeviceInfo(itemsInfo.getDeviceId());
                        itemsInfo.setMaterialId(deviceInfoMap != null && StringUtils.isNotEmpty(deviceInfoMap.get("phyasset_id")) ? deviceInfoMap.get("phyasset_id") : "");
                    }

                    if (StringUtils.isEmpty(itemsInfo.getDataType())) {
                        if (StringUtils.isNotEmpty(itemsInfo.getPatrolDeviceCode())) {
                            Map<String, Object> eqbookMap = resultAnalysisService.selectEqInfoByCode(itemsInfo.getPatrolDeviceCode());
                            if (eqbookMap != null && eqbookMap.get("type") != null) {
                                String str = eqbookMap.get("type") + "";
                                if (str.equals("13")) {
                                    itemsInfo.setDataType("3");
                                } else if (!str.equals("1") && !str.equals("2") && !str.equals("3")) {
                                    itemsInfo.setDataType(str.equals("14") ? "4" : "1");
                                } else {
                                    itemsInfo.setDataType("2");
                                    Jqtype = "2";
                                }
                            } else {
                                itemsInfo.setDataType("");
                            }
                        }
                    } else {
                        Jqtype = itemsInfo.getDataType();
                    }

                    if (StringUtils.isEmpty(itemsInfo.getFileType())) {
                        itemsInfo.setFileType("");
                    }

                    if (StringUtils.isNotEmpty(itemsInfo.getFilePath())) {
                        superiorFilePaths.add(itemsInfo.getFilePath());
                    }
                }
            } catch (Exception e) {
                logger.error("error", e);
                jsonRootBean = new JsonRootBean();
            }

            int mainID = -1;
            JSONObject parseObject = JSONObject.parseObject(messageBody);
            Object jsonArray = parseObject.get("items");
            if (jsonArray == null) {
                jsonArray = parseObject.get("Items");
            }

            List<PatrolResult> patrolResultList = JSONArray.parseArray(jsonArray.toString(), PatrolResult.class);
            String code;
            if (!patrolResultList.isEmpty()) {
                code = "";
                String sendCode = parseObject.getString("SendCode");
                for (PatrolResult arr : patrolResultList) {
//                    Map<String, String> map = resultAnalysisService.selectPointInfoById(arr.getDeviceId());
//                    if (map == null) {
//                        Map<String, Object> maps = resultAnalysisService.selectPointInfoByCode(arr.getDeviceId());
//                        if (maps != null && maps.get("patrol_point_id") != null) {
//                            String patrolPointId = String.valueOf(maps.get("patrol_point_id"));
//                            arr.setDeviceId(patrolPointId);
//                        }
//                    } else {
//                        arr.setDeviceId(String.valueOf(map.get("patrol_point_id")));
//                    }
                    Long patrolPointId = baseDataClient.queryPatrolPointId(sendCode + "|" + arr.getDeviceId());
                    if (patrolPointId != null) {
                        arr.setDeviceId(patrolPointId.toString());
                    }
                    code = arr.getTaskCode();
                    patrolDeviceCodeList.add(arr.getPatrolDeviceCode());

                    //qinyl
//                    String taskPatrolledId = arr.getTaskPatrolledId();
//                    String taskCode = arr.getTaskCode();
//                    String taskName = arr.getTaskName();
//                    logger.info("CMD_61 taskPatrolledId: {}", taskPatrolledId);
//                    if(StringUtils.isNotEmpty(taskPatrolledId)) {
//                        PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
//                        patrolTaskStatus.setTaskPatrolledId(taskPatrolledId);
//                        List<PatrolTaskStatus> patrolTaskStatusList = iPatrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
//                        logger.info("CMD_61 patrolTaskStatusList size: {}", patrolTaskStatusList.size());
//                        if(patrolTaskStatusList.isEmpty()) {
//                            PatrolTaskStatus patrolTaskStatusItem = new PatrolTaskStatus();
//                            patrolTaskStatusItem.setTaskPatrolledId(taskPatrolledId);
//                            patrolTaskStatusItem.setTaskCode(taskCode);
//                            patrolTaskStatusItem.setTaskName(taskName);
//                            patrolTaskStatusItem.setTaskState("2");
//                            patrolTaskStatusItem.setTaskProgress("0");
//                            patrolTaskStatusItem.setTaskEstimatedTime("0");
//                            patrolTaskStatusItem.setCreateTime(new Date());
//                            patrolTaskStatusItem.setStartTime(new Date());
//                            patrolTaskStatusItem.setTaskEstimatedTime("");
//                            i = iPatrolTaskStatusService.insertPatrolTaskStatus(patrolTaskStatusItem);
//                            logger.info("CMD_61 CREATE patrol_task_status record taskPatrolledId: {}, i: {}", taskPatrolledId, i);
//                        }
//                    }
                }
                List<PatrolTask> tasks = patrolTaskService.selectPatrolTaskList(PatrolTask.builder().taskCode(code).build());
                String datetype;
                // 创建巡视归档记录taskMain
                PatrolTaskStatus mainTaskStatus = iPatrolTaskStatusService.selectPatrolTaskStatusMain(patrolResultList.get(0).getTaskPatrolledId());
                logger.info("mainTaskStatus: {}", mainTaskStatus);
                if (mainTaskStatus == null) {
                    logger.info("GET_INFO_61 ROBOT_TASK_STATUS CODE {} NO EXIST, SKIP IT!", patrolResultList.get(0).getTaskCode());
                    return toAjax(i);
                }
                PatrolTaskResultMain taskResultMain = new PatrolTaskResultMain();
                taskResultMain.setTaskId(String.valueOf(tasks.get(0).getTaskId()));
                taskResultMain.setTaskPatrolledId(mainTaskStatus.getTaskPatrolledId());
                logger.info("taskResultMain: {}", taskResultMain);
                List<PatrolTaskResultMain> patrolTaskResultMainList = iPatrolTaskResultMainService.selectPatrolTaskResultMainList(taskResultMain);
                if (!patrolTaskResultMainList.isEmpty()) {
                    mainID = patrolTaskResultMainList.get(0).getLineId().intValue();
                    logger.info("exist PatrolTaskResultMain Id: {}", mainID);
                } else {
                    mainID = iPatrolTaskStatusService.generateTaskResultMain(mainTaskStatus);
                    logger.info("insert PatrolTaskResultMain Id: {}", mainID);
                }

                List<PatrolResult> algrithomPatrolResultList = new ArrayList<>();
                for (PatrolResult patrolResult : patrolResultList) {
                    logger.info(Color.CYAN + "PatrolResult: {}" + Color.END, patrolResult);
                    datetype = "";
                    String str;
                    if (StringUtils.isNotEmpty(patrolResult.getPatrolDeviceCode())) {
                        Map<String, Object> eqbookMap = resultAnalysisService.selectEqInfoByCode(patrolResult.getPatrolDeviceCode());
                        if (eqbookMap != null && eqbookMap.get("type") != null) {
                            str = eqbookMap.get("type") + "";
                            if (str.equals("13")) {
                                datetype = "3";
                            } else if (!str.equals("1") && !str.equals("2") && !str.equals("3")) {
                                datetype = str.equals("14") ? "4" : "1";
                            } else {
                                datetype = "2";

                            }
                        }
                    }

                    PatrolResult patrolResultParam = new PatrolResult();
                    patrolResultParam.setTaskPatrolledId(patrolResult.getTaskPatrolledId());
//                    str = parseObject.getString("SendCode");
                    String strfile;
//                    if ("2".equals(datetype)) {
//                        logger.info("feedback from robot");
//                        Long patrolPointId = baseDataClient.queryPatrolPointId(str + "|" + patrolResult.getDeviceId());
//                        if (patrolPointId != null) {
//                            patrolResult.setDeviceId(patrolPointId.toString());
//                        }
//                        InputStream is = null;
//                        String filePath = patrolResult.getFilePath();
//                        if (filePath != null && !filePath.isEmpty()) {
//                            String[] filePathArr = filePath.split(StringUtils.COMMA);
//                            for (String s : filePathArr) {
//                                is = doGetRequestForInputStream(intranetFtpAddress + s);
//                            }
//                        }
//                        InputStream is = doGetRequestForInputStream(intranetFtpAddress + patrolResult.getFilePath());

//                        logger.info("feedback from robot image size: {}", (is != null));
//                        if (is != null) {
//                            try {
//                                is = ImageUtil.overlaying(is, patrolResult.getRectangle(), patrolResult.getValue());
//                                strfile = patrolResult.getFilePath();
//                                strfile = strfile.substring(0, strfile.lastIndexOf("/"));
//                                String fileName = "modify_" + strfile.substring(strfile.lastIndexOf("/") + 1);
//                                String file = saveFile(is, fileName, strfile);
//                                patrolResult.setFilePath(file);
//                                logger.info("robot image path: {}", file);
//                            } catch (Exception e) {
//                                //e.printStackTrace();
//                                logger.info("ImageUtil.overlaying error: {}", e.getMessage());
//                            }
//                        }
//                    }

                    // 无人机点位id处理
//                    if ("3".equals(datetype)) {
//                        Long patrolPointId = baseDataClient.queryPatrolPointId(str + "|" + patrolResult.getDeviceId());
//                        if (patrolPointId != null) {
//                            patrolResult.setDeviceId(patrolPointId.toString());
//                        }
//                    }

                    patrolResultParam.setDeviceId(patrolResult.getDeviceId());
                    patrolResultParam.setDataType(datetype);
                    List<PatrolResult> results = patrolResultService.selectPatrolResultList(patrolResultParam);
                    if (!results.isEmpty()) {
                        //patrol_result记录已存在则更新
                        logger.info("SEND_MESSAGE UPDATE dateType: {}, patrol_result: {}", datetype, patrolResult);
                        PatrolResult patrolResult2 = results.get(0);
                        patrolResult2.setCoordinatePixel(patrolResult.getCoordinatePixel());
                        if (StringUtils.isNotEmpty(patrolResult.getFilePath())) {
                            patrolResult2.setFilePath(patrolResult.getFilePath());
                        }

                        if (StringUtils.isNotEmpty(patrolResult.getFileType())) {
                            String fileType = patrolResult.getFileType();
                            if (fileType.indexOf(StringUtils.COMMA) > 0 && fileType.endsWith(StringUtils.COMMA)) {
                                // 去掉最后一个逗号
                                patrolResult2.setFileType(fileType.substring(0, fileType.lastIndexOf(StringUtils.COMMA)));
                            } else {
                                patrolResult2.setFileType(fileType);
                            }
                        }

                        if (StringUtils.isNotEmpty(patrolResult.getTime())) {
                            patrolResult2.setTime(patrolResult.getTime());
                        }

                        if ("2".equals(datetype)) {
                            if (StringUtils.isNotEmpty(patrolResult.getUnit())) {
                                patrolResult2.setUnit(patrolResult.getUnit());
                            }

                            if (StringUtils.isNotEmpty(patrolResult.getValid())) {
                                patrolResult2.setValid(patrolResult.getValid());
                            }

                            if (StringUtils.isNotEmpty(patrolResult.getValue())) {
                                patrolResult2.setValue(patrolResult.getValue());
                            }

                            if (StringUtils.isNotEmpty(patrolResult.getValueType())) {
                                patrolResult2.setValueType(patrolResult.getValueType());
                            }

                            if (StringUtils.isNotEmpty(patrolResult.getValueUnit())) {
                                patrolResult2.setValueUnit(patrolResult.getValueUnit());
                            }
                        }

                        Map<String, String> valueMap = patrolResultService.getPatrolResultValue(patrolResult);
                        if (null != valueMap && !valueMap.isEmpty()) {
                            logger.info("valueMap:" + valueMap.get("value") + ",value_unit:" + valueMap.get("value_unit"));
                            if (valueMap.containsKey("value") && null != valueMap.get("value")) {
                                strfile = valueMap.get("value");
                                patrolResult.setValue(strfile);
                            }

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

                        if (StringUtils.isNotEmpty(patrolResult.getFilePath()) && patrolResult.getFilePath().contains(patrolTaskFtp.getFtpPath())) {
                            strfile = patrolResult.getFilePath().replaceAll(patrolTaskFtp.getFtpPath().concat(StringUtils.SLASH), StringUtils.EMPTY);
                            if (StringUtils.isNotEmpty(strfile)) {
                                patrolResult2.setFilePath(strfile);
                            }
                        }

                        logger.info("SEND_MESSAGE UPDATE patrolResult2: {}", patrolResult2);
                        i = patrolResultService.updatePatrolResult(patrolResult2);
//                        if (!"2".equals(Jqtype)) {
                        algrithomPatrolResultList.add(patrolResult2);
//                        }
                    } else {
                        //patrol_result记录不存在则新增
                        logger.info("SEND_MESSAGE NEW dateType: {}, patrol_result: {}", datetype, patrolResult);
                        patrolResult.setMainId(mainID + "");
                        Map<String, String> stringStringMap = patrolResultService.selectThresholdByPointId(patrolResult.getDeviceId());
                        if (stringStringMap != null && StringUtils.isNotEmpty(stringStringMap.get("alarm_threshold"))) {
                            patrolResult.setThreshold(stringStringMap.get("alarm_threshold"));
                        }

                        patrolResult.setPatrolStatus("0");
                        if (StringUtils.isNotEmpty(patrolResult.getPatrolDeviceCode())) {
                            Map<String, Object> valueMap = resultAnalysisService.selectEqInfoByCode(patrolResult.getPatrolDeviceCode());
                            if (valueMap != null && valueMap.get("type") != null) {
                                strfile = valueMap.get("type") + "";
                                if (strfile.equals("13")) {
                                    patrolResult.setDataType("3");
                                } else if (!strfile.equals("1") && !strfile.equals("2") && !strfile.equals("3")) {
                                    patrolResult.setDataType(strfile.equals("14") ? "4" : "1");
                                } else {
                                    patrolResult.setDataType("2");
                                }
                            }
                        }

                        if (StringUtils.isNotEmpty(patrolResult.getFilePath()) && patrolResult.getFilePath().contains(patrolTaskFtp.getFtpPath())) {
                            strfile = patrolResult.getFilePath().replaceAll(patrolTaskFtp.getFtpPath() + "/", StringUtils.EMPTY);
                            if (StringUtils.isNotEmpty(strfile)) {
                                patrolResult.setFilePath(strfile);
                            }
                        }

                        if (StringUtils.isNotEmpty(patrolResult.getFileType())) {
                            String fileType = patrolResult.getFileType();
                            if (fileType.indexOf(StringUtils.COMMA) > 0 && fileType.endsWith(StringUtils.COMMA)) {
                                // 去掉最后一个逗号
                                patrolResult.setFileType(fileType.substring(0, fileType.lastIndexOf(StringUtils.COMMA)));
                            } else {
                                patrolResult.setFileType(fileType);
                            }
                        }

                        Map<String, String> valueMap = patrolResultService.getPatrolResultValue(patrolResult);
                        if (null != valueMap && !valueMap.isEmpty()) {
                            logger.info("valueMap:" + valueMap.get("value") + ",value_unit:" + valueMap.get("value_unit"));
                            if (valueMap.containsKey("value") && null != valueMap.get("value")) {
                                strfile = valueMap.get("value");
                                patrolResult.setValue(strfile);
                            }

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

                        logger.info("SEND_MESSAGE NEW patrolResult: {}", patrolResult);
                        Map<String, String> map = resultAnalysisService.selectPointInfoById(patrolResult.getDeviceId());
                        String unit = map.get("purpose");
                        patrolResult.setUnit(unit);
                        i = patrolResultService.insertPatrolResult(patrolResult);//
                        resultStatistics.compare(patrolResult);
//                        if (!"2".equals(Jqtype)) {
                        algrithomPatrolResultList.add(patrolResult);
//                        }
                    }
                }

                if (!algrithomPatrolResultList.isEmpty()) {
                    logger.info(Color.CYAN + "+++++++ callAlgorithm start +++++++" + Color.END);
                    // 非摄像头的设备任务，需要从数据库统计执行点位数量
                    if (jsonRootBean.getTotalNumber() == null && !tasks.isEmpty()) {
                        logger.info("jsonRootBean.getTotalNumber not NULL: {}", algrithomPatrolResultList);
                        String taskCode = String.valueOf(tasks.get(0).getTaskId());
                        logger.info("taskCode: {}, sendCode: {}", taskCode, sendCode);
                        // 获取设备标识，以便统计执行点位数量
                        List<String> algList = patrolResultService.selectAlgList(taskCode, sendCode, tasks.get(0).getSpecifiedAlg());
                        logger.info("algList: {}", algList.toString());
                        int algCount = 0;
                        for (String alg : algList) {
                            String[] sub = alg.split(StringUtils.COMMA);
                            algCount += sub.length;
                        }
                        logger.info("algCount: {}", algCount);
                        jsonRootBean.setTotalNumber(algCount);
                    }
                    if (!tasks.isEmpty()) {
                        callRemoteAlgorithm(jsonRootBean.getTotalNumber(), algrithomPatrolResultList);
                    } else {
                        logger.info(Color.CYAN + "callAlgorithm task: {} not exist!!!" + Color.END, code);
                    }
                    logger.info(Color.CYAN + "+++++++ callAlgorithm end +++++++" + Color.END);
                }
            }

            if (CollectionUtils.isNotEmpty(patrolDeviceCodeList)) {
                try {
                    code = patrolDeviceCodeList.stream().distinct().collect(Collectors.joining(StringUtils.COMMA));
                    deviceStateMapper.updatePatrolDeviceTaskState(code);
                } catch (Exception e) {
                    logger.error("error", e);
                }
            }
            logger.info(Color.CYAN + "###### RECEIVE DATA TO ANALYSIS [61] end ######" + Color.END);
        }

        return toAjax(i);
    }

    public void saveDataToResultAnalysis(String taskPatrolledId) {
        logger.info("[RES] ROBOT TASK FINISHED, AMEND ANALYSIS DATA");
        PatrolResult patrolResult = new PatrolResult();
        patrolResult.setTaskPatrolledId(taskPatrolledId);
        List<PatrolResult> list = patrolResultService.selectPatrolResultList(patrolResult);
        ResultAnalysis resultAnalysis;
        for (Iterator<PatrolResult> iterator = list.iterator(); iterator.hasNext(); resultAnalysisService.insertResultAnalysis(resultAnalysis)) {
            PatrolResult pr = iterator.next();
            Map<String, String> map = resultAnalysisService.selectPointInfoById(pr.getDeviceId());
            String alarm_threshold = map.get("alarm_threshold");
            double lowerValue = 0.0D;
            double upperValue = 0.0D;
            if (alarm_threshold != null) {
                JSONArray jsonArrayInfrared = JSONArray.parseArray(alarm_threshold);
                for (Object object : jsonArrayInfrared) {
                    JSONObject jsonObjectInfrared = JSONObject.parseObject(String.valueOf(object));
                    if (jsonObjectInfrared.get("upperValue") != null) {
                        upperValue = Double.parseDouble(String.valueOf(jsonObjectInfrared.get("upperValue")));
                    }

                    if (jsonObjectInfrared.get("lowerValue") != null) {
                        lowerValue = Double.parseDouble(String.valueOf(jsonObjectInfrared.get("lowerValue")));
                    }
                }
            }

            resultAnalysis = new ResultAnalysis();
            double parsedDouble = Double.parseDouble(pr.getValue());
            if ("1".equals(pr.getValid())) {
                if (lowerValue == 0.0D && upperValue == 0.0D) {
                    resultAnalysis.setResultType("1");
                    resultAnalysis.setResStatus("1");
                    resultAnalysis.setPointStatus("1");
                    resultAnalysis.setDescription(messageUtils.get("数值正常"));
                } else if (parsedDouble > lowerValue && parsedDouble < upperValue) {
                    resultAnalysis.setResultType("1");
                    resultAnalysis.setResStatus("1");
                    resultAnalysis.setPointStatus("1");
                    resultAnalysis.setDescription(messageUtils.get("数值正常"));
                } else {
                    resultAnalysis.setResultType("0");
                    resultAnalysis.setResStatus("0");
                    resultAnalysis.setPointStatus("0");
                    if (parsedDouble < lowerValue) {
                        resultAnalysis.setDescription(messageUtils.get("数值小于告警阈值最小值"));
                    }

                    if (parsedDouble > upperValue) {
                        resultAnalysis.setDescription(messageUtils.get("数值大于告警阈值最大值"));
                    }
                }
            } else {
                resultAnalysis.setResultType("2");
                resultAnalysis.setResStatus("0");
                resultAnalysis.setPointStatus("0");
                resultAnalysis.setDescription(messageUtils.get("巡视异常"));
            }

            resultAnalysis.setBusinessId(String.valueOf(pr.getLineId()));
            resultAnalysis.setResultContent("");
            resultAnalysis.setCreateTime(new Date());
            resultAnalysis.setObjectId(pr.getDeviceId());
            String[] strings = pr.getFilePath().split(StringUtils.COMMA);
            if (strings.length > 1) {
                resultAnalysis.setResultContent("{\"resultList\": [{\"results\": [{\"type\": [\"infrared\"],\"resImageUrl\": \"" + strings[1] + "\"}]}]}");
            } else {
                resultAnalysis.setResultContent("{\"resultList\": [{\"results\": [{\"type\": [\"infrared\"],\"resImageUrl\": \"" + strings[0] + "\"}]}]}");
            }
        }
    }

    @GetMapping({"/taskAndstatus"})
    public AjaxResult getInfo(String eqpbookId) {
        PatrolTask patrolTask = new PatrolTask();
        patrolTask.setDevNo(eqpbookId);
        List<PatrolTask> patrolTaskList = patrolTaskService.selectPatrolTaskList(patrolTask);
        if (!patrolTaskList.isEmpty()) {
            for (PatrolTask arr : patrolTaskList) {
                PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
                patrolTaskStatus.setTaskCode(arr.getTaskCode());
                patrolTaskStatus.setTaskState("2");
                List<PatrolTaskStatus> statusList = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
                if (!statusList.isEmpty()) {
                    arr.setFileStatus("1");
                } else {
                    arr.setFileStatus("0");
                }
            }
        }

        return AjaxResult.success(patrolTaskList);
    }

    @GetMapping({"/productionAndstatus"})
    public AjaxResult productionAndStatus(String id) {
        PatrolTask patrolTask = new PatrolTask();
        patrolTask.setDeviceList(id);
        List<PatrolTask> patrolTaskList = patrolTaskService.selectPatrolTaskList(patrolTask);
        if (!patrolTaskList.isEmpty()) {
            for (PatrolTask task : patrolTaskList) {
                PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
                patrolTaskStatus.setTaskCode(task.getTaskCode());
                patrolTaskStatus.setTaskState("2");
                List<PatrolTaskStatus> statusList = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
                task.setFileStatus(statusList.isEmpty() ? "0" : "1");
            }
        }

        return AjaxResult.success(patrolTaskList);
    }

    @GetMapping({"/getEqpBookListInfoForXml"})
    public String getEqpBookListInfo(BasedataEqpBookMoMain basedataEqpBook) {
        logger.info("--------getEqpBookListInfo 1!!!!!!");
        Map<String, String> stationMap = patrolResultService.selectBasedataStation();
        String stationNo = stationMap.get("station_no");
        // 灵州站编码
        if ("lingzhouzhiliu".equals(stationNo)) {
            stationNo = "1cc010d8a78a598ccb52fb470301531cbff88e26c5";
        }
        String stationName = stationMap.get("station_name");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PatrolTaskFtp patrolTaskFtp = patrolTaskFtpService.selectPatrolTaskFtpByLineId(3L);
        List<String> algId = new ArrayList<>(); //设备类型，巡视主机 20，机器人 1，2，3，摄像机及硬盘录像机 10，11，无人机及无人机巢 13，声纹 14
        String filename;
        String modelXml = null;
        String contype = ""; // 1:设备模型，2：任务文件，3：检修区域配置文件
        String type = basedataEqpBook.getType();
        String str;
        switch (type) {
            // 巡视主机及分析主机模型
            case "1":
                algId.add("20");
                contype = "1";
                break;
            case "2":
                // 机器人模型
                algId.add("1");
                algId.add("2");
                algId.add("3");
                contype = "1";
                break;
            case "3":
                // 摄像机及硬盘录像机模型
                algId.add("10");
                algId.add("11");
                contype = "1";
                break;
            default:
                String path;
                switch (type) {
                    // 点位模型
                    case "4":
                        logger.info("--------getEqpBookListInfo 2 type:4!!!!!!");
                        path = baseDataClient.superSystemSynPatrolPointModel();
                        str = "{\"device_file_path\":\"" + path + "\"}";
                        return str;
                    case "5":
                        // 无人机及无人机巢模型
                        algId.add("13");
                        contype = "1";
                        break;
                    case "6":
                        // 声纹模型
                        algId.add("14");
                        contype = "1";
                        break;
                    case "7":
                        // 任务文件
                        algId.add("-1");
                        contype = "2";
                        break;
                    case "8":
                        // 检修区域配置文件
                        algId.add("-1");
                        contype = "3";
                        break;
                    case "9":
                        // 地图文件
                        path = baseDataClient.setSendServiceForMap();
                        str = "{\"map_file_path\":\"" + path + "\"}";
                        return str;
                }

                break;
        }

        GenXmlByBean pulseGet;
        if (contype.equals("1")) {
            basedataEqpBook.setAlgId(algId);
            new SimpleDateFormat("yyyyMMdd");
            basedataEqpBook.setType(null);
//            List<BasedataEqpBookMoMain> list = patrolResultService.selectBasedataEqpBookList(basedataEqpBook);
            List<BasedataEqpBookMoMain> list = patrolResultService.selectCamera(basedataEqpBook);
            logger.info("--------getEqpBookListInfo new list size:{}!!!!!!", list.size());
            ArrayList items;
            if (null != list && !list.isEmpty()) {
                items = new ArrayList<>();
                BasedataEqpBookXml basedataEqpbookXml;
                for (Iterator<BasedataEqpBookMoMain> iterator = list.iterator(); iterator.hasNext(); items.add(basedataEqpbookXml)) {
                    BasedataEqpBookMoMain book = iterator.next();
                    basedataEqpbookXml = new BasedataEqpBookXml();
                    BeanUtils.copyBeanProp(basedataEqpbookXml, book);
                    basedataEqpbookXml.setStationCode(stationNo);
                    basedataEqpbookXml.setStationName(stationName);
                    basedataEqpbookXml.setPatrolDeviceCode(book.getUpSystemDeviceCode());

                    if (basedataEqpbookXml.getDeviceModel() == null) {
                        basedataEqpbookXml.setDeviceModel("");
                    }

                    if (basedataEqpbookXml.getManufacturer() == null) {
                        basedataEqpbookXml.setManufacturer("");
                    }

                    if (basedataEqpbookXml.getUseUnit() == null) {
                        basedataEqpbookXml.setUseUnit("");
                    }

                    if (basedataEqpbookXml.getDeviceSource() == null) {
                        basedataEqpbookXml.setDeviceSource("");
                    }

                    if (basedataEqpbookXml.getProductionDate() == null) {
                        basedataEqpbookXml.setProductionDate("");
                    }

                    if (basedataEqpbookXml.getProductionCode() == null) {
                        basedataEqpbookXml.setProductionCode("");
                    }

                    if (basedataEqpbookXml.getUseMode() == null) {
                        basedataEqpbookXml.setUseMode("");
                    }

                    if (basedataEqpbookXml.getVideoMode() == null) {
                        basedataEqpbookXml.setVideoMode("");
                    }

                    if (basedataEqpbookXml.getPlace() == null) {
                        basedataEqpbookXml.setPlace("");
                    }

                    if (basedataEqpbookXml.getPatrolDeviceInfo() == null) {
                        basedataEqpbookXml.setPatrolDeviceInfo("");
                    }

                    if (basedataEqpbookXml.getMountPatrolDeviceCode() == null) {
                        basedataEqpbookXml.setMountPatrolDeviceCode("");
                    }

//                    if (StringUtils.isNotEmpty(basedataEqpbookXml.getDelFlag())) {
//                        basedataEqpbookXml.setDelFlag(null);
//                    }
                }

                pulseGet = new GenXmlByBean<>();
                PatrolDeviceXml pd = new PatrolDeviceXml();
                pd.setItem(items);
                modelXml = pulseGet.getXml(pd);
            } else {
                items = new ArrayList();
                BasedataEqpBookXml basedataEqpbookXml = new BasedataEqpBookXml();
                items.add(basedataEqpbookXml);
                pulseGet = new GenXmlByBean<>();
                PatrolDeviceXml pd = new PatrolDeviceXml();
                pd.setItem(items);
                modelXml = pulseGet.getXml(pd);
            }
        } else {
            List maintAreaList;
            ArrayList items;
            Iterator iterator;
            if (contype.equals("2")) {
                // 同步任务文件
                maintAreaList = patrolTaskService.selectPatrolTaskList(new PatrolTask());
                if (null != maintAreaList && !maintAreaList.isEmpty()) {
                    items = new ArrayList<>();

                    PatrolTaskXML patrolTaskXML;
                    for (iterator = maintAreaList.iterator(); iterator.hasNext(); items.add(patrolTaskXML)) {
                        PatrolTask book = (PatrolTask) iterator.next();
                        patrolTaskXML = new PatrolTaskXML();
                        BeanUtils.copyBeanProp(patrolTaskXML, book);
                        patrolTaskXML.setStationCode(stationNo);
                        patrolTaskXML.setStationName(stationName);
                        noNullStringAttr(patrolTaskXML);
                        if (book.getFixedStartTime() != null) {
                            patrolTaskXML.setFixedStartTime(sdf.format(book.getFixedStartTime()));
                        }

                        if (book.getCycleExecuteTime() != null) {
                            patrolTaskXML.setCycleExecuteTime(book.getCycleExecuteTime());
                        }

                        if (book.getCycleStartTime() != null) {
                            patrolTaskXML.setCycleStartTime(sdf.format(book.getCycleStartTime()));
                        }

                        if (book.getCycleEndTime() != null) {
                            patrolTaskXML.setCycleEndTime(sdf.format(book.getCycleEndTime()));
                        }

                        if (book.getIntervalExecuteTime() != null) {
                            patrolTaskXML.setIntervalExecuteTime(book.getIntervalExecuteTime());
                        }

                        if (book.getIntervalStartTime() != null) {
                            patrolTaskXML.setIntervalStartTime(sdf.format(book.getIntervalStartTime()));
                        }

                        if (book.getIntervalEndTime() != null) {
                            patrolTaskXML.setIntervalEndTime(sdf.format(book.getIntervalEndTime()));
                        }

                        if (book.getInvalidStartTime() != null) {
                            patrolTaskXML.setInvalidStartTime(sdf.format(book.getInvalidStartTime()));
                        }

                        if (book.getInvalidEndTime() != null) {
                            patrolTaskXML.setInvalidEndTime(sdf.format(book.getInvalidEndTime()));
                        }

                        if (book.getCreateTime() != null) {
                            patrolTaskXML.setCreateTime(sdf.format(book.getCreateTime()));
                        }

                        if (book.getIntervalNumber() != 0) {
                            patrolTaskXML.setIntervalNumber(book.getIntervalNumber() + "");
                        }
                    }

                    pulseGet = new GenXmlByBean<>();
                    PatrolTaskModuleXml pd = new PatrolTaskModuleXml();
                    pd.setItem(items);
                    modelXml = pulseGet.getXml(pd);
                } else {
                    items = new ArrayList<>();
                    PatrolTaskXML patrolTaskXML = new PatrolTaskXML();
                    items.add(patrolTaskXML);
                    pulseGet = new GenXmlByBean<>();
                    PatrolTaskModuleXml pd = new PatrolTaskModuleXml();
                    pd.setItem(items);
                    modelXml = pulseGet.getXml(pd);
                }
            } else if (contype.equals("3")) {
                // 同步维护区域文件
                maintAreaList = maintainRegionService.selectMaintainRegionList(new MaintainRegion());
                if (null != maintAreaList && !maintAreaList.isEmpty()) {
                    items = new ArrayList<>();

                    MaintainAreaXML up;
                    for (iterator = maintAreaList.iterator(); iterator.hasNext(); items.add(up)) {
                        MaintainRegion book = (MaintainRegion) iterator.next();
                        up = new MaintainAreaXML();
                        BeanUtils.copyBeanProp(up, book);
                        noNullStringAttr(up);
                        up.setStationCode(stationNo);
                        up.setStationName(stationName);
                        if (book.getStartTime() != null) {
                            up.setStartTime(sdf.format(book.getStartTime()));
                        }

                        if (book.getEndTime() != null) {
                            up.setEndTime(sdf.format(book.getEndTime()));
                        }
                    }

                    pulseGet = new GenXmlByBean<>();
                    PatrolMaintainModuleXml pd = new PatrolMaintainModuleXml();
                    pd.setItem(items);
                    modelXml = pulseGet.getXml(pd);
                } else {
                    items = new ArrayList<>();
                    MaintainAreaXML maintainAreaXML = new MaintainAreaXML();
                    items.add(maintainAreaXML);
                    pulseGet = new GenXmlByBean<>();
                    PatrolMaintainModuleXml pd = new PatrolMaintainModuleXml();
                    pd.setItem(items);
                    modelXml = pulseGet.getXml(pd);
                }
            }
        }

        logger.info("--------getEqpBookListInfo 2 type:other!!!!!!");
        InputStream inputStream = new ByteArrayInputStream(modelXml.getBytes());

        str = "";
        switch (type) {
            case "1":
                str = "host";
                break;
            case "2":
                str = "robot";
                break;
            case "3":
                str = "video";
                break;
            case "4":
                str = "device";
                break;
            case "5":
                str = "drone";
                break;
            case "6":
                str = "voice";
                break;
            case "7":
                str = "task";
                break;
            case "8":
                str = "overhaularea";
                break;
            case "9":
                str = "map";
                break;
        }

        filename = str + "_" + System.currentTimeMillis() + ".xml";
        DataMsg DataMsg = new DataMsg();
        DataMsg.setIp(patrolTaskFtp.getFtpIp());
        DataMsg.setPort(patrolTaskFtp.getFtpPort());
        DataMsg.setUsername(patrolTaskFtp.getFtpUserName());
        DataMsg.setPassword(patrolTaskFtp.getFtpPwd());
        DataMsg.setBasePath(patrolTaskFtp.getFtpPath());
        DataMsg.setType("0");
        String algorithmBaseImagePath = stationNo + "/Model/";
        DataMsg.setFilePath(algorithmBaseImagePath);
        DataMsg.setFileName(filename);
        DataMsg.setInputStream(inputStream);
        DataMsg.setIsImplicit("true");
        logger.info("--------getEqpBookListInfo 3!!!!!!");
        SFTPUtil.uploadFileForXml(DataMsg);
        logger.info("--------getEqpBookListInfo 4!!!!!!");
        String typename = "";
        switch (type) {
            case "1":
                typename = "host_file_path";
                break;
            case "2":
                typename = "robot_file_path";
                break;
            case "3":
                typename = "video_file_path";
                break;
            case "4":
                typename = "device_file_path";
                break;
            case "5":
                typename = "drone_file_path";
                break;
            case "6":
                typename = "voice_file_path";
                break;
            case "7":
                typename = "task_file_path";
                break;
            case "8":
                typename = "overhaularea_file_path";
                break;
            case "9":
                typename = "map_file_path";
                break;
        }

        logger.info("--------getEqpBookListInfo 5!!!!!!");
        String path = "";
        UploadResponse uploadResponse = new UploadResponse("test", "http://emptu.com");
        try {
            MultipartFile multipartFile = MultipartFileUtils.toMultipartFile(new ByteArrayInputStream(modelXml.getBytes()),
                    filename,
                    ("application/octet-stream"));
            uploadResponse = feignMinioService.uploadFileToMinio(multipartFile);
            path = uploadResponse.getUrl();
            logger.info("path: " + path);
        } catch (Exception e) {
            logger.error("error", e);
        }

        return "{\"" + typename + "\":\"" + path + "\"}";
    }

    public static <T> T noNullStringAttr(T cls) {
        Field[] fields = cls.getClass().getDeclaredFields();
        for (Field field : fields) {
            if ("String".equals(field.getType().getSimpleName())) {
                field.setAccessible(true);
                try {
                    Object value = field.get(cls);
                    if (value == null) {
                        field.set(cls, "");
                    }
                } catch (IllegalAccessException | IllegalArgumentException e) {
                    e.printStackTrace();
                }
            }
        }
        return cls;
    }

    @PostMapping({"/lasupload"})
    public String list(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        String algorithmBaseImagePath = "algorithm_base_image/";
        SftpUploadEntity sftpUploadEntity = new SftpUploadEntity(file.getInputStream());
        sftpUploadEntity.setFilePath(algorithmBaseImagePath);
        return sftpClient.upload(sftpUploadEntity);
    }

    @GetMapping({"/fileInputStream"})
    public void pathInputStream(String path, HttpServletResponse httpServletResponse) throws Exception {
        sftpClient.downLoad(path, (inputStream) -> {
            try (ServletOutputStream outputStream = httpServletResponse.getOutputStream()) {
                byte[] bytes = new byte[1024];

                int index;
                while ((index = inputStream.read(bytes)) > -1) {
                    outputStream.write(Arrays.copyOfRange(bytes, 0, index));
                }

                outputStream.flush();
            }
        });
    }

    @PostMapping({"/openApi/{type}/{date}"})
    public AjaxResult openApi(@PathVariable String type, @PathVariable String date) {
        Date newTime = DateUtils.parse(DateUtils.yyyyMMdd2, date);
        PatrolResult patrolResult = new PatrolResult();
        patrolResult.setCreateTime(newTime);
        List<ResultValue> list = new ArrayList<>();
        long start = System.currentTimeMillis();
        if ("1".equals(type)) {
            list = patrolResultService.selectOilResultValue(patrolResult);
        }
        logger.info("openApi selectOilResultValue cost: {}ms", System.currentTimeMillis() - start);

        start = System.currentTimeMillis();
        if ("2".equals(type)) {
            list = patrolResultService.select6FsResultValue(patrolResult);
        }
        logger.info("openApi select6FsResultValue cost: {}ms", System.currentTimeMillis() - start);

        for (ResultValue object : list) {
            object.setValue(object.formatValue(object.getValue()));
        }

        return AjaxResult.success(list);
    }

    public static InputStream doGetRequestForInputStream(String urlStr) {
        String DEFAULT_CHARSET = "utf-8";
        InputStream is = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type", "plain/text;charset=" + DEFAULT_CHARSET);
            conn.setRequestProperty("charset", DEFAULT_CHARSET);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return is;
    }

    public String saveFile(InputStream is, String fileName, String fileTypeDir) {
        DataMsg dataMsg = new DataMsg();
        try {
            SftpUploadEntity sftpUploadEntity = new SftpUploadEntity(is);
            sftpUploadEntity.setFilePath(fileTypeDir);
            sftpUploadEntity.setFileName(fileName);
            return sftpClient.upload(sftpUploadEntity);
        } catch (Exception e) {
            logger.error("[RES] UPLOAD TO FTP EXCEPTION: {}", e.getMessage());
            return dataMsg.getFilePath() + "/" + fileName;
        }
    }

    /**
     * 获取巡检告警结果列表接⼝
     *
     * @param pointDataVo
     * @return
     */
    @GetMapping({"/pointTrendData"})
    public AjaxResult pointTrendData(PointDataVo pointDataVo) {
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        if (StringUtils.isNotEmpty(pointDataVo.getStartTime()) && StringUtils.isNotEmpty(pointDataVo.getEndTime())) {
            // 补全开始和结束时间
            startDateTime = LocalDateTime.parse(pointDataVo.getStartTime() + " 00:00:00", formatter);
            endDateTime = LocalDateTime.parse(pointDataVo.getEndTime() + " 23:59:59", formatter);
        }
        PatrolResult patrolResult = new PatrolResult();
        patrolResult.setDeviceId(pointDataVo.getDeviceId());
        List<PatrolResult> list = patrolResultService.selectPatroByAllDev(patrolResult);
        List<PointDataResultVo> between_list = new ArrayList<>();
        for (PatrolResult result : list) {
            LocalDateTime resultDateTime = LocalDateTime.parse(result.getTime(), formatter);
            PatrolResultAux pra = new PatrolResultAux();
            pra.setResultId(result.getLineId() + "");
            List<PatrolResultAux> pra1 = iPatrolResultAuxService.selectPatrolResultAuxList(pra);
            if (!pra1.isEmpty()) {
                result.setValue(pra1.get(0).getValue());
            }

            if ("0".equals(result.getValue())) {
                result.setValue("正常");
            }

            if ("-1".equals(result.getValue()) || "1".equals(result.getValue())) {
                result.setValue("异常");
            }
            if (StringUtils.isNotEmpty(pointDataVo.getStartTime()) && StringUtils.isNotEmpty(pointDataVo.getEndTime())) {
                // 使用if判断时间范围
                if (!resultDateTime.isBefore(startDateTime) && !resultDateTime.isAfter(endDateTime)) {
                    PointDataResultVo patrolResultVo = new PointDataResultVo();
                    patrolResultVo.setTime(result.getTime());
                    patrolResultVo.setValue(result.getValue());
                    between_list.add(patrolResultVo);
                } else {

                }
            } else {
                PointDataResultVo patrolResultVo = new PointDataResultVo();
                patrolResultVo.setTime(result.getTime());
                patrolResultVo.setValue(result.getValue());
                between_list.add(patrolResultVo);
            }
        }
        return AjaxResult.success(between_list);
    }

    @GetMapping({"/inspectResult"})
    public AjaxResult inspectResult(InspectionPointParam inspectionPointParam) {
        inspectionPointParam.setOffset((inspectionPointParam.getPageNum() - 1) * inspectionPointParam.getPageSize());
        List<InspectionPointResultVo> inspectionPointResultVo = patrolResultService.inspectResult(inspectionPointParam);
        if (!inspectionPointResultVo.isEmpty()) {
            for (InspectionPointResultVo brr : inspectionPointResultVo) {
//                String pointId;
//                if (StringUtils.isNotEmpty(brr.getComponentId()) && StringUtils.isEmpty(brr.getDeviceName())) {
//                    pointId = this.recursionGetNameId(brr.getComponentId());
//                    if (StringUtils.isNotEmpty(pointId)) {
//                        String[] ars = pointId.split(StringUtils.COMMA);
//                        if (StringUtils.isNotEmpty(ars[0])) {
//                            brr.setDeviceName(ars[0]);
//                        }
//
//                        if (ars.length > 1 && StringUtils.isNotEmpty(ars[1])) {
//                            brr.setMaterialId(ars[1]);
//                        }
//                    }
//                }

                if (StringUtils.isNotEmpty(brr.getResultType())) {
                    if (brr.getResultType().equals("0")) {
                        brr.setAlarmType("1");
                        Map<String, String> stringStringMap = resultAnalysisService.selectPointInfoById(brr.getDeviceId());
                        if (stringStringMap != null) {
                            if (StringUtils.isNotEmpty(stringStringMap.get("point_impt_level"))) {
                                if (stringStringMap.get("point_impt_level").equals("Ⅰ")) {
                                    brr.setAlarmLevel("EMERGENCY");
                                } else if (stringStringMap.get("point_impt_level").equals("Ⅱ")) {
                                    brr.setAlarmLevel("SERIOUS");
                                } else {
                                    brr.setAlarmLevel("TEPID");
                                }
                            } else {
                                brr.setAlarmLevel("TEPID");
                            }
                        } else {
                            brr.setAlarmLevel("TEPID");
                        }
                    } else {
                        brr.setAlarmLevel("NORMAL");
                    }
                }

//                if (StringUtils.isNotEmpty(brr.getDeviceId())) {
//                    String pointId = brr.getDeviceId();
//                    List<Map<String, Object>> pointPrelist = this.patrolTaskService.selectBasePointPre(pointId);
//                    if (pointPrelist != null && !pointPrelist.isEmpty()) {
//                        Map<String, Object> drr = (Map) pointPrelist.get(0);
//                        if (drr != null && drr.get("channel_code") != null) {
//                            String channel_code = (String) drr.get("channel_code");
//                            brr.setPatroldeviceCode(channel_code);
//                            BasedataEqpBookChannel basedataEqpBookChannel = this.patrolResultService.selectChannelName(channel_code);
//                            if (basedataEqpBookChannel != null) {
//                                brr.setPatroldeviceName(basedataEqpBookChannel.getChannelName());
//                            }
//                        }
//                    }
//                }
            }
        }
        List<InspectionPointResultVo> filteredList = new ArrayList<>();
        for (InspectionPointResultVo brr : inspectionPointResultVo) {
            boolean flag = true;
            if ((inspectionPointParam.getAlarmLevel() != null && !inspectionPointParam.getAlarmLevel().equals(brr.getAlarmLevel()))) {
                flag = false;
            }
            if ((inspectionPointParam.getAlarmType() != null && !inspectionPointParam.getAlarmType().equals(brr.getAlarmType()))) {
                flag = false;
            }
            if ((inspectionPointParam.getPatroldeviceCode() != null && !inspectionPointParam.getPatroldeviceCode().equals(brr.getPatroldeviceCode()))) {
                flag = false;
            }
            if (flag) {
                filteredList.add(brr);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", inspectionPointResultVo.size());
        map.put("rows", filteredList);

        return AjaxResult.success(map);
    }

    public String recursionGetNameId(String devId) {
        String str = "";
        Map<String, Object> basedataDevice = this.patrolResultService.selectDevInfoById(devId);
        if (null != basedataDevice && null != basedataDevice.get("parent_id")) {
            if (basedataDevice.get("power_main_equ_flag").equals("Yes")) {
                return basedataDevice.get("device_name") + "," + basedataDevice.get("phyasset_id");
            }

            devId = basedataDevice.get("parent_id") + "";
            str = this.recursionGetNameId(devId);
        }

        return str;
    }

    public static void main(String[] args) {

        double runProgress = 0.0;
        double dbProgress = 0.0;
        //String input = "100%";
        String input = "3.0";
        String input2 = input.replaceAll("[^0-9.]", "");
        try {
            runProgress = Double.parseDouble(input2);
        } catch (Exception e) {

        }

        System.out.println("runProgress:" + runProgress);
    }

}
