package com.inspect.analysis.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.inspect.analysis.domain.*;
import com.inspect.analysis.service.IResultAnalysisService;
import com.inspect.base.core.constant.AlgConstants;
import com.inspect.base.core.domain.Response;
import com.inspect.base.core.enums.PointStatusEnum;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.PageDomain;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.base.core.web.page.TableSupport;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.fegin.FeignBasedataAreaService;
import com.inspect.message.MessageUtils;
import com.inspect.partrolresult.domain.AlgInfo;
import com.inspect.partrolresult.domain.PatrolResult;
import com.inspect.partrolresult.domain.PatrolResultRef;
import com.inspect.partrolresult.mapper.PatrolResultMapper;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.task.domain.PatrolData;
import com.inspect.task.service.IPatrolTaskService;

import com.inspect.taskinfo.domain.PatrolTaskInfo;
import com.inspect.taskinfo.service.IPatrolTaskInfoService;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.inspect.taskstatus.domain.PatrolTaskStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/analysis"})
public class ResultAnalysisController extends BaseController {
    private final IResultAnalysisService resultAnalysisService;
    private final IPatrolTaskService patrolTaskService;
    private final IPatrolTaskInfoService iPatrolTaskInfoService;
    private final IPatrolResultService patrolResultService;
    private final FeignBasedataAreaService feignBasedataAreaService;

    @Resource
    private MessageUtils messageUtils;

    @Resource
    private PatrolResultMapper patrolResultMapper;

