package com.inspect.analysis.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspect.analysis.constant.AnalyseConstants;
import com.inspect.analysis.domain.*;
import com.inspect.analysis.service.IAnalyseLogService;
import com.inspect.analysis.service.IAnalyseResponseService;
import com.inspect.analysis.service.IResultAnalysisService;
import com.inspect.analysis.utils.ResultAnalysisUtils;
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.constant.Tags;
import com.inspect.base.core.enums.TaskStatus;
import com.inspect.base.core.utils.BigDecimalUtil;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.redis.service.RedisService;
import com.inspect.common.security.utils.DictUtils;
import com.inspect.message.MessageUtils;
import com.inspect.partrolresult.domain.AnalyseRequest;
import com.inspect.partrolresult.domain.PatrolResult;
import com.inspect.partrolresult.service.DelayQueueService;
import com.inspect.partrolresult.service.IAnalyseRequestService;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.resultmain.domain.PatrolTaskResultMain;
import com.inspect.resultmain.service.IPatrolTaskResultMainService;
import com.inspect.system.base.domain.SysDictData;
import com.inspect.taskinfo.domain.PatrolTaskInfo;
import com.inspect.taskinfo.service.IPatrolTaskInfoService;
import com.inspect.taskstatus.domain.PatrolTaskStatus;
import com.inspect.taskstatus.service.IPatrolTaskStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AnalyseResponseServiceImpl implements IAnalyseResponseService {

    @Resource
    private RedisService redisService;

    @Resource
    private IAnalyseRequestService analyseRequestService;

    @Resource
    private IAnalyseLogService analysisLogService;

    @Resource
    private IResultAnalysisService resultAnalysisService;

    @Resource
    private IPatrolResultService patrolResultService;

    @Resource
    private IPatrolTaskResultMainService patrolTaskResultMainService;

    @Resource
    private IPatrolTaskStatusService patrolTaskStatusService;

    @Resource
    private IPatrolTaskInfoService patrolTaskInfoService;

    @Resource
    private MessageUtils messageUtils;

    @Resource
    private ResultAnalysisUtils resultAnalysisUtils;

    @Resource
    private DelayQueueService<String> delayQueueService;

    @Override
    public void picAnalyseRetNotify(AnalyseResult analyseResult) {
        log.info("RESULT_TO_ALGORITHM_RESPONSE_QUEUE: patrolPointId: {}, isCompensate: {}, requestId: {}, RESULT: {}",
                analyseResult.getTaskPatrolId(),
                analyseResult.isCompensate(),
                analyseResult.getRequestId(),
                analyseResult
        );
        redisService.redisTemplate.opsForList().rightPush(
                AnalyseConstants.ALGORITHM_RESPONSE_QUEUE,
                new Gson().toJson(analyseResult)
        );
    }

    synchronized public void handleAlgorithmResult(final AnalyseResult analyseResult) throws IOException {
        //String logLabel = UUID.randomUUID().toString().trim().replaceAll(StringUtils.DASH, StringUtils.EMPTY);
        String requestId = analyseResult.getRequestId();
        log.info(Color.GREEN + "HANDLE_ALGORITHM_RESULT_S patrolPointId: {}, filter: {}, requestId: {}, analyseResult:{}" + Color.END,
                analyseResult.getTaskPatrolId(),
                analyseResult.getFilter(),
                requestId,
                analyseResult);

//        {
//            String value = analyseResult.getResultList().get(0).getResults().get(0).getValue();
//            log.info("testing value: {}", value);
//            ObjectMapper mapper = new ObjectMapper();
//            List<List<Double>> list;
//            try {
//                list = mapper.readValue(value, new TypeReference<List<List<Double>>>() {
//                });
//                log.info("testing size: {}, list: {}", list.size(), list);
//            } catch (Exception e) {
//                log.info("testing list exception: {}", e.getMessage());
//            }
//        }

        String keyId = AnalyseConstants.ANALYSE_REQUEST_ID.concat(requestId);
        if (!redisService.hasKey(keyId)) {
            log.error("ALGO_RES_UUID: {}, picAnalyseRetNotify isTest: {}, NO keyId={}, REQUEST_ID={} in REDIS!", requestId, analyseResult.isTest(), keyId, requestId);
            if (!analyseResult.isTest()) {
                return;
            }
            //redisService.setCacheObject(keyId, "123456789");
        } else {
            log.info("ANALYSE_REQUEST_ID: DEL {} FROM REDIS!", keyId);
            //redisService.deleteObject(keyId);
        }

        String patrolTaskIdObj = redisService.getCacheObject(keyId);
        log.info("ALGO_RES_UUID: {}, picAnalyseRetNotify keyId={}, requestId={}, patrolTaskIdObj={}", requestId, keyId, requestId, patrolTaskIdObj);
        analyseResult.setTaskPatrolId(patrolTaskIdObj);
        final String filterRequestRedisKey = AnalyseConstants.ANALYSE_FILTER_REQUEST + requestId;
        final String bigModelRequestRedisKey = AnalyseConstants.ANALYSE_AI_REQUEST + requestId;
        log.info("ALGO_RES_UUID: {}, picAnalyseRetNotify filterRequestRedisKey={}, bigModelRequestRedisKey={}", requestId, filterRequestRedisKey, bigModelRequestRedisKey);
        boolean bBigModelExecFlag = false;
        String[] algTypeList = {};
        AnalyseRequest analyseRequest = null;
        if (redisService.hasKey(filterRequestRedisKey)) { // 初筛结果
            analyseResult.setFilter("1"); // 设置初筛标志
            analyseRequest = (AnalyseRequest) redisService.redisTemplate.opsForValue().getAndDelete(filterRequestRedisKey);
            if (analyseRequest != null && analyseRequest.getObjectList() != null && !analyseRequest.getObjectList().isEmpty()) {
                log.info("ALGORITHM_FILTER_RESULT taskPatrolId: {}, requestId: {}, DATA IN REDIS: {}",
                        analyseRequest.getTaskPatrolId(),
                        requestId,
                        analyseRequest);
                if (delayQueueService.containRequest(AnalyseConstants.ALGORITHM_REQUEST_DELAY_QUEUE, analyseRequest.getRequestId())) {
                    boolean isRemoved = delayQueueService.removeRequest(AnalyseConstants.ALGORITHM_REQUEST_DELAY_QUEUE, analyseRequest.getRequestId());
                    log.info("ALGORITHM_FILTER_RESULT Redisson Removed requestId: {}, Result: {}, analyseRequest: {}", requestId, isRemoved ? "success" : "fail", analyseRequest);
                } else {
                    log.info("ALGORITHM_FILTER_RESULT Redisson has Compensated requestId: {}, analyseRequest: {}", requestId, analyseRequest);
                }

                algTypeList = analyseRequest.getObjectList().get(0).getTypeList();
                analyseResult.reloadReq(analyseRequest);//只有一个,analyseReq.getObjectList().get(0)
                log.info("ALGORITHM_FILTER_RESULT RELOAD requestId: {},  algTypeList: {}, analyseResult: {}",
                        requestId,
                        algTypeList,
                        analyseResult);
            }

            /*
             *大致两种情况：1. 算法是表计(meter); 2. 算法不是表计(meter)
             * 1. 算法不是表计(meter)
             * 1.1 初筛结果有缺陷：继续发给大模型处理
             * 1.2 初筛结果无缺陷：不用调用大模型，流程就此结束
             * 2. 算法是表计(meter)
             * 不论初筛结果有没有缺陷，都要继续调用大模型，因为大模型调用了表计(meter)识别算法
             */
            AnalyseResPoint analyseResPoint = analyseResult.getResultList().get(0).getResults().get(0);
            boolean bDefect = analyseResPoint.isDefect(); // code=2000代表初筛结果返回正常，value=1代表有缺陷

            final String algType = analyseRequest.getObjectList().get(0).getTypeList()[0];
            log.info("ALGORITHM_FILTER_RESULT CHECK DEFECT requestId: {}, bDefect: {}, algType: {}, algTypeInRedis: {}",
                    requestId,
                    bDefect,
                    analyseResPoint.getType(),
                    algType);
            if (algType.equals("filter")) {
                log.info("**************配置初筛算法，不走大模型*****************");
                bDefect = false;
            }
            if (bDefect || AlgConstants.BIG_MODEL_ALG_LIST.contains(algType)) {
                /*
                 * 先检查结果有缺无缺陷，如果有缺陷不用判断算法直接调用大模型；*
                 * 如果无缺陷，再去判断算法，如果算法是meter, infrared就继续调用大模型。*
                 */
                analyseResult.setResult("0");
                bBigModelExecFlag = true;
//                log.info("picAnalyseRetNotify CALL BIG_MODEL REQUEST_ID={}", requestId);
//                ispAlgorithmRequestService.sendRequest(analyseRequest);
            } else {
                //初筛结果无缺陷并且非表计算法，不用调用大模型，流程就此结束
                log.info("ALGORITHM_FILTER_RESULT CALL_NO_BIG_MODEL requestId: {}", requestId);
            }
        } else if (redisService.hasKey(bigModelRequestRedisKey)) { // 大模型结果
            analyseRequest = (AnalyseRequest) redisService.redisTemplate.opsForValue().getAndDelete(bigModelRequestRedisKey);
            if (analyseRequest != null) {
                analyseResult.reloadReq(analyseRequest);
                log.info("ALGORITHM_BIG_MODEL_RESULT taskPatrolId: {}, requestId: {}, DATA IN REDIS: {}, reloadResult: {}",
                        analyseRequest.getTaskPatrolId(),
                        requestId,
                        analyseRequest,
                        analyseResult);

                // 发给光明大模型处理
                redisService.redisTemplate.opsForList().rightPush(
                        AnalyseConstants.LUMINOSITY_REQUEST_QUEUE,
                        new Gson().toJson(analyseRequest)
                );
            }

            analyseResult.setFilter("0"); // 设置大模型标志为0
        } else {
            log.info("ALGORITHM_UNKNOWN_RESULT taskPatrolId: {}, requestId: {}, result: {}",
                    analyseResult.getTaskPatrolId(),
                    requestId,
                    analyseResult);
            return;
        }

        //qinyl
        try {
            final String objectId = analyseResult.getResultsList() != null && !analyseResult.getResultsList().isEmpty()
                    ? analyseResult.getResultsList().get(0).getObjectId() : "00000000";
            analysisLogService.log(new AnalyseLog(analyseResult.toString(),
                    analyseResult.isCompensate() ? AnalyseConstants.ANALYSE_LOG_TYPE_TIMEOUT : AnalyseConstants.ANALYSE_LOG_TYPE_RECV,
                    analyseResult.getTaskPatrolId(),
                    analyseResult.getFilter(),
                    requestId,
                    objectId,
                    StringUtils.EMPTY));
            repositAnalyseAlgorithmResult(analyseResult);
        } catch (Exception e) {
            log.error("error", e);
        }
        //doAlgorithmAnalysis(analyseResult);
        //calculateProcess(analyseResult);
        //log.info(Color.CYAN + "ALGO_RES_UUID: {}, ###### 分析算法模块返回的表计识别结果 end ######" + Color.END, requestId);

        if (bBigModelExecFlag) {
            log.info("ALGORITHM_RESULT CALL_BIG_MODEL , taskPatrolId: {}, requestId: {}", analyseResult.getTaskPatrolId(), requestId);
            try {
                analyseRequest.setFilter(false);
                analyseRequestService.sendRequest(analyseRequest, algTypeList, Boolean.FALSE);
            } catch (IOException e) {
                log.info("ALGORITHM_RESULT BIG_MODEL_CALL Exception requestId: {}, Msg: {}", requestId, e.getMessage());
                throw e;
            }
        }

        log.info(Color.GREEN + "HANDLE_ALGORITHM_RESULT_E patrolPointId: {}, requestId: {}" + Color.END,
                analyseResult.getTaskPatrolId(),
                requestId);
    }


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

        List<AnalyseResItem> resContentList = analyseResult.getResultList();
        Map<String, PatrolResult> resMap = selectObj2PatrolResultMap(analyseResult.getTaskPatrolId());
        log.info(Color.GREEN + "doAlgorithmAnalysis meter algorithm resContentList: {}" + Color.END, resContentList);
        log.info(Color.GREEN + "doAlgorithmAnalysis meter algorithm resMap: {}" + Color.END, JSONObject.toJSONString(resMap));
        try {
            if (!resContentList.isEmpty()) {
                List<WebsocketData> websocketDataArrayList = new ArrayList<>();
                for (AnalyseResItem algorithmResult : resContentList) {
                    Long lineId = deviceIdLineIdMap.get(algorithmResult.getObjectId());
                    log.info("doAlgorithmAnalysis resultList lineId: {}, objectId: {}", lineId, algorithmResult.getObjectId());
                    ResultAnalysis resultAnalysis = new ResultAnalysis();
                    resultAnalysis.setBusinessId(String.valueOf(lineId));
                    resultAnalysis.setResultContent(new Gson().toJson(analyseResult));
                    resultAnalysis.setResultType("1");
                    resultAnalysis.setObjectId(algorithmResult.getObjectId());
                    List<AnalyseResPoint> resultsList = algorithmResult.getResults();
                    String value = "";
                    List<String> typeList = new ArrayList<>();
                    String description;
                    String objectId;
                    for (Iterator<AnalyseResPoint> iterator = resultsList.iterator(); iterator.hasNext(); resultAnalysis.setDescription(description)) {
                        AnalyseResPoint algorithmInnerResult = iterator.next();
                        value = algorithmInnerResult.getValue();
                        String code = algorithmInnerResult.getCode();
                        description = algorithmInnerResult.getDesc();
                        objectId = algorithmInnerResult.getType();
                        if (StringUtils.isNotEmpty(objectId)) {
                            typeList.add(objectId);
                        }

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

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

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

                        resultAnalysis.setTaskPatrolId(analyseResult.getTaskPatrolId());
                        resultAnalysis.setRequestId(analyseResult.getRequestId());
                        resultAnalysis.setAlgType(algorithmInnerResult.getType());
                        resultAnalysis.setResValue(algorithmInnerResult.getValue());
                        resultAnalysis.setResCode(algorithmInnerResult.getCode());
                        resultAnalysis.setResConf(algorithmInnerResult.getConf());
                        resultAnalysis.setResDesc(algorithmInnerResult.getDesc());
                        resultAnalysis.setResult(analyseResult.getResult());
                        if (StringUtils.isEmpty(algorithmInnerResult.getResImageUrl())) {
                            PatrolResult patrolResult = resMap.get(algorithmResult.getObjectId());
                            log.info(Color.GREEN + "------------------------doAlgorithmAnalysis patrolResult: {}" + Color.END, JSONObject.toJSONString(patrolResult));
                            resultAnalysis.setResImgUrl(patrolResult.getFilePath());
                        } else {
                            resultAnalysis.setResImgUrl(algorithmInnerResult.getResImageUrl());
                        }
                        resultAnalysis.setImageNormalUrlPath(algorithmInnerResult.getImageNormalUrlPath());
                        resultAnalysis.setResPos(algorithmInnerResult.getPos() == null ? StringUtils.EMPTY : JSONObject.toJSONString(algorithmInnerResult.getPos()));
                        resultAnalysis.setFilter(analyseResult.getFilter());
                    }

                    log.info("doAlgorithmAnalysis BEFORE resultAnalysis: {}", resultAnalysis);
                    try {
                        setAllStatus(resultAnalysis);
                    } catch (Exception e) {
                        log.error("error", e);
                    }

                    log.info("doAlgorithmAnalysis AFTER resultAnalysis: {}", resultAnalysis);
                    if (StringUtils.isNotEmpty(resultAnalysis.getBusinessId())) {
                        ResultAnalysis analysis = new ResultAnalysis();
                        analysis.setBusinessId(resultAnalysis.getBusinessId());
                        analysis.setFilter(resultAnalysis.getFilter());
                        analysis.setAlgType(resultAnalysis.getAlgType());
                        log.info("doAlgorithmAnalysis selectResultAnalysisList analysis: {}", analysis);
                        List<ResultAnalysis> resultAnalyses = resultAnalysisService.selectResultAnalysisList(analysis);
                        if (resultAnalyses.isEmpty()) {
                            int analysisRes = resultAnalysisService.insertResultAnalysis(resultAnalysis);
                            log.info(Color.GREEN + "doAlgorithmAnalysis CRUD insert analysisRes: {}, lineId: {}" + Color.END, analysisRes, resultAnalysis.getLineId());
                        } else {
                            resultAnalysis.setLineId(resultAnalyses.get(0).getLineId());
                            int analysisRes = resultAnalysisService.updateResultAnalysis(resultAnalysis);
                            log.info(Color.GREEN + "doAlgorithmAnalysis CRUD update analysisRes: {}, lineId: {}" + Color.END, analysisRes, resultAnalysis.getLineId());
                        }
                    }

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

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

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

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

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

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

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

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

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

                if (point.size() == size) {
                    boolean bRes = redisService.deleteObject(requestId);
                    log.info("doAlgorithmAnalysis CLEAR requestId FROM REDIS: {}", bRes);
                }
            }
        } catch (Exception e) {
            log.error("error", e);
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    private void calculateProcess(AnalyseResult analyseResult) {
        try {
            String requestId = analyseResult.getRequestId();
            String taskPatrolId = analyseResult.getTaskPatrolId();
            String requestSetKey = AnalyseConstants.ANALYSE_REQUEST_ALG + requestId;
            String taskSetKey = AnalyseConstants.ANALYSE_TASK_REQUEST + taskPatrolId;
            if ("0".equals(analyseResult.getFilter())) {
                analyseResult.getResultList().forEach((item) -> {
                    for (AnalyseResPoint result : item.getResults()) {
                        redisService.redisTemplate.opsForSet().remove(
                                requestSetKey,
                                result.toResultValue(item.getObjectId())
                        );
                    }

                });
            }

            if (!redisService.hasKey(requestSetKey)) {
                redisService.redisTemplate.opsForSet().remove(taskSetKey, requestId);
                redisService.deleteObject(AnalyseConstants.ANALYSE_REQUEST_ID.concat(requestId));
            }

            if (!this.redisService.hasKey(taskSetKey)) {
                PatrolTaskStatus taskStatus = new PatrolTaskStatus();
                taskStatus.setTaskPatrolledId(taskPatrolId);
                taskStatus = patrolTaskStatusService.selectPatrolTaskStatusList(taskStatus).get(0);
                if (AnalyseConstants.TASK_PROGRESS_WAITING.equals(taskStatus.getTaskProgress())) {
                    taskStatus.setTaskProgress(AnalyseConstants.TASK_PROGRESS_OK);
                    taskStatus.setTaskState("1");
                    taskStatus.setTaskEstimatedTime(DateUtil.formatDateTime(new Date()));
                    taskStatus.setEndTime(DateUtil.formatDateTime(new Date()));
                    patrolTaskStatusService.updatePatrolTaskStatus(taskStatus);
                    //patrolResultController.senWebsocket(taskStatus);
                    log.info("picAnalyseRetNotify TASK FINISH taskPatrolId: {}", taskPatrolId);
                }
            }
        } catch (Exception e) {
            log.error("error", e);
        }

    }

    private Map<String, PatrolResult> selectObj2PatrolResultMap(String patrolTaskId) {
        PatrolTaskResultMain resultMain =
                patrolTaskResultMainService.selectPatrolTaskResultMainList(new PatrolTaskResultMain(patrolTaskId)).get(0);
        List<PatrolResult> results =
                patrolResultService.selectPatrolResultList(new PatrolResult(String.valueOf(resultMain.getLineId())));
        Map<String, PatrolResult> resMap = new HashMap<>();
        results.forEach((item) -> {
            resMap.put(item.getDeviceId(), item);
        });
        return resMap;
    }

    private Map<String, PatrolResult> selectObj2PatrolResultMap(String filter, String patrolTaskId, String deviceId) {
        log.info("OBJ_TO_PATROL_RESULT_S taskPatrolId: {}, filter: {}, deviceId: {}", patrolTaskId, filter, deviceId);
        PatrolTaskResultMain resultMain = patrolTaskResultMainService.selectPatrolTaskResultMainOne(patrolTaskId);
        PatrolResult patrolResult = new PatrolResult();
        patrolResult.setMainId(String.valueOf(resultMain.getLineId()));
        patrolResult.setDeviceId(deviceId);
        List<PatrolResult> patrolResultList =
                patrolResultService.selectPatrolResultList(patrolResult);
        Map<String, PatrolResult> resultMap = new HashMap<>();
        patrolResultList.forEach((item) -> resultMap.put(item.getDeviceId(), item));
        log.info("OBJ_TO_PATROL_RESULT_E taskPatrolId: {}, deviceId: {}, resultMap: {}", patrolTaskId, deviceId, resultMap);
        return resultMap;
    }

    public void repositAnalyseAlgorithmResult(AnalyseResult analyseResult) {
        List<WebsocketData> websocketDataList = new ArrayList<>();
        //Map<String, PatrolResult> resultMap = selectObj2PatrolResultMap(analyseResult.getTaskPatrolId());
        List<AnalyseResItem> resultList = analyseResult.getResultList();

        PatrolResult patrolResult = new PatrolResult();
        for (Iterator<AnalyseResItem> iterator = resultList.iterator(); iterator.hasNext(); patrolResultService.updatePatrolResult(patrolResult)) {
            AnalyseResItem resItem = iterator.next();
            Map<String, PatrolResult> resultMap =
                    selectObj2PatrolResultMap(analyseResult.getFilter(), analyseResult.getTaskPatrolId(), resItem.getObjectId());
            if (!resultMap.isEmpty()) {
                patrolResult = resultMap.get(resItem.getObjectId());
                List<ResultAnalysis> resultAnalysisList = new ArrayList<>();
                StringJoiner valueJoiner = new StringJoiner(StringUtils.COMMA);
                StringJoiner validJoiner = new StringJoiner(StringUtils.COMMA);

                List<AnalyseResPoint> analyseResPointList = resItem.getResults();
                if (!resItem.getResults().isEmpty()) {
                    AnalyseResPoint analyseResPoint = resItem.getResults().get(0);
                    String algType = analyseResPoint.getType();
                    log.info("RESULT_MERGE algType: {}, analyseResPoint: {}", algType, analyseResPoint);
                    if ("switch".equals(algType)) {
                        analyseResPointList = mergeAnalyseResItem(analyseResPointList);
                        log.info("RESULT_MERGE algType: {}, analyseResPointList: {}", algType, analyseResPointList);
                    }
                }

                for (AnalyseResPoint analyseResPoint : analyseResPointList) {
                    ResultAnalysis resultAnalysis = combineAnalyse(analyseResult,
                            String.valueOf(patrolResult.getLineId()),
                            resItem.getObjectId(),
                            patrolResult.getFilePath(),
                            analyseResPoint);
                    if (StringUtils.isEmpty(resultAnalysis.getAlgType()) || resultAnalysis.getAlgType().contains(",")) {
                        // 兼容算法结果传过来多个算法
                        continue;
                    }

                    // 红外算法保留一位小数，其他可读数算法增加读数单位
                    String resValue = resultAnalysisUtils.addUnit2Value(resultAnalysis.getResValue(), resultAnalysis.getAlgType(), patrolResult.getUnit());
                    resultAnalysis.setResValue(resValue);

                    resultAnalysisList.add(resultAnalysis);
                    valueJoiner.add(resultAnalysis.getResValue());
                    String pointStatus = resultAnalysis.getPointStatus();
                    String resultType = resultAnalysis.getResultType();
                    String resStatus = resultAnalysis.getResStatus();
                    // resultType:0-告警 1-正常 2-异常
                    if ("0".equals(resultType)) {
                        // 判别异常
                        validJoiner.add("2");
                    } else if ("1".equals(resultType)) {
                        // 成功
                        validJoiner.add("1");
                    } else if ("2".equals(resultType)) {
                        // 失败
                        validJoiner.add("0");
                    }
                    log.info(Color.GREEN + "[analysis] createTime: {}, insertResultAnalysis: {}" + Color.END, resultAnalysis.getCreateTime(), resultAnalysis);
                    try {
                        resultAnalysisService.insertResultAnalysis(resultAnalysis);
                    } catch (Exception e) {
                        log.error("error", e);
                    }
                }

                patrolResult.setValue(valueJoiner.toString());
                patrolResult.setValid(validJoiner.toString());
                List<SysDictData> algAliasList = DictUtils.getDictCache(Tags.DEFECT_TYPE);
                JSONObject algAliasMap = new JSONObject();
                Objects.requireNonNull(algAliasList).stream().filter((item) -> {
                    return !StringUtils.isEmpty(item.getRemark());
                }).forEach((item) -> {
                    algAliasMap.put(item.getDictValue(), item.getRemark());
                });
                String algType = resultAnalysisList.stream().map((item) -> {
                    return algAliasMap.containsKey(item.getAlgType()) ? algAliasMap.getString(item.getAlgType()) : item.getAlgType();
                }).collect(Collectors.joining(StringUtils.COMMA));
                patrolResult.setRecognitionType(algType);
                long alarmCount = resultAnalysisList.stream().filter((item) -> {
                    return "1".equals(item.getResultType());
                }).count();
                if (alarmCount > 0L) {
                    patrolResult.setValueUnit(messageUtils.get("有缺陷"));
                    websocketDataList.add(new WebsocketData(resItem.getObjectId(), patrolResult.getValueUnit()));
                } else {
                    patrolResult.setValueUnit(messageUtils.get("无缺陷"));
                }
            } else {
                log.info("OBJ_TO_PATROL_RESULT_ERROR taskPatrolId: {}, filter: {}, deviceId: {}", analyseResult.getTaskPatrolId(), analyseResult.getFilter(), resItem.getObjectId());
            }
        }

        // 计算初筛算法的进度
        log.info("BEFORE_FILTER_PROGRESS CALC filter: {}, totalNumber: {}, resultList: {}",
                analyseResult.getFilter(),
                analyseResult.getTotalNumber(),
                analyseResult.getResultList());
        if ("1".equals(analyseResult.getFilter()) && !analyseResult.getResultList().isEmpty()) {
            final String objectId = analyseResult.getResultList().get(0).getObjectId();
            calcRemoteAlgorithmProgress(analyseResult.getTaskPatrolId(), objectId, analyseResult.getTotalNumber());
        }

        //this.senWebsocket(websocketDataList);
    }

    private ResultAnalysis combineAnalyse(
            AnalyseResult analyseResult,
            String patrolResultId,
            String objectId,
            String filePath,
            AnalyseResPoint analyseResPoint) {
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setTaskPatrolId(analyseResult.getTaskPatrolId());
        resultAnalysis.setRequestId(analyseResult.getRequestId());
        resultAnalysis.setBusinessId(patrolResultId);
        resultAnalysis.setResultContent(analyseResPoint.toString());
        resultAnalysis.setObjectId(objectId);
        resultAnalysis.setAlgType(analyseResPoint.getType());
        resultAnalysis.setResValue(analyseResPoint.getValue());
        resultAnalysis.setResCode(analyseResPoint.getCode());
        resultAnalysis.setResConf(analyseResPoint.getConf());
        resultAnalysis.setResDesc(analyseResPoint.getDesc());
        resultAnalysis.setResult(analyseResult.getResult());
        if (StringUtils.isEmpty(analyseResPoint.getResImageUrl())) {
            analyseResPoint.setResImageUrl(filePath);
        }

        if (StringUtils.isEmpty(analyseResPoint.getImageNormalUrlPath())) {
            analyseResPoint.setImageNormalUrlPath(analyseResPoint.getImageNormalUrlPath());
        }

        resultAnalysis.setResImgUrl(analyseResPoint.getResImageUrl());
        resultAnalysis.setImageNormalUrlPath(analyseResPoint.getImageNormalUrlPath());
        resultAnalysis.setResPos(analyseResPoint.getPos() == null ? StringUtils.EMPTY : JSONObject.toJSONString(analyseResPoint.getPos()));
        String value = analyseResPoint.getValue();
        resultAnalysis.setFilter(analyseResult.getFilter());
        // 处理正常结果、以及兼容处理无机人表计gis_meter2、纠偏correction的异常结果
        if (resultAnalysisUtils.checkCode(analyseResPoint.getCode(), analyseResPoint.getDesc(), resultAnalysis)
                || (AlgConstants.GIS_METER_2.equals(analyseResPoint.getType()))
                || (AlgConstants.CORRECTION.equals(analyseResPoint.getType()) && Arrays.asList("2001", "2002", "2003").contains(analyseResPoint.getCode()) )) {
            AlgValue algValue = selectAlgMap(objectId, analyseResPoint.getType());
            resultAnalysisUtils.parseAlg(analyseResPoint.getType(), algValue, value, analyseResPoint.getDesc(), resultAnalysis);
            // 合并辅助值字段
            // todo 等待避雷器表计记算法优化再放开
//            resultAnalysisUtils.mergeValue(analyseResPoint ,resultAnalysis);
        }

        return resultAnalysis;
    }

    private void calcRemoteAlgorithmProgress(final String taskPatrolledId, final String objectId, final int totalNumber) {
        log.info("CALC_REMOTE_ALGORITHM_PROGRESS taskPatrolId: {}, objectId: {}, totalNumber: {}", taskPatrolledId, objectId, totalNumber);
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setTaskPatrolId(taskPatrolledId);
        resultAnalysis.setFilter("1");
        List<ResultAnalysis> resultAnalysisList = resultAnalysisService.selectResultAnalysisList(resultAnalysis);
        String algorithmProgress = decimalFormatNum(resultAnalysisList.size(), totalNumber);
//        log.info(Color.GREEN + "calcRemoteAlgorithmProgress: curNumber: {}, totalNumer: {}, algorithmProgress: {}, taskPatrolledId: {}" + Color.END,
//                resultAnalysisList.size(), totalNumber, algorithmProgress, taskPatrolledId);

        PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
        patrolTaskStatus.setTaskPatrolledId(taskPatrolledId);
        List<PatrolTaskStatus> patrolTaskStatusList = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
        log.info("CALC_REMOTE_ALGORITHM_PROGRESS algorithmProgress： {}, patrolTaskStatusList size: {}", algorithmProgress, patrolTaskStatusList.size());
        if (!patrolTaskStatusList.isEmpty()) {
            patrolTaskStatus = patrolTaskStatusList.get(0);
            patrolTaskStatus.setTaskEstimatedTime(algorithmProgress);
            BigDecimal algorithmProgressBD = BigDecimalUtil.toBigDecimal(algorithmProgress);
            BigDecimal oneHundredBD = new BigDecimal(100);
            if (algorithmProgressBD.compareTo(oneHundredBD) == 0) {
                log.info(Color.GREEN + "DONE CALC_REMOTE_ALGORITHM_PROGRESS taskPatrolledId: {}, objectId: {}, curNumber: {}, totalNumer: {}, algorithmProgress: {}, db-taskProgress: {}" + Color.END,
                        taskPatrolledId,
                        objectId,
                        resultAnalysisList.size(),
                        totalNumber,
                        algorithmProgress,
                        patrolTaskStatus.getTaskProgress());
                BigDecimal taskProgressBD = BigDecimalUtil.toBigDecimal(patrolTaskStatus.getTaskProgress());
                if (taskProgressBD.compareTo(oneHundredBD) == 0) {
                    patrolTaskStatus.setTaskState(TaskStatus.DONE.getCode());
                }
                patrolTaskStatusService.updateTaskProgress(patrolTaskStatus.getLineId(), patrolTaskStatus.getTaskProgress(), patrolTaskStatus.getTaskEstimatedTime(), patrolTaskStatus.getTaskState());
            } else {
                log.info(Color.GREEN + "RUNNING CALC_REMOTE_ALGORITHM_PROGRESS taskPatrolledId: {}, objectId: {}, curNumber: {}, totalNumer: {}, algorithmProgress: {}, status: {}" + Color.END,
                        taskPatrolledId,
                        objectId,
                        resultAnalysisList.size(),
                        totalNumber,
                        algorithmProgress,
                        patrolTaskStatus.getTaskState());

                if (TaskStatus.RUNNING.getCode().equals(patrolTaskStatus.getTaskState())) {
                    patrolTaskStatus.setTaskState(TaskStatus.RUNNING.getCode());
                    patrolTaskStatusService.updateTaskProgress(patrolTaskStatus.getLineId(), patrolTaskStatus.getTaskProgress(), patrolTaskStatus.getTaskEstimatedTime(), patrolTaskStatus.getTaskState());
                }
            }
        }
    }

    private String decimalFormatNum(int current, int all) {
        if (all == 0) {
            return "0.0"; // 防止除以0
        }

        DecimalFormat nf = new DecimalFormat("0.0");
        nf.setMaximumIntegerDigits(3);
        float decimalFormatNum = (float) (current) / (float) all;
        if (decimalFormatNum > 1) {
            decimalFormatNum = 1;
        }
        return nf.format(decimalFormatNum * 100.0F);
    }

    private AlgValue selectAlgMap(String devId, String type) {
        AlgValue algValue = null;
        Map<String, String> map = this.resultAnalysisService.selectPointInfoById(devId);
        String alarmThreshold = map.get(AnalyseConstants.ANALYSE_ALARM_THRESHOLD);
        log.info("selectAlgMap patrolPointId: {}, type: {}, alarmThreshold: {}", devId, type, alarmThreshold);
        if (StringUtils.isNotBlank(alarmThreshold)) {
            try {
                JSONArray thresholdList = JSONArray.parseArray(alarmThreshold);
                for (int i = 0; i < thresholdList.size(); ++i) {
                    JSONObject threshold = thresholdList.getJSONObject(i);
                    if (StringUtils.isNotEmpty(type) && type.equals(threshold.getString(AnalyseConstants.ANALYSE_CODE))) {
                        log.info("selectAlgMap patrolPoint threshold: {}", JSONObject.toJSONString(threshold));
                        algValue = new AlgValue(threshold.getString(AnalyseConstants.ANALYSE_UPPER_VALUE), threshold.getString(AnalyseConstants.ANALYSE_LOWER_VALUE));
                    }
                }
            } catch (Exception e) {
                log.error("selectAlgMap Exception devId: {}, alarmThreshold: {}, Msg: {}", devId, alarmThreshold, e.getMessage());
            }
        }

        if (algValue == null) {
            Map<String, String> threshold = patrolResultService.selectPatrolPresetParam(devId);
            if (threshold != null) {
                log.info("selectAlgMap patrolPreset threshold: {}", JSONObject.toJSONString(threshold));
                try {
                    algValue = new AlgValue(threshold.get(AnalyseConstants.ANALYSE_MAX_TEMP), threshold.get(AnalyseConstants.ANALYSE_MIN_TEMP));
                } catch (Exception e) {
                    log.error("selectAlgMap Exception-2 Msg: {}", e.getMessage());
                }
            }
        }

        if (algValue == null) {
            log.info("selectAlgMap threshold is not set, devId: {}", devId);
            algValue = new AlgValue();
        }

        return algValue;
    }

    public static final String mergeString = "{\n" +
            "\t\"requestId\": \"b00f2fbd1fcc49c6a47ed2b3a77e5028\",\n" +
            "\t\"resultsList\": [{\n" +
            "\t\t\"objectId\": \"2079991\",\n" +
            "\t\t\"results\": [{\n" +
            "\t\t\t\"type\": \"switch\",\n" +
            "\t\t\t\"value\": \"和\",\n" +
            "\t\t\t\"code\": \"2000\",\n" +
            "\t\t\t\"resImageUrl\": \"2/2025/12/12/1531/CCD/3038_R100-001_20251212140756.jpg\",\n" +
            "\t\t\t\"pos\": [],\n" +
            "\t\t\t\"conf\": 0.99,\n" +
            "\t\t\t\"desc\": \"\",\n" +
            "\t\t\t\"imageNormalUrlPath\": \"1/2025/08/29/1584/CCD/3038_R100-001_20250829123953.jpg\"\n" +
            "\t\t}, {\n" +
            "\t\t\t\"type\": \"switch\",\n" +
            "\t\t\t\"value\": \"和\",\n" +
            "\t\t\t\"code\": \"2000\",\n" +
            "\t\t\t\"resImageUrl\": \"2/2025/12/12/1531/CCD/3038_R100-001_20251212140756.jpg\",\n" +
            "\t\t\t\"pos\": [],\n" +
            "\t\t\t\"conf\": 0.99,\n" +
            "\t\t\t\"desc\": \"\",\n" +
            "\t\t\t\"imageNormalUrlPath\": \"1/2025/08/29/1584/CCD/3038_R100-001_20250829123953.jpg\"\n" +
            "\t\t}, {\n" +
            "\t\t\t\"type\": \"switch\",\n" +
            "\t\t\t\"value\": \"分\",\n" +
            "\t\t\t\"code\": \"2000\",\n" +
            "\t\t\t\"resImageUrl\": \"2/2025/12/12/1531/CCD/3038_R100-001_20251212140756.jpg\",\n" +
            "\t\t\t\"pos\": [],\n" +
            "\t\t\t\"conf\": 0.99,\n" +
            "\t\t\t\"desc\": \"\",\n" +
            "\t\t\t\"imageNormalUrlPath\": \"1/2025/08/29/1584/CCD/3038_R100-001_20250829123953.jpg\"\n" +
            "\t\t}, {\n" +
            "\t\t\t\"type\": \"switch\",\n" +
            "\t\t\t\"value\": \"和\",\n" +
            "\t\t\t\"code\": \"2000\",\n" +
            "\t\t\t\"resImageUrl\": \"2/2025/12/12/1531/CCD/3038_R100-001_20251212140756.jpg\",\n" +
            "\t\t\t\"pos\": [],\n" +
            "\t\t\t\"conf\": 0.99,\n" +
            "\t\t\t\"desc\": \"\",\n" +
            "\t\t\t\"imageNormalUrlPath\": \"1/2025/08/29/1584/CCD/3038_R100-001_20250829123953.jpg\"\n" +
            "\t\t}, {\n" +
            "\t\t\t\"type\": \"switch\",\n" +
            "\t\t\t\"value\": \"分\",\n" +
            "\t\t\t\"code\": \"2000\",\n" +
            "\t\t\t\"resImageUrl\": \"2/2025/12/12/1531/CCD/3038_R100-001_20251212140756.jpg\",\n" +
            "\t\t\t\"pos\": [],\n" +
            "\t\t\t\"conf\": 0.99,\n" +
            "\t\t\t\"desc\": \"\",\n" +
            "\t\t\t\"imageNormalUrlPath\": \"1/2025/08/29/1584/CCD/3038_R100-001_20250829123953.jpg\"\n" +
            "\t\t}, {\n" +
            "\t\t\t\"type\": \"switch\",\n" +
            "\t\t\t\"value\": \"分\",\n" +
            "\t\t\t\"code\": \"2000\",\n" +
            "\t\t\t\"resImageUrl\": \"2/2025/12/12/1531/CCD/3038_R100-001_20251212140756.jpg\",\n" +
            "\t\t\t\"pos\": [],\n" +
            "\t\t\t\"conf\": 0.99,\n" +
            "\t\t\t\"desc\": \"\",\n" +
            "\t\t\t\"imageNormalUrlPath\": \"1/2025/08/29/1584/CCD/3038_R100-001_20250829123953.jpg\"\n" +
            "\t\t}],\n" +
            "\t\t\"algFactory\": \"yd\"\n" +
            "\t}]\n" +
            "}";

    public static List<AnalyseResPoint> mergeAnalyseResItem(List<AnalyseResPoint> analyseResPointList) {
        String mergedValue = analyseResPointList.stream()
                .map(AnalyseResPoint::getValue)
                .filter(Objects::nonNull)
                .collect(Collectors.joining(StringUtils.COMMA));
        AnalyseResPoint first = analyseResPointList.get(0);

        AnalyseResPoint mergedPoint = new AnalyseResPoint();
        mergedPoint.setType(first.getType());
        mergedPoint.setCode(first.getCode());
        mergedPoint.setResImageUrl(first.getResImageUrl());
        mergedPoint.setImageNormalUrlPath(first.getImageNormalUrlPath());
        mergedPoint.setConf(first.getConf());
        mergedPoint.setDesc(first.getDesc());
        mergedPoint.setPos(first.getPos());
        mergedPoint.setValue(mergedValue);

        return Collections.singletonList(mergedPoint);
    }
    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        AnalyseResult analyseResult;
        try {
            analyseResult = mapper.readValue(mergeString, new TypeReference<AnalyseResult>() {
            });
            log.info("mergeAnalyseResItem analyseResult: {}", analyseResult);
            List<AnalyseResPoint> result = mergeAnalyseResItem(analyseResult.getResultsList().get(0).getResults());
            log.info("mergeAnalyseResItem result: {}", result);
        } catch (Exception e) {
            log.error("mergeAnalyseResItem exception", e);
        }
    }

}