    public ResultAnalysisController(IResultAnalysisService resultAnalysisService, IPatrolTaskService patrolTaskService, IPatrolTaskInfoService iPatrolTaskInfoService, IPatrolResultService patrolResultService, FeignBasedataAreaService feignBasedataAreaService) {
        this.resultAnalysisService = resultAnalysisService;
        this.patrolTaskService = patrolTaskService;
        this.iPatrolTaskInfoService = iPatrolTaskInfoService;
        this.patrolResultService = patrolResultService;
        this.feignBasedataAreaService = feignBasedataAreaService;
    }

    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;
    }

    @GetMapping({"/list"})
    public TableDataInfo list(PatrolResult patrolResult) {
        this.startPage();
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        if (StringUtils.isNotEmpty(patrolResult.getDefectType())) {
            resultAnalysis.setResultContent(patrolResult.getDefectType());
        }

        if (StringUtils.isNotEmpty(patrolResult.getBeginTime())) {
            resultAnalysis.setBeginTime(patrolResult.getBeginTime());
        }

        if (StringUtils.isNotEmpty(patrolResult.getEndTime())) {
            resultAnalysis.setEndTime(patrolResult.getEndTime());
        }

        if (StringUtils.isNotEmpty(patrolResult.getAreaId())) {
            resultAnalysis.setAreaId(patrolResult.getAreaId());
        }

        if (StringUtils.isNotEmpty(patrolResult.getMainDevId())) {
            resultAnalysis.setMainDevId(patrolResult.getMainDevId());
        }

        if (StringUtils.isNotEmpty(patrolResult.getAlarmType()) && patrolResult.getAlarmType().equals("1")) {
            resultAnalysis.setResultType("0");
        }

        if (StringUtils.isNotEmpty(patrolResult.getResStatus())) {
            resultAnalysis.setResStatus(patrolResult.getResStatus());
        }

        List<PatrolResult> patrolResultList = resultAnalysisService.selectResultAnd(resultAnalysis);
        if (!patrolResultList.isEmpty()) {
            for (PatrolResult brr : patrolResultList) {
                String pointId;
                if (StringUtils.isNotEmpty(brr.getComponentId()) && StringUtils.isEmpty(brr.getDeviceName())) {
                    pointId = this.recursionGetNameId(brr.getComponentId());
                    System.out.println(pointId);
                    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.getResStatus())) {
                    if (brr.getResStatus().equals("0")) {
                        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.setWarnLevel("EMERGENCY");
                                } else if (stringStringMap.get("point_impt_level").equals("Ⅱ")) {
                                    brr.setWarnLevel("SERIOUS");
                                } else {
                                    brr.setWarnLevel("TEPID");
                                }
                            } else {
                                brr.setWarnLevel("TEPID");
                            }
                        } else {
                            brr.setWarnLevel("TEPID");
                        }
                    } else {
                        brr.setWarnLevel("NORMAL");
                    }
                }

                List pointPrelist;
                if (StringUtils.isNotEmpty(brr.getResultContent())) {
                    JSONObject parseObject = JSONObject.parseObject(brr.getResultContent());
                    Object jsonArray = parseObject.get("resultList");
                    pointPrelist = JSONArray.parseArray(jsonArray + "", resultList.class);
                    if (pointPrelist != null && !pointPrelist.isEmpty()) {
                        resultList resultList = (resultList) pointPrelist.get(0);
                        if (resultList.getResults() != null && !resultList.getResults().isEmpty()) {
                            List<String> ss = resultList.getResults().stream().map(results::getType).collect(Collectors.toList());
                            List<String> aa = new ArrayList<>();
                            if (ss.size() > 1) {

                                for (String arr : ss) {
                                    if (StringUtils.isNotEmpty(arr)) {
                                        aa.add(arr);
                                    }
                                }

                                brr.setDefectType(StringUtils.join(aa, StringUtils.COMMA));
                            } else {
                                brr.setDefectType(StringUtils.join(ss, StringUtils.COMMA));
                            }

                            List<String> stringList = resultList.getResults().stream().map(results::getResImageUrl).filter((getResImageUrl) -> {
                                return !getResImageUrl.isEmpty();
                            }).collect(Collectors.toList());
                            if (!stringList.isEmpty()) {
                                brr.setVisible(stringList);
                            } else {
                                stringList.add(brr.getFilePath());
                                brr.setVisible(stringList);
                            }

                            brr.setVisible(stringList);
                            List<String> infraReda = new ArrayList<>();
                            List<String> audioa = new ArrayList<>();
                            List<String> videoa = new ArrayList<>();
                            List<String> photoa = new ArrayList<>();
                            brr.setInfraRed(infraReda);
                            brr.setAudio(audioa);
                            brr.setVideo(videoa);
                            brr.setPhoto(photoa);
                        }
                    }
                }

                if (StringUtils.isNotEmpty(brr.getDeviceId())) {
                    pointId = brr.getDeviceId();
                    List<Map<String, Object>> pointlist = this.patrolTaskService.selectBasePointByPointId(pointId);
                    if (pointlist != null && !pointlist.isEmpty()) {
                        Map<String, Object> crr = pointlist.get(0);
                        if (crr != null) {
                            String patrolPointName = (String) crr.get("patrolPointName");
                            brr.setPatrolPointName(patrolPointName);
                        }
                    }

                    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.setChannelCode(channel_code);
                        }
                    }
                }
            }
        }

        return this.getDataTable(patrolResultList);
    }

    @GetMapping({"/unexecuted"})
    public TableDataInfo unexecuted(PatrolResult patrolResult) {
        this.startPage();
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        if (StringUtils.isNotEmpty(patrolResult.getDefectType())) {
            resultAnalysis.setResultContent(patrolResult.getDefectType());
        }

        if (StringUtils.isNotEmpty(patrolResult.getBeginTime())) {
            resultAnalysis.setBeginTime(patrolResult.getBeginTime());
        }

        if (StringUtils.isNotEmpty(patrolResult.getEndTime())) {
            resultAnalysis.setEndTime(patrolResult.getEndTime());
        }

        if (StringUtils.isNotEmpty(patrolResult.getAlarmType()) && patrolResult.getAlarmType().equals("1")) {
            resultAnalysis.setResultType("0");
        }

        resultAnalysis.setResStatus("0");
        List<PatrolResult> patrolResultList = this.resultAnalysisService.selectResultAnd(resultAnalysis);
        if (!patrolResultList.isEmpty()) {
            for (PatrolResult brr : patrolResultList) {
                List<String> infraReda = new ArrayList<>();
                List<String> visiblea = new ArrayList<>();
                List<String> audioa = new ArrayList<>();
                List<String> videoa = new ArrayList<>();
                List<String> photoa = new ArrayList<>();
                if (brr.getFileType() != null && brr.getFilePath() != null) {
                    String[] type = brr.getFileType().split(StringUtils.COMMA);
                    String[] filepath = brr.getFilePath().split(StringUtils.COMMA);

                    for (int i = 0; i < type.length; ++i) {
                        if (type[i].equals("1")) {
                            infraReda.add(filepath[i]);
                        } else if (type[i].equals("2")) {
                            visiblea.add(filepath[i]);
                        } else if (type[i].equals("3")) {
                            audioa.add(filepath[i]);
                        } else if (type[i].equals("4")) {
                            videoa.add(filepath[i]);
                        } else if (type[i].equals("5")) {
                            photoa.add(filepath[i]);
                        }
                    }
                }

                brr.setInfraRed(infraReda);
                brr.setVisible(visiblea);
                brr.setAudio(audioa);
                brr.setVideo(videoa);
                brr.setPhoto(photoa);
                if (StringUtils.isNotEmpty(brr.getResultContent())) {
                    JSONObject parseObject = JSONObject.parseObject(brr.getResultContent());
                    Object jsonArray = parseObject.get("resultList");
                    List<resultList> resContentList = JSONArray.parseArray(jsonArray + "", resultList.class);
                    if (!resContentList.isEmpty()) {
                        resultList resultList = resContentList.get(0);
                        if (resultList.getResults() != null && !resultList.getResults().isEmpty() && StringUtils.isNotEmpty(((results) resultList.getResults().get(0)).getType())) {
                            brr.setDefectType(resultList.getResults().get(0).getType());
                        }
                    }
                }
            }
        }

        return this.getDataTable(patrolResultList);
    }

    @Log(
            title = "分析结果",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, ResultAnalysis resultAnalysis) {
        List<ResultAnalysis> list = this.resultAnalysisService.selectResultAnalysisList(resultAnalysis);
        ExcelUtil<ResultAnalysis> util = new ExcelUtil<>(ResultAnalysis.class);
        util.exportExcel(response, list, "分析结果数据");
    }

    @GetMapping({"/{lineId}"})
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId) {
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setLineId(lineId);
        List<PatrolResult> patrolResultList = this.resultAnalysisService.selectResultAnd(resultAnalysis);
        PatrolResult brr = patrolResultList.get(0);
        brr.setStatus(brr.getResStatus());
        brr.setSuggestion(brr.getSuggestion());
        List pointPrelist;
        if (StringUtils.isNotEmpty(brr.getResultContent())) {
            JSONObject parseObject = JSONObject.parseObject(brr.getResultContent());
            Object jsonArray = parseObject.get("resultList");
            pointPrelist = JSONArray.parseArray(jsonArray + "", resultList.class);
            if (!pointPrelist.isEmpty()) {
                resultList resultList = (resultList) pointPrelist.get(0);
                if (resultList.getResults() != null && !resultList.getResults().isEmpty()) {
                    if (StringUtils.isNotEmpty(resultList.getResults().get(0).getResImageUrl())) {
                        brr.setPhotoUrl(resultList.getResults().get(0).getResImageUrl());
                    }

                    if (StringUtils.isNotEmpty(resultList.getResults().get(0).getType())) {
                        brr.setDefectType(resultList.getResults().get(0).getType());
                    }

                    if (StringUtils.isNotEmpty(resultList.getResults().get(0).getDesc())) {
                        if ("meter normal".equals(resultList.getResults().get(0).getDesc())) {
                            brr.setDesc(brr.getDescription());
                        } else if ("out of range".equals(resultList.getResults().get(0).getDesc())) {
                            brr.setDesc(brr.getDescription());
                        } else {
                            brr.setDesc(resultList.getResults().get(0).getDesc());
                        }
                    }
                }
            }
        }

        if (StringUtils.isNotEmpty(brr.getDeviceId())) {
            String pointId = brr.getDeviceId();
            List<Map<String, Object>> pointlist = this.patrolTaskService.selectBasePointByPointId(pointId);
            if (pointlist != null && !pointlist.isEmpty()) {
                Map<String, Object> crr = pointlist.get(0);
                if (crr != null) {
                    String patrolPointName = (String) crr.get("patrolPointName");
                    brr.setPatrolPointName(patrolPointName);
                }
            }

            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.setChannelCode(channel_code);
                }
            }
        }

        return AjaxResult.success(brr);
    }

    @Log(
            title = "分析结果",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody ResultAnalysis resultAnalysis) {
        return this.toAjax(this.resultAnalysisService.insertResultAnalysis(resultAnalysis));
    }

    @Log(
            title = "分析结果",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody ResultAnalysis resultAnalysis) {
        return this.toAjax(this.resultAnalysisService.updateResultAnalysis(resultAnalysis));
    }

    @Log(
            title = "分析结果",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{lineIds}"})
    public AjaxResult remove(@PathVariable Long[] lineIds) {
        return this.toAjax(this.resultAnalysisService.deleteResultAnalysisByLineIds(lineIds));
    }

    @GetMapping({"/updateWarn"})
    public AjaxResult updateWarn(PatrolTaskInfo patrolTaskInfo) {
        List<String> algs = Arrays.asList("gis_meter2", "gis_meter", "infrared", "infra_1800", "infra_yu3", "infra_camera", "infra_camera_reverse", "switch", "meter");
        if (patrolTaskInfo.getLineIds() == null) {
            patrolTaskInfo.setLineIds(patrolTaskInfo.getLineId() + "");
        }
        // 初筛 忽略，不用改大模型状态  跟踪确认，初筛、大模型都改成跟踪确认
        // 初筛、大模型，改成跟踪确认忽略，初筛、大模型都改成跟踪确认忽略
        // 大模型，跟踪确认忽略，大模型都改成跟踪确认忽略
        logger.info("[ANALYSIS] lineIds: {}", patrolTaskInfo.getLineIds());
        String[] strs = patrolTaskInfo.getLineIds().split(StringUtils.COMMA);

        for (String str : strs) {
            ResultAnalysis resultAnalysis = new ResultAnalysis();
            resultAnalysis.setLineId(Long.valueOf(str));
            List<ResultAnalysis> resultAnalysisList = resultAnalysisService.selectResultAnalysisList(resultAnalysis);
            if (!resultAnalysisList.isEmpty()) {
                ResultAnalysis analysis = resultAnalysisList.get(0);
                // 初筛结果，跟踪确认，大模型的结果状态也要改为跟踪确认  初筛 meter，其余算法不覆盖
                if (strs.length == 1
                        && (PointStatusEnum.CONFIRMED.getCode().equals(patrolTaskInfo.getStatus())
                        || PointStatusEnum.TRACKING.getCode().equals(patrolTaskInfo.getStatus()))
                        && "1".equals(analysis.getFilter()) && !algs.contains(analysis.getAlgType())) {
                    // 初筛大模型都改  都覆盖
                    analysis.setLineId(null);
                    analysis.setDescription("缺陷");
                }
                logger.info("[ANALYSIS] lineId: {}", analysis.getLineId());
                // 告警确认状态 3-已撤销（忽略） 4-跟踪（告警） 5-确认 6-缺陷
                analysis.setPointStatus(patrolTaskInfo.getStatus());
                analysis.setSuggestion(patrolTaskInfo.getSuggestion());
                // meter初筛结果不变，大模型结果不变
                if (PointStatusEnum.CONFIRMED.getCode().equals(patrolTaskInfo.getStatus())) {
                    // 确认
                    analysis.setResultType("0");//缺陷
                } else if (PointStatusEnum.REVOKED.getCode().equals(patrolTaskInfo.getStatus())) {
                    // 忽略
                    analysis.setResultType("1");//结果正常
                    analysis.setDescription("忽略");
                } else if (PointStatusEnum.TRACKING.getCode().equals(patrolTaskInfo.getStatus())) {
                    // 跟踪
                    analysis.setResultType("0");//缺陷
                }
//                resultAnalysisService.updateResultAnalysis(analysis);
                resultAnalysisService.updateResultAnalysisByCondition(analysis);
            }
        }

        return this.toAjax(1);
    }

    @GetMapping({"/abnormal"})
    public TableDataInfo abnormal(PatrolTaskInfo patrolTaskInfo) {
        this.startPage();
        List<PatrolTaskInfo> list = this.iPatrolTaskInfoService.selectPatrolAbnormalTaskList(patrolTaskInfo);
        return this.getDataTable(list);
    }

    public static void main(String[] args) {
        String str = "1236";
        String[] strs = str.split(StringUtils.COMMA);
        System.out.println(strs[0]);
    }

    public void analysis(String str) {
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setResultContent(str);
        resultAnalysis.setCreateTime(new Date());
        resultAnalysis.setResStatus("0");
        resultAnalysis.setResultType("0");
        JSONObject parseObject = JSONObject.parseObject(str);
        Object jsonArray = parseObject.get("resultList");
        List<resultList> resContentList = JSONArray.parseArray(jsonArray + "", resultList.class);
        if (!resContentList.isEmpty()) {
            String objectId = resContentList.get(0).getObjectId();
            resultAnalysis.setObjectId(objectId);
            if ((resContentList.get(0)).getResults() != null && !(resContentList.get(0)).getResults().isEmpty()) {
                List<results> results = resContentList.get(0).getResults();
                String value = results.get(0).getValue();
                String code = results.get(0).getCode();
                String desc = results.get(0).getDesc();
                this.logger.info("======告警描述=======" + desc);
                if (desc.contains("normal")) {
                    desc = messageUtils.get("识别完成");
                }

                resultAnalysis.setDescription(desc);
                if (value.equals("0")) {
                    resultAnalysis.setPointStatus("1");
                } else if (value.equals("1")) {
                    resultAnalysis.setPointStatus("0");
                }

                if (!code.equals("2000")) {
                    resultAnalysis.setPointStatus("0");
                }

                if (StringUtils.isEmpty(results.get(0).getResImageUrl())) {
                    resultAnalysis.setPointStatus("2");
                }
            }
        }

        resultAnalysis.setResStatus("0");
        this.resultAnalysisService.insertResultAnalysis(resultAnalysis);
    }

    @GetMapping({"/test"})
    public AjaxResult test(String areaId) {
        return AjaxResult.success(this.ToStationIn(areaId));
    }

    public String ToStationIn(String areaId) {
        String dianyadengji = "";
        Map<String, Object> map = this.patrolResultService.selectAreaInfo(areaId);
        if (map != null) {
            String mapType = map.get("area_type") + "";
            if (StringUtils.isNotEmpty(mapType) && mapType.equals("station_in")) {
                dianyadengji = map.get("area_name") + "";
            } else {
                String ancestors = map.get("ancestors") + "";
                String[] ancestorsSplit = ancestors.split(StringUtils.COMMA);

                for (String s : ancestorsSplit) {
                    Map<String, Object> maps = this.patrolResultService.selectAreaInfo(s);
                    if (maps != null) {
                        String mapTypes = maps.get("area_type") + "";
                        if (StringUtils.isNotEmpty(mapTypes) && mapTypes.equals("station_in")) {
                            dianyadengji = maps.get("area_name") + "";
                        }
                    }
                }

                if (StringUtils.isEmpty(dianyadengji)) {
                    List<Map<String, Object>> parentMap = this.patrolResultService.selectAreaInfoByParentId(areaId);
                    if (parentMap != null) {
                        System.out.println(parentMap.size());
                        if (!parentMap.isEmpty()) {

                            for (Map<String, Object> stringObjectMap : parentMap) {
                                if (stringObjectMap != null) {
                                    String mapTypes = stringObjectMap.get("area_type") + "";
                                    if (StringUtils.isNotEmpty(mapTypes) && mapTypes.equals("station_in")) {
                                        dianyadengji = stringObjectMap.get("area_name") + "";
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return dianyadengji;
    }

    @GetMapping({"/list_v2"})
    public TableDataInfo listV2(PatrolTaskStatus patrolTaskStatus) {
        logger.info("[RES ANALYZE] listV2 param: {}", patrolTaskStatus);
//        if("1".equals(patrolTaskStatus.getFilter())) {
            ResultAnalysis resultAnalysis = new ResultAnalysis();
            resultAnalysis.setTaskPatrolId(patrolTaskStatus.getTaskPatrolledId());
            resultAnalysis.setFilter(patrolTaskStatus.getFilter());
//            resultAnalysis.setResCode("2000");
//            resultAnalysis.setPointStatus("0");
            resultAnalysis.setResultType("0"); // 0缺陷
            startPage();
            List<PatrolData> filterList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
//            logger.info("[RES ANALYZE] filterList1: {}", JSONObject.toJSONString(filterList, true));
            List<AlgInfo> algInfos = patrolResultService.selectAlgInfo(new PatrolResult());
            filterList.forEach((item) -> {
                item.setAlgName((algInfos.stream().anyMatch((alg) -> {
                    return alg.getAlgSubtypeCode().equals(item.getAlgType());
                }) ? algInfos.stream().filter((alg) -> {
                    return alg.getAlgSubtypeCode().equals(item.getAlgType());
                }).findFirst().get().getAlgSubtypeName() : ""));
                if ("1".equals(item.getFilter())) {
                    item.setImg(item.getImageNormalUrlPath());
                }
                if (StringUtils.isEmpty(item.getImageNormalUrlPath())) {
                    item.setImageNormalUrlPath(item.getFilePath());
                }
//                if ("0".equals(item.getFilter())) {
//                    List<PatrolData> filterDatas = filterList.stream().filter((data) -> {
//                        return data.getObjectId().equals(item.getObjectId()) && data.getAlgType().equals(data.getAlgType());
//                    }).collect(Collectors.toList());
//                    if (!filterDatas.isEmpty()) {
//                        logger.info("filterDatas: {}", filterDatas);
//                        item.setImg((filterDatas.get(0)).getImgAnalyse());
//                    } else {
//                        item.setImg("");
//                    }
//                } else {
//                    item.setImg(item.getImgAnalyse());
////                    item.setImgAnalyse("");
//                }
                AlgValue algValue = new AlgValue();
                if(item.getResValue() != null) {
                    String str = algValue.formatValue(item.getResValue());
                    if ("meter".equals(item.getAlgType())) {
                        if (str.equals("-1")) {
                            item.setResValue("空值");
                        }
                    }
                }
            });
//            logger.info("[RES ANALYZE] filterList2: {}", JSONObject.toJSONString(filterList, true));
            Collections.sort(filterList);
            return getDataTable(filterList);
//        } else if("0".equals(patrolTaskStatus.getFilter())) {
//            ResultAnalysis resultAnalysis = new ResultAnalysis();
//            resultAnalysis.setTaskPatrolId(patrolTaskStatus.getTaskPatrolledId());
//            resultAnalysis.setFilter("0");
//            List<PatrolData> filterList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
//            List<AlgInfo> algInfos = patrolResultService.selectAlgInfo(new PatrolResult());
//            startPage();
//            resultAnalysis.setResult("1");//大模型结果
//            resultAnalysis.setResultType("1");//结果正常
//            List<PatrolData> dataList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
//            dataList.forEach((item) -> {
//                item.setAlgName((algInfos.stream().anyMatch((alg) -> {
//                    return alg.getAlgSubtypeCode().equals(item.getAlgType());
//                }) ? algInfos.stream().filter((alg) -> {
//                    return alg.getAlgSubtypeCode().equals(item.getAlgType());
//                }).findFirst().get().getAlgSubtypeName() : ""));
//                if("0".equals(item.getFilter())) {
//                    List<PatrolData> filterDatas = filterList.stream().filter((data) -> {
//                        return data.getObjectId().equals(item.getObjectId()) && data.getAlgType().equals(data.getAlgType());
//                    }).collect(Collectors.toList());
//                    if(!filterDatas.isEmpty()) {
//                        item.setImg((filterDatas.get(0)).getImgAnalyse());
//                    } else {
//                        item.setImg("");
//                    }
//                } else {
//                    item.setImg(item.getImgAnalyse());
////                    item.setImgAnalyse("");
//                }
//
//            });
//            Collections.sort(dataList);
//            return getDataTable(dataList);
//        }
    }

    /**
     * 缺陷记录（将确认缺陷的数据展示在这）
     * @return
     */
    @GetMapping({"/defect/list"})
    public TableDataInfo defectList() {
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setPointStatusList(Arrays.asList(PointStatusEnum.CONFIRMED.getCode(), PointStatusEnum.TRACKING.getCode()));
        // 查出全部数据
        List<PatrolData> allList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);

        Map<String, String> imageNormalMap = allList.parallelStream()
                .filter(patrolData -> StringUtils.isNotEmpty(patrolData.getImageNormalUrlPath()))
                .collect(Collectors.toMap(
                        patrolData -> patrolData.getTaskPatrolId() + "_" + patrolData.getObjectId() + "_" + patrolData.getAlgType(),
                        PatrolData::getImageNormalUrlPath,
                        (existing, replacement) -> existing
                ));
        // 筛出缺陷数据
        List<PatrolData> filterList = allList.parallelStream().filter(patrolData -> "0".equals(patrolData.getWarnStatus())).collect(Collectors.toList());
        List<AlgInfo> algInfos = patrolResultService.selectAlgInfo(new PatrolResult());
        filterList.forEach((item) -> {
            item.setAlgName((algInfos.stream().anyMatch((alg) -> {
                return alg.getAlgSubtypeCode().equals(item.getAlgType());
            }) ? algInfos.stream().filter((alg) -> {
                return alg.getAlgSubtypeCode().equals(item.getAlgType());
            }).findFirst().get().getAlgSubtypeName() : ""));
            if ("1".equals(item.getFilter())) {
                item.setImg(item.getImageNormalUrlPath());
            }

            AlgValue algValue = new AlgValue();
            if(item.getResValue() != null) {
                String str = algValue.formatValue(item.getResValue());
                if ("meter".equals(item.getAlgType())) {
                    if (str.equals("-1")) {
                        item.setResValue("空值");
                    }
                }
            }
        });
        Map<String, List<PatrolData>> groupedFilterList = filterList.stream().collect(Collectors.groupingBy(item -> item.getTaskPatrolId() + "|" + item.getObjectId() + "|" + item.getAlgType()));
        List<PatrolData> resultList = new ArrayList<>();
        groupedFilterList.forEach((key, value) -> {
            PatrolData patrolData = new PatrolData();
            String[] keys = key.split("\\|");
            if(keys.length != 3) {
                logger.error("key format error: " + key);
            }
            String taskPatrolId = keys[0];
            String objectId = keys[1];
            String algType = keys[2];
            patrolData.setTaskPatrolId(taskPatrolId);
            patrolData.setObjectId(objectId);
            patrolData.setAlgType(algType);
            patrolData.setDesc(value.stream().map(PatrolData::getDesc).distinct().collect(Collectors.joining(",")));
            for (PatrolData data : value) {
                // 初筛有缺陷 展示初筛结果图片
                if ("1".equals(data.getFilter()) && StringUtils.isEmpty(patrolData.getImgAnalyse())) {
                    patrolData.setImgAnalyse(data.getImgAnalyse());
                }
                if ("1".equals(data.getFilter()) && StringUtils.isEmpty(patrolData.getImg())) {
                    patrolData.setImg(data.getImg());
                }
                // 大模型有缺陷 展示大模型结果图片
                if ("0".equals(data.getFilter())) {
                    patrolData.setImgAnalyse(data.getImgAnalyse());
                    patrolData.setImg(data.getImg());
                }
            }
            String areaId = value.stream().map(PatrolData::getAreaId).distinct().findFirst().orElse("");
            logger.info("defectList缺陷记录，{}",areaId);
            // 用新的区域树
            String areaNameS = getAreaNameSByAreaIdSRelation(areaId);
            logger.info("defectList缺陷记录，{}",areaNameS);
            String imageNormalPath = imageNormalMap.getOrDefault(taskPatrolId + "_" + objectId + "_" + algType, "");
            patrolData.setImageNormalUrlPath(imageNormalPath);
            patrolData.setAlgName(value.stream().map(item -> item.getAlgName() != null ? item.getAlgName() : "").distinct().findFirst().orElse(""));
            patrolData.setAreaName(areaNameS);
            patrolData.setBrightDesc(value.stream().map(item -> item.getBrightDesc() != null ? item.getBrightDesc() : "").distinct().findFirst().orElse(""));
            patrolData.setBrightImgAnalyse(value.stream().map(item -> item.getBrightImgAnalyse() != null ? item.getBrightImgAnalyse() : "").distinct().findFirst().orElse(""));
            patrolData.setBrightResStatus(value.stream().map(item -> item.getBrightResStatus() != null ? item.getBrightResStatus() : "").distinct().findFirst().orElse(""));
            patrolData.setChannelName(value.stream().map(item -> item.getChannelName() != null ? item.getChannelName() : "").distinct().findFirst().orElse(""));
            patrolData.setDataType(value.stream().map(item -> item.getDataType() != null ? item.getDataType() : "").distinct().findFirst().orElse(""));
            patrolData.setDeviceName(value.stream().map(item -> item.getDeviceName() != null ? item.getDeviceName() : "").distinct().findFirst().orElse(""));
            patrolData.setDeviceSource(value.stream().map(item -> item.getDeviceSource() != null ? item.getDeviceSource() : "").distinct().findFirst().orElse(""));
            patrolData.setImgType(value.stream().map(item -> item.getImgType() != null ? item.getImgType() : "").distinct().findFirst().orElse(""));
            patrolData.setLineId(value.stream().map(PatrolData::getLineId).distinct().collect(Collectors.joining(",")));
            patrolData.setPatrolTime(value.stream().map(item -> item.getPatrolTime() != null ? item.getPatrolTime() : "").distinct().findFirst().orElse(""));
            patrolData.setPointId(value.stream().map(item -> item.getPointId() != null ? item.getPointId() : "").distinct().findFirst().orElse(""));
            patrolData.setPointName(value.stream().map(item -> item.getPointName() != null ? item.getPointName() : "").distinct().findFirst().orElse(""));
            patrolData.setPointStatus(value.stream().map(item -> item.getPointStatus() != null ? item.getPointStatus() : "").distinct().findFirst().orElse(""));
            patrolData.setRequestId(value.stream().map(item -> item.getRequestId() != null ? item.getRequestId() : "").distinct().findFirst().orElse(""));
            patrolData.setResValue(value.stream().map(item -> item.getResValue() != null ? item.getResValue() : "").distinct().findFirst().orElse(""));
            patrolData.setResStatus(value.stream().map(item -> item.getResStatus() != null ? item.getResStatus() : "").distinct().findFirst().orElse(""));
            patrolData.setSuggestion(value.stream().map(item -> item.getSuggestion() != null ? item.getSuggestion() : "").distinct().findFirst().orElse(""));
            patrolData.setWarnStatus(value.stream().map(item -> item.getWarnStatus() != null ? item.getWarnStatus() : "").distinct().findFirst().orElse(""));

            resultList.add(patrolData);
        });
        // 非 null 的值按降序排列（最新的时间在前）,null的在最后面排列
        resultList.sort(Comparator.comparing(PatrolData::getPatrolTime,
                Comparator.nullsLast(Comparator.reverseOrder())));

        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();
        int toNum = Math.min(resultList.size(), pageNum * pageSize);
        List<PatrolData> pageList = resultList.subList((pageNum - 1) * pageSize, toNum);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(pageList);
        rspData.setMsg("查询成功");
        rspData.setTotal((new PageInfo<>(resultList)).getTotal());

        return rspData;
    }

    /**
     * 新的关系树
     * @param areaIdS
     * @return
     */
    private String getAreaNameSByAreaIdSRelation(String areaIdS) {
        AjaxResult ajaxResult = feignBasedataAreaService.selectAreaNameSForTaskByAreaIdSRelation((new JSONObject()).fluentPut("areaIdS", areaIdS));
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(ajaxResult));
        return jsonObject.get("data").toString();
    }

    //初筛大模型一起查询
    @GetMapping({"/list_v2_ex"})
    public TableDataInfo listV2Ex(PatrolTaskStatus patrolTaskStatus) {
        logger.info("LIST_V2_EX listV2Ex param: {}", patrolTaskStatus);
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setTaskPatrolId(patrolTaskStatus.getTaskPatrolledId());
        // 查出全部数据
        List<PatrolData> allList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);

        Map<String, String> imageNormalMap = allList.parallelStream()
                .collect(Collectors.toMap(
                        patrolData -> patrolData.getObjectId() + "_" + patrolData.getAlgType(),
                        patrolData -> StringUtils.isNotEmpty(patrolData.getImageNormalUrlPath())
                                ?patrolData.getImageNormalUrlPath()
                                :patrolData.getImgAnalyse(),
                        (existing, replacement) -> existing
                ));
        // 筛出缺陷数据
        List<PatrolData> filterList = allList.parallelStream().filter(patrolData -> "0".equals(patrolData.getWarnStatus())).collect(Collectors.toList());
        List<AlgInfo> algInfos = patrolResultService.selectAlgInfo(new PatrolResult());
        filterList.forEach((item) -> {
            item.setAlgName((algInfos.stream().anyMatch((alg) -> {
                return alg.getAlgSubtypeCode().equals(item.getAlgType());
            }) ? algInfos.stream().filter((alg) -> {
                return alg.getAlgSubtypeCode().equals(item.getAlgType());
            }).findFirst().get().getAlgSubtypeName() : ""));
            if ("1".equals(item.getFilter())) {
                item.setImg(item.getImageNormalUrlPath());
            }

            AlgValue algValue = new AlgValue();
            if(item.getResValue() != null) {
                String str = algValue.formatValue(item.getResValue());
                if ("meter".equals(item.getAlgType())) {
                    if (str.equals("-1")) {
                        item.setResValue("空值");
                    }
                }
            }
        });
        Map<GroupKey, List<PatrolData>> groupedFilterList = filterList.stream().collect(Collectors.groupingBy(
                item -> new GroupKey(item.getObjectId(), item.getAlgType())
        ));
        List<PatrolData> resultList = new ArrayList<>();
        for (Map.Entry<GroupKey, List<PatrolData>> groupKeyListEntry : groupedFilterList.entrySet()) {
            GroupKey key = groupKeyListEntry.getKey();
            List<PatrolData> value = groupKeyListEntry.getValue();
            PatrolData patrolData = new PatrolData();
            patrolData.setObjectId(key.objectId);
            patrolData.setAlgType(key.algType);
            if (AlgConstants.CORRECTION.equals(key.algType)) {
                continue;
            }
            patrolData.setDesc(value.stream().map(PatrolData::getDesc).distinct().collect(Collectors.joining(",")));
            for (PatrolData data : value) {
                // 初筛有缺陷 展示初筛结果图片
                if ("1".equals(data.getFilter()) && StringUtils.isEmpty(patrolData.getImgAnalyse())) {
                    patrolData.setImgAnalyse(data.getImgAnalyse());
                }
                if ("1".equals(data.getFilter()) && StringUtils.isEmpty(patrolData.getImg())) {
                    patrolData.setImg(data.getImg());
                }
                // 大模型有缺陷 展示大模型结果图片
                if ("0".equals(data.getFilter())) {
                    patrolData.setImgAnalyse(data.getImgAnalyse());
                    patrolData.setImg(data.getImg());
                }
            }
            String imageNormalPath = imageNormalMap.getOrDefault(key.objectId + "_" + key.algType, "");
            patrolData.setImageNormalUrlPath(imageNormalPath);
            patrolData.setAlgName(value.stream().map(item -> item.getAlgName() != null ? item.getAlgName() : "").distinct().findFirst().orElse(""));
            patrolData.setAreaName(value.stream().map(item -> item.getAreaName() != null ? item.getAreaName() : "").distinct().findFirst().orElse(""));
            patrolData.setBrightDesc(value.stream().map(item -> item.getBrightDesc() != null ? item.getBrightDesc() : "").distinct().findFirst().orElse(""));
            patrolData.setBrightImgAnalyse(value.stream().map(item -> item.getBrightImgAnalyse() != null ? item.getBrightImgAnalyse() : "").distinct().findFirst().orElse(""));
            patrolData.setBrightResStatus(value.stream().map(item -> item.getBrightResStatus() != null ? item.getBrightResStatus() : "").distinct().findFirst().orElse(""));
            patrolData.setChannelName(value.stream().map(item -> item.getChannelName() != null ? item.getChannelName() : "").distinct().findFirst().orElse(""));
            patrolData.setDataType(value.stream().map(item -> item.getDataType() != null ? item.getDataType() : "").distinct().findFirst().orElse(""));
            patrolData.setDeviceName(value.stream().map(item -> item.getDeviceName() != null ? item.getDeviceName() : "").distinct().findFirst().orElse(""));
            patrolData.setDeviceSource(value.stream().map(item -> item.getDeviceSource() != null ? item.getDeviceSource() : "").distinct().findFirst().orElse(""));
            patrolData.setImgType(value.stream().map(item -> item.getImgType() != null ? item.getImgType() : "").distinct().findFirst().orElse(""));
            patrolData.setLineId(value.stream().map(PatrolData::getLineId).distinct().collect(Collectors.joining(",")));
            patrolData.setPatrolTime(value.stream().map(item -> item.getPatrolTime() != null ? item.getPatrolTime() : "").distinct().findFirst().orElse(""));
            patrolData.setPointId(value.stream().map(item -> item.getPointId() != null ? item.getPointId() : "").distinct().findFirst().orElse(""));
            patrolData.setPointName(value.stream().map(item -> item.getPointName() != null ? item.getPointName() : "").distinct().findFirst().orElse(""));
            patrolData.setPointStatus(value.stream().map(item -> item.getPointStatus() != null ? item.getPointStatus() : "").distinct().findFirst().orElse(""));
            patrolData.setRequestId(value.stream().map(item -> item.getRequestId() != null ? item.getRequestId() : "").distinct().findFirst().orElse(""));
            patrolData.setResValue(value.stream().map(item -> item.getResValue() != null ? item.getResValue() : "").distinct().findFirst().orElse(""));
            patrolData.setResStatus(value.stream().map(item -> item.getResStatus() != null ? item.getResStatus() : "").distinct().findFirst().orElse(""));
            patrolData.setSuggestion(value.stream().map(item -> item.getSuggestion() != null ? item.getSuggestion() : "").distinct().findFirst().orElse(""));
            patrolData.setWarnStatus(value.stream().map(item -> item.getWarnStatus() != null ? item.getWarnStatus() : "").distinct().findFirst().orElse(""));

            resultList.add(patrolData);
        }


        Collections.sort(resultList);

        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();
        int toNum = Math.min(resultList.size(), pageNum * pageSize);
        List<PatrolData> pageList = resultList.subList((pageNum - 1) * pageSize, toNum);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(pageList);
        rspData.setMsg("查询成功");
        rspData.setTotal((new PageInfo<>(resultList)).getTotal());

        return rspData;
    }

    private static class GroupKey {
        private final String objectId;
        private final String algType;

        public GroupKey(String objectId, String algType) {
            this.objectId = objectId;
            this.algType = algType;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            GroupKey groupKey = (GroupKey) o;
            return Objects.equals(objectId, groupKey.objectId) && Objects.equals(algType, groupKey.algType);

        }

        @Override
        public int hashCode() {
            return Objects.hash(objectId, algType);
        }
    }

    @GetMapping({"/list_v3"})
    public TableDataInfo listV3(PatrolTaskStatus patrolTaskStatus) {
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setTaskPatrolId(patrolTaskStatus.getTaskPatrolledId());
        resultAnalysis.setResult("0");
        List<PatrolData> filterList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
        startPage();
        resultAnalysis.setFilter(patrolTaskStatus.getFilter());
        resultAnalysis.setResult("");
        List<PatrolData> list = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
        List<AlgInfo> algInfos = patrolResultService.selectAlgInfo(new PatrolResult());
        list.forEach((item) -> {
            item.setAlgName((algInfos.stream().filter((alg) -> {
                return alg.getAlgSubtypeCode().equals(item.getAlgType());
            }).findFirst().get()).getAlgSubtypeName());
            if("0".equals(item.getFilter())) {
                List<PatrolData> filterDatas = filterList.stream().filter((data) -> {
                    return data.getObjectId().equals(item.getObjectId()) && data.getAlgType().equals(data.getAlgType());
                }).collect(Collectors.toList());
                if(!filterDatas.isEmpty()) {
                    item.setImg((filterDatas.get(0)).getImgAnalyse());
                    item.setImageNormalUrlPath((filterDatas.get(0)).getImageNormalUrlPath());
                } else {
                    item.setImg("");
                }
            }

        });
        Collections.sort(list);
        return this.getDataTable(list);
    }

    @GetMapping({"/list_exception"})
    public TableDataInfo listException(PatrolTaskStatus patrolTaskStatus) {
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setTaskPatrolId(patrolTaskStatus.getTaskPatrolledId());
        startPage();
        resultAnalysis.setFilter(patrolTaskStatus.getFilter());
//        resultAnalysis.setResCode("2000");
//        resultAnalysis.setPointStatus("0");
        resultAnalysis.setResultType("2"); // 2异常
        resultAnalysis.setPosType(patrolTaskStatus.getPosType());
        List<PatrolData> list = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
        List<PatrolData> filterList = new ArrayList<>();
        if ("0".equals(patrolTaskStatus.getFilter()) && list != null && list.size() > 0) {
            resultAnalysis.setFilter("1");
            resultAnalysis.setResultType("");
            resultAnalysis.setPosType("");
            filterList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
        }
        List<AlgInfo> algInfos = patrolResultService.selectAlgInfo(new PatrolResult());
        List<PatrolData> finalFilterList = filterList;
        list.forEach((item) -> {
            try {
                item.setAlgName((algInfos.stream().filter((alg) -> {
                    return alg.getAlgSubtypeCode().equals(item.getAlgType());
                }).findFirst().get()).getAlgSubtypeName());
                AlgValue algValue = new AlgValue();
                if(item.getResValue() != null) {
                    String str = algValue.formatValue(item.getResValue());
                    if ("meter".equals(item.getAlgType())) {
                        if (str.equals("-1")) {
                            item.setResValue(messageUtils.get("空值"));
                        }
                    }
                }

                if ("0".equals(item.getFilter())) {
                    // 初筛数据
                    List<PatrolData> filterDatas = finalFilterList.stream().filter((data) -> {
                        return data.getObjectId().equals(item.getObjectId()) && data.getAlgType().equals(item.getAlgType());
                    }).collect(Collectors.toList());
                    if (!filterDatas.isEmpty()) {
                        item.setImg((filterDatas.get(0)).getImgAnalyse());
                        item.setFilterDesc((filterDatas.get(0)).getDesc());
                    }
                }
            } catch (Exception e) {
                logger.error("list_exception: algType: {}, exception: {}", item.getAlgType(), e.getMessage());
            }

        });
        Collections.sort(list);
        return getDataTable(list);
    }

    @GetMapping({"/doc"})
    public TableDataInfo listDoc(PatrolResult patrolResult) {
        List<AlgInfo> algInfos = patrolResultMapper.selectAlgInfo(new PatrolResult());
        startPage();
        List<PatrolResultRef> patrolResultRefs = patrolResultMapper.selectResultDoc(patrolResult);

        for (PatrolResultRef ref : patrolResultRefs) {
            ref.setAlgName((algInfos.stream().filter((alg) -> {
                return alg.getAlgSubtypeCode().equals(ref.getAlgType());
            }).findFirst().get()).getAlgSubtypeName());
        }

        return getDataTable(patrolResultRefs);
    }

    @GetMapping({"/doc/detail"})
    public Response<PatrolResult> docDetail(PatrolResult patrolResult) {
        List<AlgInfo> algInfos = patrolResultMapper.selectAlgInfo(new PatrolResult());
        PatrolResultRef result = patrolResultMapper.selectResultDoc(patrolResult).get(0);
        result.setAlgName((algInfos.stream().filter((alg) -> {
            return alg.getAlgSubtypeCode().equals(result.getAlgType());
        }).findFirst().get()).getAlgSubtypeName());
        return Response.ok(patrolResult);
    }

    @PostMapping({"doc"})
    public AjaxResult modifyDoc(@RequestBody ModifyDocModel model) {
        ResultAnalysis resultAnalysis = resultAnalysisService.selectResultAnalysisByLineId(model.getLineId());
        resultAnalysis.setOriginalValue(resultAnalysis.getResValue());
        resultAnalysis.setResValue(model.getValue());
        resultAnalysisService.updateResultAnalysis(resultAnalysis);
        return AjaxResult.success();
    }

    @GetMapping({"summary/points"})
    public TableDataInfo summaryPoints(AnalyseSummaryAlarmModel model) {
        this.startPage();
        List<AlgPatrolPoint> algPatrolPointList = resultAnalysisService.selectResultAnalyseForAlarm(model);
        return this.getDataTable(algPatrolPointList);
    }

    @GetMapping({"summary/alarm"})
    public TableDataInfo summaryAlarm(AnalyseSummaryAlarmModel model) {
        this.startPage();
        List<PatrolData> analysisList = resultAnalysisService.selectResultAnalysisListForAlarm(model);
        if(!analysisList.isEmpty()) {
            Collections.sort(analysisList);
        }

        return this.getDataTable(analysisList);
    }

    @GetMapping({"summary/alarm/total"})
    public AjaxResult summaryAlarmTotal(AnalyseSummaryAlarmModel model) {
        String filter = StringUtils.isEmpty(model.getFilter()) ? "0" : model.getFilter();
        String isToday = StringUtils.isEmpty(model.getIsToday()) ? "0" : model.getIsToday();
        String type = StringUtils.isEmpty(model.getType()) ? "0" : model.getType();
        Long total = resultAnalysisService.getDefectCountGroupByPoint(filter, isToday, type);
        return AjaxResult.success(total);
    }

}
