package com.inspect.task.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.inspect.analysis.domain.AlgValue;
import com.inspect.analysis.domain.ResultAnalysis;
import com.inspect.analysis.service.IResultAnalysisService;
import com.inspect.base.core.constant.AlgConstants;
import com.inspect.base.core.constant.Color;
import com.inspect.base.core.constant.RedisConst;
import com.inspect.base.core.domain.DataMsg;
import com.inspect.base.core.enums.PointStatusEnum;
import com.inspect.base.core.enums.ResStatusEnum;
import com.inspect.base.core.enums.TaskStatus;
import com.inspect.base.core.service.SyncDataToUpstreamService;
import com.inspect.base.core.sftp.SftpClient;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.base.core.utils.SFTPUtil;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.bean.BeanUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.utils.xml.GenXmlByBean;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.PageDomain;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.base.core.web.page.TableSupport;
import com.inspect.base.redis.service.RedisService;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.common.security.utils.DictUtils;
import com.inspect.fegin.FeignBasedataAreaService;
import com.inspect.fegin.FeignBasedataPatrolPointPresetService;
import com.inspect.message.MessageUtils;
import com.inspect.partrolresult.controller.PatrolResultController;
import com.inspect.partrolresult.domain.AlgInfo;
import com.inspect.partrolresult.domain.PatrolResult;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.system.base.domain.SysDictData;
import com.inspect.system.base.openDomain.BasedataEqpBookMoMain;
import com.inspect.task.domain.*;
import com.inspect.task.service.IPatrolTaskService;
import com.inspect.taskftp.domain.PatrolTaskFtp;
import com.inspect.taskftp.service.IPatrolTaskFtpService;
import com.inspect.taskinfo.domain.PatrolTaskInfo;
import com.inspect.taskinfo.service.IPatrolTaskInfoService;
import com.inspect.taskstatus.client.FeignTaskClient;
import com.inspect.taskstatus.domain.PatrolTaskStatus;
import com.inspect.taskstatus.service.IPatrolTaskStatusService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping({"/task"})
public class PatrolTaskController extends BaseController {

    private static final String TEMP_DIR = "temp_images/";
    public final RedisService redisService;
    private final IPatrolTaskService patrolTaskService;
    private final IPatrolTaskStatusService patrolTaskStatusService;
    private final IPatrolTaskInfoService patrolTaskInfoService;
    private final IResultAnalysisService resultAnalysisService;
    private final IPatrolResultService patrolResultService;
    private final FeignBasedataPatrolPointPresetService basedataPatrolPointPresetServiceClient;
    private final FeignBasedataAreaService FeignBasedataAreaService;
    private final IPatrolTaskFtpService patrolTaskFtpService;
    private final SyncDataToUpstreamService syncDataToUpstreamService;
    @Resource
    private FeignTaskClient feignTaskClient;
    @Resource
    private SftpClient sftpClient;
    @Autowired
    private MessageUtils MessageUtils;

    public PatrolTaskController(
            IPatrolTaskService patrolTaskService,
            IPatrolTaskStatusService patrolTaskStatusService,
            IPatrolTaskInfoService patrolTaskInfoService,
            IResultAnalysisService resultAnalysisService,
            IPatrolResultService patrolResultService,
            FeignBasedataPatrolPointPresetService basedataPatrolPointPresetServiceClient,
            FeignBasedataAreaService FeignBasedataAreaService,
            RedisService redisService,
            IPatrolTaskFtpService patrolTaskFtpService,
            SyncDataToUpstreamService syncDataToUpstreamService) {
        this.patrolTaskService = patrolTaskService;
        this.patrolTaskStatusService = patrolTaskStatusService;
        this.patrolTaskInfoService = patrolTaskInfoService;
        this.resultAnalysisService = resultAnalysisService;
        this.patrolResultService = patrolResultService;
        this.basedataPatrolPointPresetServiceClient = basedataPatrolPointPresetServiceClient;
        this.FeignBasedataAreaService = FeignBasedataAreaService;
        this.redisService = redisService;
        this.patrolTaskFtpService = patrolTaskFtpService;
        this.syncDataToUpstreamService = syncDataToUpstreamService;
    }

    public static String toCycleMonth(String monthSting) {
        StringBuilder stringBuilder = new StringBuilder();
        String[] months = monthSting.split(StringUtils.COMMA);
        for (String month : months) {
            for (int i = 1; i < 31; ++i) {
                if (month.equals(i + "号")) {
                    stringBuilder.append(i).append(StringUtils.COMMA);
                }
            }
        }

        return stringBuilder.toString();
    }

    public static String calcCycleMonth(String month) {
        StringBuilder str = new StringBuilder();
        String[] mon = month.split(StringUtils.COMMA);

        for (String s : mon) {
            for (int i = 1; i < 31; ++i) {
                if (s.equals(i + "")) {
                    str.append(i).append("号,");
                }
            }
        }

        return str.toString();
    }

    private static byte[] compressImage(byte[] originalBytes) throws IOException {
        ByteArrayInputStream input = new ByteArrayInputStream(originalBytes);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Thumbnails.of(input)
                .scale(0.5) // 缩小尺寸
                .outputQuality(0.5) // 70%质量
                .outputFormat("jpg")
                .toOutputStream(output);

        return output.toByteArray();
    }

    public static byte[] getStringByInputStream(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            byte[] b = new byte[10240];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                inputStream.close();
                outputStream.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        return outputStream.toByteArray();
    }

    @GetMapping("/list")
    public TableDataInfo list(PatrolTask patrolTask) {
        startPage();
        List<PatrolTask> taskList = patrolTaskService.selectPatrolTaskList(patrolTask);
        logger.debug("[TASK] patrolTask: {}, taskList: {}", patrolTask, taskList);
        for (PatrolTask task : taskList) {
            PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
            patrolTaskStatus.setTaskCode(task.getTaskCode());
            patrolTaskStatus.setTaskState(TaskStatus.RUNNING.getCode());
            List<PatrolTaskStatus> statusList = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
            if (!statusList.isEmpty()) {
                task.setFileStatus("1");
            } else {
                task.setFileStatus("0");
            }
            // 统计任务点位数量
            String taskMajorId = task.getTaskCode();
            int totalPoints = patrolTaskInfoService.countPatrolTaskInfoByMajorId(taskMajorId);
            task.setTotalPoints(totalPoints);
        }
        return getDataTable(taskList);
    }

    @GetMapping({"/taskInfo"})
    public TableDataInfo taskInfo(TaskInfoParams taskInfoParams) {
        PatrolTaskStatus taskStatus
                = patrolTaskStatusService.selectPatrolTaskStatusByLineId(taskInfoParams.getLineId());
        List<PatrolData> list = new ArrayList<>();
        if (taskStatus != null) {
            long start = System.currentTimeMillis();
            startPage();
            PatrolResult patrolResult = new PatrolResult();
            patrolResult.setTaskCode(taskStatus.getTaskCode());
            patrolResult.setTaskPatrolledId(taskStatus.getTaskPatrolledId());
            patrolResult.setDataType(taskInfoParams.getDataType());
            patrolResult.setRecognitionType(taskInfoParams.getRecognitionType());
            patrolResult.setValid(taskInfoParams.getValid());
            patrolResult.setPatrolStatus(taskInfoParams.getPatrolStatus());
            list = patrolResultService.selectPatrolDataResultByTaskCode(patrolResult);
            for (PatrolData patrolData : list) {
                if (StringUtils.isNotEmpty(patrolData.getImg()) && patrolData.getImg().contains(",")) {
                    String img = patrolData.getImg();
                    if (img.indexOf(",") > 0) {
                        img = img.split(",")[1];
                        if (!img.startsWith("/")) {
                            img = "/" + img;
                        }
                    }
                    patrolData.setImg(img);
                }
            }
            logger.info("[TASK] query cost {} ms", (System.currentTimeMillis() - start));
        }

        return getDataTable(list);
    }

    @GetMapping("/taskInfo_v2")
    public TableDataInfo taskInfoV3(PatrolTaskStatus patrolTaskStatus) {
        logger.info(Color.GREEN + "[MAIN TASK] taskInfoV2 param: {}" + Color.END, patrolTaskStatus);
        Long lineId = patrolTaskStatus.getLineId();
        if (lineId == null) {
            return getDataTable(1, new ArrayList<>(), new ArrayList<>());
        }
        PatrolTaskStatus taskStatus = patrolTaskStatusService.selectPatrolTaskStatusByLineId(lineId);
        if (taskStatus == null) {
            return getDataTable(2, new ArrayList<>(), new ArrayList<>());
        }
        List<PatrolData> newList = getNewList(patrolTaskStatus, taskStatus.getTaskPatrolledId());

        // 10. 分页（仍为内存分页，详见下方说明）
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int pageNum = pageDomain.getPageNum();
        int pageSize = pageDomain.getPageSize();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(newList.size(), pageNum * pageSize);
        List<PatrolData> pageList = (fromIndex < newList.size())
                ? newList.subList(fromIndex, toIndex)
                : new ArrayList<>();

        return getDataTable(0, pageList, newList);
    }

    private List<PatrolData> getNewList(PatrolTaskStatus patrolTaskStatus, String taskPatrolledId) {
        // 查询算法列表
        List<AlgInfo> algInfos = patrolResultService.selectAlgInfo(new PatrolResult());
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setTaskPatrolId(taskPatrolledId);
        resultAnalysis.setPosType(patrolTaskStatus.getPosType());
        resultAnalysis.setFilter("1");
        // 初筛数据（filter=1）
        List<PatrolData> filterList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);

        // 大模型数据（filter=0）
        resultAnalysis.setFilter("0");
        List<PatrolData> newList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);

        // 光明模型数据（filter=2）
        resultAnalysis.setFilter("2");
        List<PatrolData> brightList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);

        // 1. 预构建 algName 映射（避免每次循环 stream 查找）
        Map<String, String> algNameMap = algInfos.stream()
                .collect(Collectors.toMap(
                        AlgInfo::getAlgSubtypeCode,
                        AlgInfo::getAlgSubtypeName,
                        (a, b) -> a // 重复时保留第一个
                ));

        // 2. 使用 LinkedHashMap 构建 filter/bright 映射（O(1) 查找 + 保持原有顺序）
        Map<String, PatrolData> filterMap = filterList.stream()
                .collect(Collectors.toMap(
                        data -> data.getObjectId() + "_" + data.getAlgType(),
                        data -> data,
                        (a, b) -> a,
                        LinkedHashMap::new
                ));

        Map<String, PatrolData> brightMap = brightList.stream()
                .collect(Collectors.toMap(
                        data -> data.getObjectId() + "_" + data.getAlgType(),
                        data -> data,
                        (a, b) -> a,
                        LinkedHashMap::new
                ));
        /**
         * 初筛，大模型  大模型结果为最终缺陷
         * 初筛，光明大模型 初筛结果为最终缺陷
         */
        for (PatrolData item : newList) {
            String key = item.getObjectId() + "_" + item.getAlgType();

            // 初筛数据合并
            PatrolData filterData = filterMap.get(key);
            if (filterData != null) {
                item.setImg(filterData.getImgAnalyse());
                item.setFilterDesc(filterData.getDesc());
                if (StringUtils.isEmpty(item.getImageNormalUrlPath())) {
                    item.setImageNormalUrlPath(filterData.getImageNormalUrlPath());
                }
                filterMap.remove(key);
            }

            // 光明大模型数据合并
            PatrolData brightData = brightMap.get(key);
            if (brightData != null) {
                item.setBrightDesc(brightData.getDesc());
                item.setBrightResStatus(brightData.getResStatus());
                item.setBrightImgAnalyse(brightData.getImgAnalyse());
                brightMap.remove(key);
            }
        }

        // 4. 处理剩余初筛数据
        List<PatrolData> remainingFilters = new ArrayList<>(filterMap.values());
        for (PatrolData item : remainingFilters) {
            String key = item.getObjectId() + "_" + item.getAlgType();
            PatrolData brightData = brightMap.get(key);
            if (brightData != null) {
                item.setBrightDesc(brightData.getDesc());
                item.setBrightResStatus(brightData.getResStatus());
                item.setBrightImgAnalyse(brightData.getImgAnalyse());
                brightMap.remove(key);
            }
            item.setImgAnalyse(null);
            item.setFilterDesc(item.getDesc());
            item.setDesc("");
        }

        // 5. 处理剩余光明大模型数据
        List<PatrolData> remainingBrights = new ArrayList<>(brightMap.values());
        for (PatrolData item : remainingBrights) {
            item.setBrightDesc(item.getDesc());
            item.setBrightResStatus(item.getResStatus());
            item.setBrightImgAnalyse(item.getImgAnalyse());
            item.setDesc("");
        }

        // 合并所有数据
        newList.addAll(remainingFilters);
        newList.addAll(remainingBrights);

        // 6. 统一设置 algName + resValue 格式化（只循环一次）
        AlgValue algValue = new AlgValue();
        for (PatrolData item : newList) {
            item.setAlgName(algNameMap.getOrDefault(item.getAlgType(), ""));
            if (item.getResValue() != null) {
                String str = algValue.formatValue(item.getResValue());
                if ("meter".equals(item.getAlgType()) && "-1".equals(str)) {
                    item.setResValue("空值");
                }
            }
        }

        // 7. 所有过滤条件合并为一个 stream（避免多次 filter + collect）
        newList = newList.stream()
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getAlgName())
                        || patrolTaskStatus.getAlgName().equals(element.getAlgName()))
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getFilterDesc())
                        || patrolTaskStatus.getFilterDesc().equals(element.getFilterDesc()))
                // 生产设备、点位名称等模糊匹配（增加 null 保护，防止 NPE）
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getDeviceName())
                        || (element.getDeviceName() != null && element.getDeviceName().contains(patrolTaskStatus.getDeviceName())))
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getPointName())
                        || (element.getPointName() != null && element.getPointName().contains(patrolTaskStatus.getPointName())))
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getChannelName())
                        || (element.getChannelName() != null && element.getChannelName().contains(patrolTaskStatus.getChannelName())))
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getDeviceSource())
                        || (element.getDeviceSource() != null && element.getDeviceSource().contains(patrolTaskStatus.getDeviceSource())))
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getPointStatus())
                        || patrolTaskStatus.getPointStatus().equals(element.getPointStatus()))
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getDesc())
                        || patrolTaskStatus.getDesc().equals(element.getDesc()))
                .filter(element -> StringUtils.isEmpty(patrolTaskStatus.getResultType())
                        || patrolTaskStatus.getResultType().equals(element.getWarnStatus()))
                .collect(Collectors.toList());

        // 8. 去重（保持首次出现顺序）
        Map<String, PatrolData> keyPatrolData = new LinkedHashMap<>();
        for (PatrolData patrolData : newList) {
            keyPatrolData.putIfAbsent(patrolData.getObjectId() + "_" + patrolData.getAlgType(), patrolData);
        }
        newList = new ArrayList<>(keyPatrolData.values());

        // 9. 异常置顶排序
        if ("1".equals(patrolTaskStatus.getAbnormal())) {
            newList.sort(Comparator.comparingInt(obj -> {
                switch (obj.getPointStatus()) {
                    case "6":
                        return 1; // 缺陷
                    case "5":
                        return 2; // 确认
                    case "4":
                        return 3; // 跟踪（告警）
                    case "0":
                        return 4; // 异常
                    case "1":
                        return 5; // 正常
                    case "2":
                        return 6; // 待人工确认
                    case "3":
                        return 7; // 已撤销（忽略）
                    default:
                        return 8;
                }
            }));
        }
        return newList;
    }

    @Log(
            title = "巡视任务(任务模型文件数据)",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, PatrolTask patrolTask) {
        List<PatrolTask> list = patrolTaskService.selectPatrolTaskList(patrolTask);
        ExcelUtil<PatrolTask> util = new ExcelUtil<>(PatrolTask.class);
        util.exportExcel(response, list, "巡视任务(任务模型文件数据)数据");
    }

    /**
     * 信息
     *
     * @param object
     * @return
     */
    @GetMapping({"/{taskId}"})
    public AjaxResult getInfo(@PathVariable("taskId") Object object) {
        long taskId;
        try {
            taskId = Long.parseLong(String.valueOf(object));
        } catch (Exception e) {
            logger.info("[TASK] parameter taskId error: {}", e.getMessage());
            return AjaxResult.fail(500, "parameter error: {}", e.getMessage());
        }
        List<PrevPoint> prevPoints = new ArrayList<>();
        PatrolTask patrolTask = patrolTaskService.selectPatrolTaskByTaskId(taskId);
        if (patrolTask == null) {
            return AjaxResult.fail(500, "任务不存在");
        }

        if (StringUtils.isEmpty(patrolTask.getExecutionMode())) {
            patrolTask.setExecutionMode("0");
        }

        if (StringUtils.isEmpty(patrolTask.getType())) {
            patrolTask.setType("4");
        }

        if (StringUtils.isNotEmpty(patrolTask.getCycleMonth())) {
            String cycleMonth = calcCycleMonth(patrolTask.getCycleMonth());
            if (StringUtils.isNotEmpty(cycleMonth)) {
                patrolTask.setCycleMonth(cycleMonth);
            }
        }

        PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
        patrolTaskInfo.setTaskMajorId(patrolTask.getTaskId() + "");
        List<PatrolTaskInfo> patrolTaskInfos = patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
        if (!patrolTaskInfos.isEmpty()) {
            for (PatrolTaskInfo taskInfo : patrolTaskInfos) {
                PrevPoint prevPoint = new PrevPoint();
                prevPoint.setParentId(taskInfo.getParentId());
                prevPoint.setEqpBookId(taskInfo.getEbookId());
                prevPoint.setLabel(taskInfo.getEbookName());
                prevPoint.setPresetCode(taskInfo.getPresetCode());
                prevPoints.add(prevPoint);
            }
        }

        patrolTask.setPrevPoints(prevPoints);
        return AjaxResult.success(patrolTask);
    }

    /**
     * 信息
     *
     * @param object
     * @return
     */
    @GetMapping({"/shaoxing/{taskId}"})
    public AjaxResult getInfoShaoxing(@PathVariable("taskId") Object object) {
        long taskId;
        try {
            taskId = Long.parseLong(String.valueOf(object));
        } catch (Exception e) {
            logger.info("[TASK] parameter taskId error: {}", e.getMessage());
            return AjaxResult.fail(500, "parameter error: {}", e.getMessage());
        }
        List<PrevPoint> prevPoints = new ArrayList<>();
        PatrolTask patrolTask = patrolTaskService.selectPatrolTaskByTaskId(taskId);
        if (patrolTask == null) {
            return AjaxResult.fail(500, "任务不存在");
        }

        if (StringUtils.isEmpty(patrolTask.getExecutionMode())) {
            patrolTask.setExecutionMode("0");
        }

        if (StringUtils.isEmpty(patrolTask.getType())) {
            patrolTask.setType("4");
        }

        if (StringUtils.isNotEmpty(patrolTask.getCycleMonth())) {
            String cycleMonth = calcCycleMonth(patrolTask.getCycleMonth());
            if (StringUtils.isNotEmpty(cycleMonth)) {
                patrolTask.setCycleMonth(cycleMonth);
            }
        }

        PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
        patrolTaskInfo.setTaskMajorId(patrolTask.getTaskId() + "");
        List<PatrolTaskInfo> patrolTaskInfos = patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
        List<String> patrolPointIds = new ArrayList<>();
        if (!patrolTaskInfos.isEmpty()) {
            for (PatrolTaskInfo taskInfo : patrolTaskInfos) {
                patrolPointIds.add(taskInfo.getDeviceId());
            }
        }

        patrolTask.setPrevPoints(prevPoints);
        patrolTask.setPatrolPointIds(patrolPointIds);
        return AjaxResult.success(patrolTask);
    }

    @Log(
            title = "巡视任务(任务模型文件数据)",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody PatrolTask patrolTask) {
        return toAjax(patrolTaskService.insertPatrolTask(patrolTask));
    }

    @Log(
            title = "巡视任务(任务模型文件数据)",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody PatrolTask patrolTask) {
        return toAjax(patrolTaskService.updatePatrolTask(patrolTask));
    }

    @Log(
            title = "巡视任务(任务模型文件数据)",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{taskIds}"})
    public AjaxResult remove(@PathVariable Long[] taskIds) {
        for (Long id : taskIds) {
            logger.info("[CONTROLLER] remove task taskId: {}", id);
            PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
            patrolTaskStatus.setTaskCode(String.valueOf(id));
            patrolTaskStatus.setTaskState("2");
            List<PatrolTaskStatus> results = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
            if (!results.isEmpty()) {
                return AjaxResult.error("无法删除正在执行的任务！");
            }
        }

        patrolTaskService.deletePatrolTaskByTaskIds(taskIds);
        patrolTaskInfoService.deletePatrolTaskInfoByMajorIds(taskIds);
        for (Long taskId : taskIds) {
            for (String key : redisService.keys(RedisConst.TASK_CODE_EX)) {
                logger.info("[CONTROLLER] remove task redis key: {}", key);
                if (key.contains(String.valueOf(taskId))) {
                    redisService.deleteObject(key);
                }
            }
        }
        return toAjax(1);
    }

    public String majorId(PatrolTask patrolTask) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return patrolTask.getTaskCode() + "_" + sdf.format(patrolTask.getCycleExecuteTime());
    }

    @PostMapping({"/shaoxing/add"})
    @ResponseBody
    public AjaxResult add_shaoxing(@RequestBody String message) {
        logger.info("[TASK] add message: {}", message);
        List<String> patrolTaskIds = new ArrayList<>();
        if (StringUtils.isEmpty(message)) {
            return AjaxResult.success(String.join(StringUtils.COMMA, patrolTaskIds));
        }
        JSONObject jsonObject = JSONObject.parseObject(message);
        logger.info(Color.GREEN + "[MAIN] toPatrolTaskList jsonObject: {}" + Color.END, jsonObject);
        PatrolTask patrolTask = new PatrolTask();
        toPatrolTask(jsonObject, patrolTask);

        List<String> patrolPointIds = new ArrayList<>();
        // 点位信息
        if (jsonObject.get("patrolPointIds") != null) {
            String jsonObjectString = jsonObject.get("patrolPointIds").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                String[] pointArr = jsonObjectString.split(",");
                patrolPointIds = Arrays.asList(pointArr);
            }
        }
        List<PatrolTaskInfo> taskInfos = new ArrayList<>();
        if (patrolPointIds.size() > 0) {
            // 查询点位信息
            List<JSONObject> patrolPointList = patrolTaskService.selectBasedataPatrolPointList(patrolPointIds);
            Map<Long, JSONObject> patrolPointIdMap = patrolPointList.stream().collect(Collectors.toMap(item -> item.getLong("patrolPointId"), Function.identity()));
            // 查询点位预置位信息
            List<JSONObject> basedataPatrolPointPresetList = patrolTaskService.selectBasedataPatrolPointPresetList(patrolPointIds);
            Map<Long, JSONObject> basedataPatrolPointPresetMap = basedataPatrolPointPresetList.stream().collect(Collectors.toMap(item -> item.getLong("patrolPointId"), Function.identity(), (e1, e2) -> e2));
            // 查询点位预置位位置信息
            List<JSONObject> basedataPatrolPresetPosList = patrolTaskService.selectPatrolPresetPosList(patrolPointIds);
            Map<Long, JSONObject> basedataPatrolPresetPosMap = basedataPatrolPresetPosList.stream().collect(Collectors.toMap(item -> item.getLong("patrolPointId"), Function.identity(), (e1, e2) -> e2));
            Set<String> eqpBookIdPreset = basedataPatrolPointPresetList.stream().map(basedataPatrolPointPresetJson -> {
                return basedataPatrolPointPresetJson.getString("eqpBookId");
            }).collect(Collectors.toSet());
            Set<String> eqpBookIdPos = basedataPatrolPresetPosList.stream().map(basedataPatrolPresetPosJson -> {
                return basedataPatrolPresetPosJson.getString("eqpBookId");
            }).collect(Collectors.toSet());
            List<String> eqpBookIds = new ArrayList<>();
            eqpBookIds.addAll(eqpBookIdPreset);
            eqpBookIds.addAll(eqpBookIdPos);
            // 查询设备信息
            List<Map<String, String>> list = patrolTaskInfoService.selectVideoPosByPointIdByEqpbookIds(eqpBookIds);
            Map<String, Map<String, String>> eqpBooksMap =
                    list.stream().collect(Collectors.toMap(e -> String.valueOf(e.get("eqp_book_id")), e -> e, (e1, e2) -> e2));
            List<String> devTypeList = new LinkedList<>();
            Set<String> devNoSet = new LinkedHashSet<>();
            Set<String> deviceSet = new LinkedHashSet<>();
            // 查询点位预置位信息
            for (String patrolPointId : patrolPointIds) {
                PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
                patrolTaskInfo.setEbookId(basedataPatrolPointPresetMap.getOrDefault(Long.valueOf(patrolPointId), basedataPatrolPresetPosMap.getOrDefault(Long.valueOf(patrolPointId),new JSONObject())).getString("eqpBookId"));
                Map<String, String> videoPos = eqpBooksMap.get(patrolTaskInfo.getEbookId());
                String type = videoPos.get("type");
                String patrolDeviceCode = videoPos.get("patrol_device_code");
                String typeEx;
                if (type.equals("13")) {
                    typeEx = "0";
                } else if (!type.equals("1") && !type.equals("2") && !type.equals("3")) {
                    typeEx = "2";
                } else {
                    typeEx = "1";
                }
                patrolTaskInfo.setDeviceId(patrolPointId);
                patrolTaskInfo.setDeviceName(patrolPointIdMap.getOrDefault(Long.valueOf(patrolPointId), new JSONObject()).getString("patrolPointName"));
                patrolTaskInfo.setComponentId(patrolPointIdMap.getOrDefault(Long.valueOf(patrolPointId), new JSONObject()).getString("relationDeviceId"));
//                patrolTaskInfo.setComponentName();
//                patrolTaskInfo.setBayId();
//                patrolTaskInfo.setBayName();
                patrolTaskInfo.setMainDeviceId(patrolPointIdMap.getOrDefault(Long.valueOf(patrolPointId), new JSONObject()).getString("relationMainDeviceId"));
//                patrolTaskInfo.setMainDeviceName();
                patrolTaskInfo.setDevNo(patrolDeviceCode);
                patrolTaskInfo.setDevType(typeEx);
                patrolTaskInfo.setPresetCode(basedataPatrolPointPresetMap.getOrDefault(Long.valueOf(patrolPointId), basedataPatrolPresetPosMap.getOrDefault(Long.valueOf(patrolPointId),new JSONObject())).getString("presetCode"));
                patrolTaskInfo.setEbookName(videoPos.getOrDefault("patrol_device_name", ""));
//                patrolTaskInfoService.insertPatrolTaskInfo(patrolTaskInfo);
                if (devNoSet.add(patrolTaskInfo.getDevNo())) {
                    devTypeList.add(patrolTaskInfo.getDevType());
                }
                deviceSet.add(patrolTaskInfo.getMainDeviceId());
                taskInfos.add(patrolTaskInfo);
            }
            patrolTask.setDevType(StringUtils.join(devTypeList, ","));
            patrolTask.setDevNo(StringUtils.join(devNoSet, ","));
            patrolTask.setDeviceList(StringUtils.join(deviceSet, ","));

        }
        logger.info("任务新增，patrolTask {}",patrolTask);
        int majorId = patrolTaskService.insertPatrolTask(patrolTask);
        patrolTaskIds.add(majorId + "");
        logger.info("============任务新增成功=======");
        PatrolTask patrolTaskTemp = patrolTaskService.selectPatrolTaskByTaskId((long) majorId);
        patrolTaskTemp.setTaskCode(patrolTaskTemp.getTaskId() + "");
        patrolTaskService.updatePatrolTask(patrolTaskTemp);

        patrolTask.setTaskCode(patrolTaskTemp.getTaskCode());
        for (PatrolTaskInfo taskInfo : taskInfos) {
            taskInfo.setTaskMajorId(majorId + "");
        }
        patrolTaskInfoService.batchInsertPatrolTaskInfo(taskInfos);

        try {
            logger.info("-----------------patrolTask start");
            issueTask(patrolTask);
            logger.info("-----------------patrolTask end");
        } catch (Exception e) {
            logger.info("error", e);
        }

        return AjaxResult.success(String.join(StringUtils.COMMA, patrolTaskIds));
    }

    private void toPatrolTask(JSONObject jsonObject, PatrolTask patrolTask) {
        String jsonObjectString;

        if (jsonObject.get("deviceType") != null) {
            jsonObjectString = jsonObject.get("deviceType").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setDeviceType(jsonObjectString);
            }
        }

        if (jsonObject.get("pointType") != null) {
            jsonObjectString = jsonObject.get("pointType").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setPointType(jsonObjectString);
            }
        }

        if (jsonObject.get("taskId") != null) {
            jsonObjectString = jsonObject.get("taskId").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setTaskId(Long.valueOf(jsonObjectString));
                patrolTask.setCreateTime(patrolTaskService.selectPatrolTaskByTaskId(Long.valueOf(jsonObjectString)).getCreateTime());
            }
        }

        if (jsonObject.get("stationName") != null) {
            jsonObjectString = jsonObject.get("stationName").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setStationName(jsonObjectString);
            }
        }

        if (jsonObject.get("areaId") != null) {
            jsonObjectString = jsonObject.get("areaId").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setAreaId(jsonObjectString);
            }
        }

        if (jsonObject.get("areaName") != null) {
            jsonObjectString = jsonObject.get("areaName").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setAreaName(jsonObjectString);
            }
        }

        if (jsonObject.get("stationCode") != null) {
            jsonObjectString = jsonObject.get("stationCode").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setStationCode(jsonObjectString);
            }
        }

        if (jsonObject.get("type") != null) {
            jsonObjectString = jsonObject.get("type").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setType(jsonObjectString);
            }
        }

        if (jsonObject.get("taskCode") != null) {
            jsonObjectString = jsonObject.get("taskCode").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setTaskCode(jsonObjectString);
            }
        }

        if (jsonObject.get("taskName") != null) {
            jsonObjectString = jsonObject.get("taskName").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setTaskName(jsonObjectString);
            }
        }

        if (jsonObject.get("priority") != null) {
            jsonObjectString = jsonObject.get("priority").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setPriority(jsonObjectString);
            }
        }

        if (jsonObject.get("deviceLevel") != null) {
            jsonObjectString = jsonObject.get("deviceLevel").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setDeviceLevel(jsonObjectString);
            }
        }

        if (jsonObject.get("deviceList") != null) {
            jsonObjectString = jsonObject.get("deviceList").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setDeviceList(jsonObjectString);
            }
        }

        if (jsonObject.get("fixedStartTime") != null) {
            jsonObjectString = jsonObject.get("fixedStartTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setFixedStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
            }
        }

        if (jsonObject.get("cycleMonth") != null) {
            jsonObjectString = jsonObject.get("cycleMonth").toString();
            if (jsonObjectString != null && StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setCycleMonth(jsonObjectString);
            }
        }

        if (jsonObject.get("cycleWeek") != null) {
            jsonObjectString = jsonObject.get("cycleWeek").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setCycleWeek(jsonObjectString);
            }
        }

        if (jsonObject.get("cycleExecuteTime") != null) {
            jsonObjectString = jsonObject.get("cycleExecuteTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setCycleExecuteTime(jsonObjectString);
            }
        }

        if (jsonObject.get("cycleStartTime") != null) {
            jsonObjectString = jsonObject.get("cycleStartTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setCycleStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
            }
        }

        if (jsonObject.get("cycleEndTime") != null) {
            jsonObjectString = jsonObject.get("cycleEndTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setCycleEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
            }
        }

        if (jsonObject.get("intervalNumber") != null) {
            jsonObjectString = jsonObject.get("intervalNumber").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setIntervalNumber(Integer.parseInt(jsonObjectString));
            }
        }

        if (jsonObject.get("intervalType") != null) {
            jsonObjectString = jsonObject.get("intervalType").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setIntervalType(jsonObjectString);
            }
        }

        if (jsonObject.get("intervalExecuteTime") != null) {
            jsonObjectString = jsonObject.get("intervalExecuteTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setIntervalExecuteTime(jsonObjectString);
            }
        }

        if (jsonObject.get("intervalStartTime") != null) {
            jsonObjectString = jsonObject.get("intervalStartTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setIntervalStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
            }
        }

        if (jsonObject.get("intervalEndTime") != null) {
            jsonObjectString = jsonObject.get("intervalEndTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setIntervalEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
            }
        }

        if (jsonObject.get("invalidStartTime") != null) {
            jsonObjectString = jsonObject.get("invalidStartTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setInvalidStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
            }
        }

        if (jsonObject.get("invalidEndTime") != null) {
            jsonObjectString = jsonObject.get("invalidEndTime").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setInvalidEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
            }
        }

        if (jsonObject.get("isenable") != null) {
            jsonObjectString = jsonObject.get("isenable").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setIsEnable(jsonObjectString);
            }
        }

        if (jsonObject.get("devType") != null) {
            jsonObjectString = jsonObject.get("devType").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setDevType(jsonObjectString);
            }
        }

        if (jsonObject.get("creator") != null) {
            jsonObjectString = jsonObject.get("creator").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setDrafter(jsonObjectString);
            }
        }

        if (jsonObject.get("executionStatus") != null) {
            jsonObjectString = jsonObject.get("executionStatus").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setExecutionStatus(jsonObjectString);
            }
        }

        if (jsonObject.get("taskCycle") != null) {
            jsonObjectString = jsonObject.get("taskCycle").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setTaskCycle(jsonObjectString);
            }
        }

        if (jsonObject.get("devNo") != null) {
            jsonObjectString = jsonObject.get("devNo").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setDevNo(jsonObjectString);
            }
        }

        if (jsonObject.get("executionMode") != null) {
            jsonObjectString = jsonObject.get("executionMode").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setExecutionMode(jsonObjectString);
            }
        }

        if (jsonObject.get("linkageState") != null) {
            jsonObjectString = jsonObject.get("linkageState").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setLinkageState(jsonObjectString);
            }
        }

        if (jsonObject.get("areaIdS") != null) {
            jsonObjectString = jsonObject.get("areaIdS").toString();
            if (jsonObjectString != null && StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setAreaIdS(jsonObjectString);
                // 用新的区域树
                String areaNameS = getAreaNameSByAreaIdSRelation(jsonObjectString);
                patrolTask.setAreaName(areaNameS);
            }
        }

        if (jsonObject.get("taskId") != null) {
            jsonObjectString = jsonObject.get("taskId").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setTaskId(Long.valueOf(jsonObjectString));
            }
        }

        if (jsonObject.get("cycleMonth") != null) {
            jsonObjectString = jsonObject.get("cycleMonth").toString();
            if (StringUtils.isNotEmpty(jsonObjectString)) {
                patrolTask.setCycleMonth(jsonObjectString);
            }
        }


        if (StringUtils.isNotEmpty(patrolTask.getCycleMonth())) {
            final String cycleMonth = toCycleMonth(patrolTask.getCycleMonth());
            if (StringUtils.isNotEmpty(cycleMonth)) {
                patrolTask.setCycleMonth(cycleMonth);
            }
        }

        String executionType = "1";
        if (jsonObject.get("executionType") != null) {
            executionType = jsonObject.get("executionType").toString();
        }

        if ("2".equals(executionType) || "3".equals(executionType)) {
            patrolTask.setFixedStartTime(null);
        }
    }

    @PostMapping({"/shaoxing/save"})
    @ResponseBody
    public AjaxResult save_shaoxing(@RequestBody String message) {
        try {
            logger.info("message: {}", message);
            int a = 1;
            if (StringUtils.isNotEmpty(message)) {
                JSONObject parseObject = JSONObject.parseObject(message);
                PatrolTask patrolTask = new PatrolTask();
                toPatrolTask(parseObject, patrolTask);
                String key = redisService.getCacheObjectOfTask(RedisConst.TASK_CURRENT_CODE, String.valueOf(patrolTask.getTaskId()));
                if (key != null && key.contains(String.valueOf(patrolTask.getTaskId()))) {
                    return AjaxResult.error("任务正在执行，禁止修改！");
                }

                patrolTask.setStorage(message);
                String cycleMonthText;
                if (StringUtils.isNotEmpty(patrolTask.getCycleMonth())) {
                    cycleMonthText = toCycleMonth(patrolTask.getCycleMonth());
                    if (StringUtils.isNotEmpty(cycleMonthText)) {
                        patrolTask.setCycleMonth(cycleMonthText);
                    }
                }
                String executionTypeText = "";
                if (parseObject.get("executionType") != null) {
                    executionTypeText = parseObject.get("executionType").toString();
                }
                if ("2".equals(executionTypeText) || "3".equals(executionTypeText)) {
                    patrolTask.setFixedStartTime(null);
                    patrolTaskService.updatePatrolTaskTime(patrolTask.getTaskId().toString());
                }


                Long majorId = patrolTask.getTaskId();
                patrolTask.setTaskCode(patrolTask.getTaskId() + "");
                patrolTaskInfoService.deletePatrolTaskInfoByMajorId(majorId);
                // 点位信息
                List<String> patrolPointIds = new ArrayList<>();
                if (parseObject.get("patrolPointIds") != null) {
                    String jsonObjectString = parseObject.get("patrolPointIds").toString();
                    if (StringUtils.isNotEmpty(jsonObjectString)) {
                        String[] pointArr = jsonObjectString.split(",");
                        patrolPointIds = Arrays.asList(pointArr);
                    }
                }
                List<PatrolTaskInfo> taskInfos = new ArrayList<>();
                if (patrolPointIds.size() > 0) {
                    // 查询点位信息
                    List<JSONObject> patrolPointList = patrolTaskService.selectBasedataPatrolPointList(patrolPointIds);
                    Map<Long, JSONObject> patrolPointIdMap = patrolPointList.stream().collect(Collectors.toMap(item -> item.getLong("patrolPointId"), Function.identity()));
                    // 查询点位预置位信息
                    List<JSONObject> basedataPatrolPointPresetList = patrolTaskService.selectBasedataPatrolPointPresetList(patrolPointIds);
                    Map<Long, JSONObject> basedataPatrolPointPresetMap = basedataPatrolPointPresetList.stream().collect(Collectors.toMap(item -> item.getLong("patrolPointId"), Function.identity(), (e1, e2) -> e2));
                    // 查询点位预置位位置信息
                    List<JSONObject> basedataPatrolPresetPosList = patrolTaskService.selectPatrolPresetPosList(patrolPointIds);
                    Map<Long, JSONObject> basedataPatrolPresetPosMap = basedataPatrolPresetPosList.stream().collect(Collectors.toMap(item -> item.getLong("patrolPointId"), Function.identity(), (e1, e2) -> e2));
                    Set<String> eqpBookIdPreset = basedataPatrolPointPresetList.stream().map(basedataPatrolPointPresetJson -> {
                        return basedataPatrolPointPresetJson.getString("eqpBookId");
                    }).collect(Collectors.toSet());
                    Set<String> eqpBookIdPos = basedataPatrolPresetPosList.stream().map(basedataPatrolPresetPosJson -> {
                        return basedataPatrolPresetPosJson.getString("eqpBookId");
                    }).collect(Collectors.toSet());
                    List<String> eqpBookIds = new ArrayList<>();
                    eqpBookIds.addAll(eqpBookIdPreset);
                    eqpBookIds.addAll(eqpBookIdPos);
                    // 查询设备信息
                    List<Map<String, String>> list = patrolTaskInfoService.selectVideoPosByPointIdByEqpbookIds(eqpBookIds);
                    Map<String, Map<String, String>> eqpBooksMap =
                            list.stream().collect(Collectors.toMap(e -> String.valueOf(e.get("eqp_book_id")), e -> e, (e1, e2) -> e2));
                    List<String> devTypeList = new LinkedList<>();
                    Set<String> devNoSet = new LinkedHashSet<>();
                    Set<String> deviceSet = new LinkedHashSet<>();
                    // 查询点位预置位信息
                    for (String patrolPointId : patrolPointIds) {
                        PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
                        patrolTaskInfo.setEbookId(basedataPatrolPointPresetMap.getOrDefault(Long.valueOf(patrolPointId), basedataPatrolPresetPosMap.getOrDefault(Long.valueOf(patrolPointId),new JSONObject())).getString("eqpBookId"));
                        Map<String, String> videoPos = eqpBooksMap.get(patrolTaskInfo.getEbookId());
                        String type = videoPos.get("type");
                        String patrolDeviceCode = videoPos.get("patrol_device_code");
                        String typeEx;
                        if (type.equals("13")) {
                            typeEx = "0";
                        } else if (!type.equals("1") && !type.equals("2") && !type.equals("3")) {
                            typeEx = "2";
                        } else {
                            typeEx = "1";
                        }
                        patrolTaskInfo.setDeviceId(patrolPointId);
                        patrolTaskInfo.setDeviceName(patrolPointIdMap.getOrDefault(Long.valueOf(patrolPointId), new JSONObject()).getString("patrolPointName"));
                        patrolTaskInfo.setComponentId(patrolPointIdMap.getOrDefault(Long.valueOf(patrolPointId), new JSONObject()).getString("relationDeviceId"));
//                patrolTaskInfo.setComponentName();
//                patrolTaskInfo.setBayId();
//                patrolTaskInfo.setBayName();
                        patrolTaskInfo.setMainDeviceId(patrolPointIdMap.getOrDefault(Long.valueOf(patrolPointId), new JSONObject()).getString("relationMainDeviceId"));
//                patrolTaskInfo.setMainDeviceName();
                        patrolTaskInfo.setDevNo(patrolDeviceCode);
                        patrolTaskInfo.setDevType(typeEx);
                        patrolTaskInfo.setPresetCode(basedataPatrolPointPresetMap.getOrDefault(Long.valueOf(patrolPointId), basedataPatrolPresetPosMap.getOrDefault(Long.valueOf(patrolPointId),new JSONObject())).getString("presetCode"));
                        patrolTaskInfo.setEbookName(videoPos.getOrDefault("patrol_device_name", ""));
//                patrolTaskInfoService.insertPatrolTaskInfo(patrolTaskInfo);
                        if (devNoSet.add(patrolTaskInfo.getDevNo())) {
                            devTypeList.add(patrolTaskInfo.getDevType());
                        }
                        deviceSet.add(patrolTaskInfo.getMainDeviceId());
                        taskInfos.add(patrolTaskInfo);
                    }
                    patrolTask.setDevType(StringUtils.join(devTypeList, ","));
                    patrolTask.setDevNo(StringUtils.join(devNoSet, ","));
                    patrolTask.setDeviceList(StringUtils.join(deviceSet, ","));

                }
                patrolTaskService.updatePatrolTask(patrolTask);
                for (PatrolTaskInfo taskInfo : taskInfos) {
                    taskInfo.setTaskMajorId(majorId + "");
                }
                patrolTaskInfoService.batchInsertPatrolTaskInfo(taskInfos);
                issueTask(patrolTask);
                // 修改任务，删除原有的任务执行策略，根据新的策略重新生成
                if (StringUtils.isNotEmpty(patrolTask.getTaskCode())) {
                    Collection<String> redisKeys = redisService.keys(RedisConst.TASK_CODE + patrolTask.getTaskCode() + StringUtils.AT + "*");
                    for (String redisKey : redisKeys) {
                        redisService.deleteObject(redisKey);
                    }
                }
            }
            return toAjax(a);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return toAjax(0);
    }


    @PostMapping({"/add"})
    @ResponseBody
    public AjaxResult add(@RequestBody String message) {
        logger.info("[TASK] add message: {}", message);
        List<String> patrolTaskIds = new ArrayList<>();
        if (StringUtils.isEmpty(message)) {
            return AjaxResult.success(String.join(StringUtils.COMMA, patrolTaskIds));
        }
        JSONObject parseObject = JSONObject.parseObject(message);
        Object taskIsPoint = parseObject.get("taskIsPoint");
        Object isUp = parseObject.get("isUp");
        String jsonText = "";
        List<PatrolTask> patrolTaskList = new ArrayList<>();
        if (taskIsPoint != null) {
            if (taskIsPoint.toString().equals("1")) {
                jsonText = message;
                patrolTaskList = toPatrolTaskList(parseObject, taskIsPoint.toString());
                makeupPatrolTaskDetails(patrolTaskList, taskIsPoint.toString());
            } else if (taskIsPoint.toString().equals("0")) {
                jsonText = message;
                try {
                    patrolTaskList = JSONArray.parseArray(message, PatrolTask.class);
                } catch (Exception e) {
                    logger.warn("Exception: {}", e.getMessage());
                    patrolTaskList = toPatrolTaskList(parseObject, taskIsPoint.toString());
                }
                makeupPatrolTaskDetails(patrolTaskList, taskIsPoint.toString());
            }
        } else {
            final String flag = "0";
            jsonText = message;
            try {
                patrolTaskList = JSONArray.parseArray("[" + message + "]", PatrolTask.class);
                patrolTaskList = toPatrolTaskList(parseObject, flag);
                //eqList = JSONArray.parseArray(message + "", PatrolTask.class);
            } catch (Exception e) {
                logger.warn("2 Exception: {}", e.getMessage());
                patrolTaskList = toPatrolTaskList(parseObject, flag);
            }

            makeupPatrolTaskDetails(patrolTaskList, flag);
        }

        PatrolTask patrolTask = (PatrolTask) ((List<?>) patrolTaskList).get(0);
        if (StringUtils.isNotEmpty(jsonText)) {
            patrolTask.setStorage(jsonText);
        }

        if (!patrolTaskList.isEmpty()) {
            List<PatrolTaskInfo> patrolTaskInfo = ((PatrolTask) ((List<?>) patrolTaskList).get(0)).getEqpointList();
            if (StringUtils.isNotEmpty(patrolTask.getCycleMonth())) {
                final String cycleMonth = toCycleMonth(patrolTask.getCycleMonth());
                if (StringUtils.isNotEmpty(cycleMonth)) {
                    patrolTask.setCycleMonth(cycleMonth);
                }
            }

            String executionType = "1";
            if (parseObject.get("executionType") != null) {
                executionType = parseObject.get("executionType").toString();
            }

            if ("2".equals(executionType) || "3".equals(executionType)) {
                patrolTask.setFixedStartTime(null);
            }

            int majorId = patrolTaskService.insertPatrolTask(patrolTask);
            patrolTaskIds.add(majorId + "");
            PatrolTask patrolTaskTemp = patrolTaskService.selectPatrolTaskByTaskId((long) majorId);
            if (isUp == null || StringUtils.isEmpty(isUp.toString())) {
                logger.info("[ADD] isUp is null: {}", isUp);
                patrolTaskTemp.setTaskCode(patrolTaskTemp.getTaskId() + "");
                patrolTaskService.updatePatrolTask(patrolTaskTemp);

                patrolTask.setTaskCode(patrolTaskTemp.getTaskCode());
            }

            logger.info("[ADD] patrolTaskInfo size: {}", patrolTaskInfo.size());
            for (PatrolTaskInfo info : patrolTaskInfo) {
                logger.info("[ADD] patrolTaskInfo devNo : {}", info.getDevNo());
                info.setTaskMajorId(majorId + "");
                patrolTaskInfoService.insertPatrolTaskInfo(info);
            }

//            if ("0".equals(patrolTask.getExecutionStatus())) {
            try {
                logger.info("-----------------patrolTask start");
                issueTask(patrolTask);
                logger.info("-----------------patrolTask end");
            } catch (Exception e) {
                logger.info("error", e);
            }
//            }
        }

        return AjaxResult.success(String.join(StringUtils.COMMA, patrolTaskIds));
    }

    @PostMapping({"/save"})
    @ResponseBody
    public AjaxResult save(@RequestBody String message) {
        try {
            logger.info("message: {}", message);
            int a = 1;
            if (StringUtils.isNotEmpty(message)) {
                JSONObject parseObject = JSONObject.parseObject(message);
                final String flag = "0";
                List<PatrolTask> eqList = toPatrolTaskList(parseObject, flag);
                makeupPatrolTaskDetails(eqList, flag);
                PatrolTask patrolTask = eqList.get(0);
                String key = redisService.getCacheObjectOfTask(RedisConst.TASK_CURRENT_CODE, String.valueOf(patrolTask.getTaskId()));
                if (key != null && key.contains(String.valueOf(patrolTask.getTaskId()))) {
                    return AjaxResult.error("任务正在执行，禁止修改！");
                }

                if (!eqList.isEmpty()) {
                    patrolTask.setStorage(message);
                    String cycleMonthText;
                    if (StringUtils.isNotEmpty(patrolTask.getCycleMonth())) {
                        cycleMonthText = toCycleMonth(patrolTask.getCycleMonth());
                        if (StringUtils.isNotEmpty(cycleMonthText)) {
                            patrolTask.setCycleMonth(cycleMonthText);
                        }
                    }
                    String executionTypeText = "";
                    if (parseObject.get("executionType") != null) {
                        executionTypeText = parseObject.get("executionType").toString();
                    }
                    if ("2".equals(executionTypeText) || "3".equals(executionTypeText)) {
                        patrolTask.setFixedStartTime(null);
                        patrolTaskService.updatePatrolTaskTime(patrolTask.getTaskId().toString());
                    }

                    patrolTaskService.updatePatrolTask(patrolTask);
                    // 修改新增一条新任务
//                    int taskId = patrolTaskService.insertPatrolTask(patrolTask);
                    Long majorId = patrolTask.getTaskId();
                    PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
                    patrolTaskInfo.setTaskMajorId(majorId + "");
                    patrolTaskInfoService.deletePatrolTaskInfoByMajorId(majorId);
//                    List<PatrolTaskInfo> infolist = patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
//                    if (!infolist.isEmpty()) {
//                        for (PatrolTaskInfo arr : infolist) {
//                            patrolTaskInfoService.deletePatrolTaskInfoByLineId(arr.getLineId());
//                        }
//                    }
//                    patrolTask.setTaskId((long) taskId);
                    if (patrolTask.getIsUp() == null || StringUtils.isEmpty(patrolTask.getIsUp())) {
//                        PatrolTask patrolTaskTemp = patrolTaskService.selectPatrolTaskByTaskId((long) taskId);
//                        patrolTaskTemp.setTaskCode(patrolTaskTemp.getTaskId() + "");
//                        patrolTaskService.updatePatrolTask(patrolTaskTemp);
                        patrolTask.setTaskCode(patrolTask.getTaskId() + "");
                    }
                    List<PrevPoint> prevPoints = patrolTask.getPrevPoints();
                    List<String> eqpBookIds = prevPoints.parallelStream().map(PrevPoint::getEqpBookId).collect(Collectors.toList());
                    List<String> parentIds = prevPoints.parallelStream().map(PrevPoint::getParentId)
                            .filter(Objects::nonNull)
                            .filter((item) -> item.contains(StringUtils.DASH))
                            .map((item) -> item.split(StringUtils.DASH)[1])
                            .collect(Collectors.toList());
                    List<Map<String, String>> list = new ArrayList<>();
                    Map<String, Map<String, String>> eqpBooksMap = new HashMap<>();
                    if (eqpBookIds.size() > 0) {
                        list = patrolTaskInfoService.selectVideoPosByPointIdByEqpbookIds(eqpBookIds);
                        eqpBooksMap = list.stream().collect(Collectors.toMap(e -> String.valueOf(e.get("eqp_book_id")), e -> e, (e1, e2) -> e2));
                    }
                    List<PatrolTaskInfo> patrolTaskInfoListDb = new ArrayList<>();
                    Map<String, PatrolTaskInfo> patrolTaskInfoMap = new HashMap<>();
                    if (parentIds.size() > 0) {
                        patrolTaskInfoListDb = patrolTaskInfoService.selectTaskInfoByBaseIds(parentIds);
                        patrolTaskInfoMap = patrolTaskInfoListDb.stream().collect(Collectors.toMap(PatrolTaskInfo::getDeviceId, e -> e, (e1, e2) -> e2));
                    }
                    List<PatrolTaskInfo> patrolTaskInfos = new ArrayList<>();
                    for (PrevPoint prevPoint : prevPoints) {
//                        Map<String, String> videoPos = patrolTaskInfoService.selectVideoPosByPointId(prevPoint.getEqpBookId());
                        Map<String, String> videoPos = eqpBooksMap.get(prevPoint.getEqpBookId());
                        String type = videoPos.get("type");
                        String patrolDeviceCode = videoPos.get("patrol_device_code");
                        String typeEx;
                        if (type.equals("13")) {
                            typeEx = "0";
                        } else if (!type.equals("1") && !type.equals("2") && !type.equals("3")) {
                            typeEx = "2";
                        } else {
                            typeEx = "1";
                        }

                        if (prevPoint.getParentId().contains(StringUtils.DASH)) {
                            String[] str = prevPoint.getParentId().split(StringUtils.DASH);
//                            PatrolTaskInfo patrolInfo = patrolTaskInfoService.selectTaskInfoByBaseId(str[1]);
                            PatrolTaskInfo patrolInfo = patrolTaskInfoMap.get(str[1]);
                            patrolInfo.setTaskMajorId(String.valueOf(majorId));
                            patrolInfo.setPresetCode(prevPoint.getPresetCode());
                            patrolInfo.setDeviceId(str[1]);
                            patrolInfo.setDevType(typeEx);
                            patrolInfo.setDevNo(patrolDeviceCode);
                            patrolInfo.setParentId(prevPoint.getParentId());
                            patrolInfo.setEbookId(prevPoint.getEqpBookId());
                            patrolInfo.setEbookName(prevPoint.getLabel());
                            patrolInfo.setCreateTime(new Date());
                            patrolTaskInfos.add(patrolInfo);
//                            patrolTaskInfoService.insertPatrolTaskInfo(patrolInfo);
                        }
                    }
                    if (patrolTaskInfos.size() > 0) {
                        patrolTaskInfoService.batchInsertPatrolTaskInfo(patrolTaskInfos);
                    }
                }
                issueTask(patrolTask);
                // 修改任务，删除原有的任务执行策略，根据新的策略重新生成
                if (StringUtils.isNotEmpty(patrolTask.getTaskCode())) {
                    Collection<String> redisKeys = redisService.keys(RedisConst.TASK_CODE + patrolTask.getTaskCode() + StringUtils.AT + "*");
                    for (String redisKey : redisKeys) {
                        redisService.deleteObject(redisKey);
                    }
                }
            }
            return toAjax(a);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        (new Thread(() -> {
//            logger.info("[TASK] sync task to upper system start");
//            try {
//                Thread.sleep(2000L);
//                syncTaskToUpperSystem(new PatrolTask());
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            logger.info("[TASK] sync task to upper system end");
//        })).start();
        return toAjax(0);
    }

    public void split(PatrolTask patrolTask) {
        String[] cycleList = null;
        if (patrolTask.getTaskCycle().equals("0")) {
            cycleList = patrolTask.getCycleMonth().split(StringUtils.COMMA);
        } else if (patrolTask.getTaskCycle().equals("1")) {
            cycleList = patrolTask.getCycleWeek().split(StringUtils.COMMA);
        }

        for (int i = 0; i < Objects.requireNonNull(cycleList).length; ++i) {
            PatrolTaskStatus status = new PatrolTaskStatus();
            status.setTaskPatrolledId(patrolTask.getTaskId() + "");
            status.setTaskName(patrolTask.getTaskName());
            status.setTaskCode(patrolTask.getTaskCode());
            status.setPlanStartTime(patrolTask.getCycleStartTime());
            status.setPosType(patrolTask.getType());
            status.setStartTime(new Date());
            patrolTaskStatusService.insertPatrolTaskStatus(status);
        }

    }

    @GetMapping({"/issue"})
    public AjaxResult issueList(PatrolTask patrolTask) {
        PatrolTask patrolTaskEx = patrolTaskService.selectPatrolTaskByTaskId(patrolTask.getTaskId());
        issueTask(patrolTaskEx);
        return toAjax(1);
    }

    // 单个纠偏
    @PostMapping({"/correction"})
    public AjaxResult correctionAlgorithm(@RequestBody PatrolData patrolData) {
        logger.info("correctionAlgorithm patrolData: {}", patrolData);
        boolean res = patrolTaskService.correctionAlgorithm(patrolData);
        return toAjax(res);
    }

    public String calcWeekList(String week) {
        List<String> weekList = new ArrayList<>();
        if (week.contains(StringUtils.COMMA)) {
            String[] weeks = week.split(StringUtils.COMMA);

            for (String son : weeks) {
                String text = weekConvert(son);
                weekList.add(text);
            }
        } else {
            String text = weekConvert(week);
            weekList.add(text);
        }

        return String.join(StringUtils.COMMA, weekList);
    }

    public String weekConvert(String week) {
        String str = "";
        if (week.contains("一")) {
            str = "1";
        } else if (week.contains("二")) {
            str = "2";
        } else if (week.contains("三")) {
            str = "3";
        } else if (week.contains("四")) {
            str = "4";
        } else if (week.contains("五")) {
            str = "5";
        } else if (week.contains("六")) {
            str = "6";
        } else if (week.contains("日") || week.contains("七")) {
            str = "7";
        }

        return str;
    }

    public void issueTask(PatrolTask patrolTask) {
        logger.info("***************************** JobTaskTimer issueTask ************************************* patrolTask: {}", patrolTask);
        String rebootCode = patrolTaskService.selectConfigByKey("rebootCode");//robotCode
        String uavCode = patrolTaskService.selectConfigByKey("uavCode");//droneCode
        String receiveCode = "";
        String sendCode = "";
        BasedataEqpBookMoMain based = new BasedataEqpBookMoMain();
        based.setType("20");//巡视主机
        List<BasedataEqpBookMoMain> basedataEqpBookMoMains = patrolResultService.selectBasedataEqpBookList(based);
        if (!basedataEqpBookMoMains.isEmpty()) {
            sendCode = basedataEqpBookMoMains.get(0).getPatrolDeviceCode();
        }

        logger.info("-----------------patrolTask.getDevNo(): " + patrolTask.getDevNo());
        if (patrolTask.getDevNo() != null) {
            String[] devNos = patrolTask.getDevNo().split(StringUtils.COMMA);
            for (String devNo : devNos) {
                BasedataEqpBookMoMain basedataEqpbookMomain = new BasedataEqpBookMoMain();
                basedataEqpbookMomain.setPatrolDeviceCode(devNo);
                List<BasedataEqpBookMoMain> eqpBookMoMains = patrolResultService.selectBasedataEqpBookList(basedataEqpbookMomain);
                if (!eqpBookMoMains.isEmpty()) {
                    if (eqpBookMoMains.get(0).getMainSystemCode() == null) {
                        continue;
                    }

                    receiveCode = eqpBookMoMains.get(0).getMainSystemCode();
                }

                Map<String, String> stationMap = patrolResultService.selectBasedataStation();
                PatrolSendTask patrolSendTask = new PatrolSendTask();
                if (StringUtils.isNotEmpty(patrolTask.getTaskCode())) {
                    patrolSendTask.setTaskCode(patrolTask.getTaskCode());
                } else {
                    patrolSendTask.setTaskCode("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getTaskName())) {
                    patrolSendTask.setTaskName(patrolTask.getTaskName());
                } else {
                    patrolSendTask.setTaskName("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getPriority())) {
                    patrolSendTask.setPriority(patrolTask.getPriority());
                } else {
                    patrolSendTask.setPriority("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getDeviceLevel())) {
                    patrolSendTask.setDeviceLevel(patrolTask.getDeviceLevel());
                } else {
                    patrolSendTask.setDeviceLevel("3");
                }

                if (StringUtils.isNotEmpty(patrolTask.getIsUp())) {
                    if (StringUtils.isNotEmpty(patrolTask.getDeviceList())) {
                        patrolSendTask.setDeviceList(patrolTask.getDeviceList());
                    } else {
                        patrolSendTask.setDeviceList("[empty device list 1]");
                    }
                } else {
                    Map<String, List> map = patrolTaskInfoService.selectPatrolTaskInfoListByMajorId(String.valueOf(patrolTask.getTaskId()));
                    List<String> infoList = map.get("list");
                    List<String> infoListFull = map.get("listFull");
                    logger.info("[TASK] taskId1: {}, infoList1: {}, infoListFull1: {}", patrolTask.getTaskId(), infoList, infoListFull);
                    if (!infoList.isEmpty()) {
                        if (StringUtils.isNotBlank(receiveCode)) {
                            List otherDevList = new ArrayList();
                            for (int i = 0; i < infoListFull.size(); i++) {
                                String dev = infoListFull.get(i);
                                if (dev.startsWith(receiveCode)) {
                                    otherDevList.add(infoList.get(i));
                                }
                            }
                            patrolSendTask.setDeviceList(String.join(StringUtils.COMMA, otherDevList));
                        } else {
                            List selfDevList = new ArrayList();
                            for (int i = 0; i < infoListFull.size(); i++) {
                                String dev = infoListFull.get(i);
                                selfDevList.add(infoListFull.get(i));
                            }
                            patrolSendTask.setDeviceList(String.join(StringUtils.COMMA, selfDevList));
                        }
                    } else {
                        patrolSendTask.setDeviceList("[empty device list 2]");
                    }
                }

                if (patrolTask.getFixedStartTime() != null) {
                    patrolSendTask.setFixedStartTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getFixedStartTime()));
                } else {
                    patrolSendTask.setFixedStartTime("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getCycleMonth())) {
                    patrolSendTask.setCycleMonth(patrolTask.getCycleMonth());
                } else {
                    patrolSendTask.setCycleMonth("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getCycleWeek())) {
                    patrolSendTask.setCycleWeek(calcWeekList(patrolTask.getCycleWeek()));
                } else {
                    patrolSendTask.setCycleWeek("");
                }

                if (patrolTask.getCycleExecuteTime() != null) {
                    patrolSendTask.setCycleExecuteTime(patrolTask.getCycleExecuteTime());
                } else {
                    patrolSendTask.setCycleExecuteTime("");
                }

                if (patrolTask.getCycleStartTime() != null) {
                    patrolSendTask.setCycleStartTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getCycleStartTime()));
                } else {
                    patrolSendTask.setCycleStartTime("");
                }

                if (patrolTask.getCycleEndTime() != null) {
                    patrolSendTask.setCycleEndTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getCycleEndTime()));
                } else {
                    patrolSendTask.setCycleEndTime("");
                }

                if (patrolTask.getIntervalNumber() != 0) {
                    patrolSendTask.setIntervalNumber(patrolTask.getIntervalNumber() + "");
                } else {
                    patrolSendTask.setIntervalNumber("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getIntervalExecuteTime())) {
                    patrolSendTask.setIntervalExecuteTime(patrolTask.getIntervalExecuteTime());
                    if (StringUtils.isNotEmpty(patrolTask.getIntervalType())) {
                        patrolSendTask.setIntervalType(patrolTask.getIntervalType());
                    }
                } else {
                    patrolSendTask.setIntervalExecuteTime("");
                    patrolSendTask.setIntervalType("");
                }

                if (patrolTask.getIntervalStartTime() != null) {
                    patrolSendTask.setIntervalStartTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getIntervalStartTime()));
                } else {
                    patrolSendTask.setIntervalStartTime("");
                }

                if (patrolTask.getIntervalEndTime() != null) {
                    patrolSendTask.setIntervalEndTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getIntervalEndTime()));
                } else {
                    patrolSendTask.setIntervalEndTime("");
                }

                if (patrolTask.getInvalidStartTime() != null) {
                    patrolSendTask.setInvalidStartTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getInvalidStartTime()));
                } else {
                    patrolSendTask.setInvalidStartTime("");
                }

                if (patrolTask.getInvalidEndTime() != null) {
                    patrolSendTask.setInvalidEndTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getInvalidEndTime()));
                } else {
                    patrolSendTask.setInvalidEndTime("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getIsEnable())) {
                    patrolSendTask.setIsEnable(patrolTask.getIsEnable());
                } else {
                    patrolSendTask.setIsEnable("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getDrafter())) {
                    patrolSendTask.setCreator(patrolTask.getDrafter());
                } else {
                    patrolSendTask.setCreator("");
                }

                if (patrolTask.getCreateTime() != null) {
                    patrolSendTask.setCreateTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getCreateTime()));
                } else {
                    patrolSendTask.setCreateTime("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getType())) {
                    patrolSendTask.setType(patrolTask.getType());
                } else {
                    patrolSendTask.setType("");
                }

                patrolSendTask = handleFixTypeTask(patrolSendTask);
                List<PatrolSendTask> list = new ArrayList<>();
                list.add(patrolSendTask);
                SendTask sendTask = new SendTask();
                sendTask.setSendCode(sendCode);
                sendTask.setReceiveCode(receiveCode);
                sendTask.setCommand("1");
                sendTask.setType("101");
                sendTask.setItems(list);
                if (stationMap != null && stationMap.get("station_no") != null) {
                    sendTask.setCode(stationMap.get("station_no"));
                }

                String str = JSONObject.toJSONString(sendTask);
                logger.info("-----------------sendTask: " + str);
                if (StringUtils.isEmpty(receiveCode)) {
                    //手工巡视任务会进入这里，不下发
                    continue;
                }
                feignTaskClient.sendCommand(str);
//                if (receiveCode.startsWith("Client05")) {
//                    // 无人机下发逻辑和机器狗，滤波器保持一致
//                    SendTask sendTaskClient = new SendTask();
//                    sendTaskClient.setSendCode(sendCode);
//                    sendTaskClient.setCode(patrolTask.getTaskId() + "");
//                    sendTaskClient.setReceiveCode(receiveCode);
//                    sendTaskClient.setCommand("1");
//                    sendTaskClient.setType("41");
//                    String s = JSONObject.toJSONString(sendTaskClient);
//                    this.feignTaskClient.sendCommand(s);
//                }
            }
        } else {
            BasedataEqpBookMoMain basedataEqpbookMomain = new BasedataEqpBookMoMain();
            basedataEqpbookMomain.setPatrolDeviceCode(patrolTask.getDevNo());
            List<BasedataEqpBookMoMain> basedataEqpBookMoMains1 = patrolResultService.selectBasedataEqpBookList(basedataEqpbookMomain);
            if (!basedataEqpBookMoMains1.isEmpty() && basedataEqpBookMoMains1.get(0).getMainSystemCode() != null) {
                receiveCode = basedataEqpBookMoMains1.get(0).getMainSystemCode();
            }


            Map<String, String> stringMap = patrolResultService.selectBasedataStation();
            PatrolSendTask patrolSendTask = new PatrolSendTask();
            if (StringUtils.isNotEmpty(patrolTask.getTaskCode())) {
                patrolSendTask.setTaskCode(patrolTask.getTaskCode());
            } else {
                patrolSendTask.setTaskCode("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getTaskName())) {
                patrolSendTask.setTaskName(patrolTask.getTaskName());
            } else {
                patrolSendTask.setTaskName("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getPriority())) {
                patrolSendTask.setPriority(patrolTask.getPriority());
            } else {
                patrolSendTask.setPriority("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getDeviceLevel())) {
                patrolSendTask.setDeviceLevel(patrolTask.getDeviceLevel());
            } else {
                patrolSendTask.setDeviceLevel("3");
            }

            if (StringUtils.isNotEmpty(patrolTask.getIsUp())) {
                if (StringUtils.isNotEmpty(patrolTask.getDeviceList())) {
                    patrolSendTask.setDeviceList(patrolTask.getDeviceList());
                } else {
                    patrolSendTask.setDeviceList("[empty device list 3]");
                }
            } else {
                Map<String, List> map = patrolTaskInfoService.selectPatrolTaskInfoListByMajorId(String.valueOf(patrolTask.getTaskId()));
                List<String> infoList = map.get("list");
                List<String> infoListFull = map.get("listFull");
                logger.info("[TASK] taskId2: {}, infoList2: {}, infoListFull2: {}", patrolTask.getTaskId(), infoList, infoListFull);
                if (!infoList.isEmpty()) {
                    if (StringUtils.isNotBlank(receiveCode)) {
                        List otherDevList = new ArrayList();
                        for (int i = 0; i < infoListFull.size(); i++) {
                            String dev = infoListFull.get(i);
                            if (dev.startsWith(receiveCode)) {
                                otherDevList.add(infoList.get(i));
                            }
                        }
                        patrolSendTask.setDeviceList(String.join(StringUtils.COMMA, otherDevList));
                    } else {
                        List selfDevList = new ArrayList();
                        for (int i = 0; i < infoListFull.size(); i++) {
                            String dev = infoListFull.get(i);
                            selfDevList.add(infoListFull.get(i));
                        }
                        patrolSendTask.setDeviceList(String.join(StringUtils.COMMA, selfDevList));
                    }
                } else {
                    patrolSendTask.setDeviceList("[empty device list 4]");
                }
            }

            if (patrolTask.getFixedStartTime() != null) {
                patrolSendTask.setFixedStartTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getFixedStartTime()));
            } else {
                patrolSendTask.setFixedStartTime("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getCycleMonth())) {
                patrolSendTask.setCycleMonth(patrolTask.getCycleMonth());
            } else {
                patrolSendTask.setCycleMonth("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getCycleWeek())) {
                patrolSendTask.setCycleWeek(calcWeekList(patrolTask.getCycleWeek()));
            } else {
                patrolSendTask.setCycleWeek("");
            }

            if (patrolTask.getCycleExecuteTime() != null) {
                patrolSendTask.setCycleExecuteTime(patrolTask.getCycleExecuteTime());
            } else {
                patrolSendTask.setCycleExecuteTime("");
            }

            if (patrolTask.getCycleStartTime() != null) {
                patrolSendTask.setCycleStartTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getCycleStartTime()));
            } else {
                patrolSendTask.setCycleStartTime("");
            }

            if (patrolTask.getCycleEndTime() != null) {
                patrolSendTask.setCycleEndTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getCycleEndTime()));
            } else {
                patrolSendTask.setCycleEndTime("");
            }

            if (patrolTask.getIntervalNumber() != 0) {
                patrolSendTask.setIntervalNumber(patrolTask.getIntervalNumber() + "");
            } else {
                patrolSendTask.setIntervalNumber("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getIntervalExecuteTime())) {
                patrolSendTask.setIntervalExecuteTime(patrolTask.getIntervalExecuteTime());
                if (StringUtils.isNotEmpty(patrolTask.getIntervalType())) {
                    patrolSendTask.setIntervalType(patrolTask.getIntervalType());
                }
            } else {
                patrolSendTask.setIntervalExecuteTime("");
                patrolSendTask.setIntervalType("");
            }

            if (patrolTask.getIntervalStartTime() != null) {
                patrolSendTask.setIntervalStartTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getIntervalStartTime()));
            } else {
                patrolSendTask.setIntervalStartTime("");
            }

            if (patrolTask.getIntervalEndTime() != null) {
                patrolSendTask.setIntervalEndTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getIntervalEndTime()));
            } else {
                patrolSendTask.setIntervalEndTime("");
            }

            if (patrolTask.getInvalidStartTime() != null) {
                patrolSendTask.setInvalidStartTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getInvalidStartTime()));
            } else {
                patrolSendTask.setInvalidStartTime("");
            }

            if (patrolTask.getInvalidEndTime() != null) {
                patrolSendTask.setInvalidEndTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getInvalidEndTime()));
            } else {
                patrolSendTask.setInvalidEndTime("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getIsEnable())) {
                patrolSendTask.setIsEnable(patrolTask.getIsEnable());
            } else {
                patrolSendTask.setIsEnable("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getDrafter())) {
                patrolSendTask.setCreator(patrolTask.getDrafter());
            } else {
                patrolSendTask.setCreator("");
            }

            if (patrolTask.getCreateTime() != null) {
                patrolSendTask.setCreateTime(DateUtils.format(DateUtils.yyyyMMddHHmmss2, patrolTask.getCreateTime()));
            } else {
                patrolSendTask.setCreateTime("");
            }

            if (StringUtils.isNotEmpty(patrolTask.getType())) {
                patrolSendTask.setType(patrolTask.getType());
            } else {
                patrolSendTask.setType("");
            }

            patrolSendTask = handleFixTypeTask(patrolSendTask);
            List<PatrolSendTask> list = new ArrayList<>();
            list.add(patrolSendTask);
            SendTask sendTask = new SendTask();
            sendTask.setSendCode(sendCode);
            sendTask.setReceiveCode(receiveCode);
            sendTask.setCode(patrolTask.getTaskCode());
            sendTask.setCommand("1");
            sendTask.setType("101");
            sendTask.setItems(list);
            if (stringMap != null && stringMap.get("station_no") != null) {
                sendTask.setCode(stringMap.get("station_no"));
            }

            String str = JSONObject.toJSONString(sendTask);
            System.out.println(str);
            if (StringUtils.isEmpty(receiveCode)) {
                //手工巡视任务会进入这里，不下发
                return;
            }
            feignTaskClient.sendCommand(str);
//            if (receiveCode.startsWith("Client05")) {
//                // 无人机下发逻辑和机器狗，滤波器保持一致
//                SendTask sendTaskClient = new SendTask();
//                sendTaskClient.setSendCode(sendCode);
//                sendTaskClient.setCode(patrolTask.getTaskId() + "");
//                sendTaskClient.setReceiveCode(receiveCode);
//                sendTaskClient.setCommand("1");
//                sendTaskClient.setType("41");
//                String s = JSONObject.toJSONString(sendTaskClient);
//                this.feignTaskClient.sendCommand(s);
//            }
        }

    }

    private PatrolSendTask handleFixTypeTask(PatrolSendTask patrolSendTask) {
//        if (StringUtils.isNotEmpty(patrolSendTask.getFixedStartTime())) {
//            patrolSendTask.setCycleEndTime("");
//            patrolSendTask.setCycleExecuteTime("");
//            patrolSendTask.setCycleMonth("");
//            patrolSendTask.setCycleStartTime("");
//            patrolSendTask.setCycleWeek("");
//            patrolSendTask.setIntervalEndTime("");
//            patrolSendTask.setIntervalType("");
//            patrolSendTask.setIntervalExecuteTime("");
//            patrolSendTask.setIntervalNumber("");
//            patrolSendTask.setIntervalStartTime("");
//            patrolSendTask.setInvalidEndTime("");
//            patrolSendTask.setInvalidStartTime("");
//        }
        // 下发给机器狗，无人机普通任务
        patrolSendTask.setFixedStartTime("");
        patrolSendTask.setCycleEndTime("");
        patrolSendTask.setCycleExecuteTime("");
        patrolSendTask.setCycleMonth("");
        patrolSendTask.setCycleStartTime("");
        patrolSendTask.setCycleWeek("");
        patrolSendTask.setIntervalEndTime("");
        patrolSendTask.setIntervalType("");
        patrolSendTask.setIntervalExecuteTime("");
        patrolSendTask.setIntervalNumber("");
        patrolSendTask.setIntervalStartTime("");
        patrolSendTask.setInvalidEndTime("");
        patrolSendTask.setInvalidStartTime("");

        return patrolSendTask;
    }

    public void issueTaskByLinkage(PatrolTask patrolTask) {
        String receiveCode = "";
        String sendCode = "";
        BasedataEqpBookMoMain based = new BasedataEqpBookMoMain();
        based.setType("20");
        List<BasedataEqpBookMoMain> basedataEqpBookMoMains = patrolResultService.selectBasedataEqpBookList(based);
        if (!basedataEqpBookMoMains.isEmpty()) {
            sendCode = basedataEqpBookMoMains.get(0).getPatrolDeviceCode();
        }

        if (patrolTask.getDevNo() != null) {
            String[] ss = patrolTask.getDevNo().split(StringUtils.COMMA);

            for (String s : ss) {
                BasedataEqpBookMoMain basedataEqpbookMomain = new BasedataEqpBookMoMain();
                basedataEqpbookMomain.setPatrolDeviceCode(s);
                List<BasedataEqpBookMoMain> eqpBookMoMains = patrolResultService.selectBasedataEqpBookList(basedataEqpbookMomain);
                if (!eqpBookMoMains.isEmpty() && eqpBookMoMains.get(0).getMainSystemCode() != null) {
                    receiveCode = eqpBookMoMains.get(0).getMainSystemCode();
                }

                PatrolSendTask patrolSendTask = new PatrolSendTask();
                if (StringUtils.isNotEmpty(patrolTask.getTaskCode())) {
                    patrolSendTask.setTaskCode(patrolTask.getTaskCode());
                } else {
                    patrolSendTask.setTaskCode("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getTaskName())) {
                    patrolSendTask.setTaskName(patrolTask.getTaskName());
                } else {
                    patrolSendTask.setTaskName("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getPriority())) {
                    patrolSendTask.setPriority(patrolTask.getPriority());
                } else {
                    patrolSendTask.setPriority("");
                }

                if (StringUtils.isNotEmpty(patrolTask.getDeviceLevel())) {
                    patrolSendTask.setDeviceLevel(patrolTask.getDeviceLevel());
                } else {
                    patrolSendTask.setDeviceLevel("3");
                }

                if (StringUtils.isNotEmpty(patrolTask.getDeviceList())) {
                    patrolSendTask.setDeviceList(patrolTask.getDeviceList());
                } else {
                    patrolSendTask.setDeviceList("");
                }

                List<PatrolSendTask> list = new ArrayList<>();
                list.add(patrolSendTask);
                SendTask sendTask = new SendTask();
                sendTask.setSendCode(sendCode);
                sendTask.setReceiveCode(receiveCode);
                sendTask.setCode(patrolTask.getTaskCode());
                sendTask.setCommand("1");
                sendTask.setType("102");
                sendTask.setItems(list);
                String str = JSONObject.toJSONString(sendTask);
                System.out.println(str);
                feignTaskClient.sendCommand(str);
            }
        }

    }

    public void issueControl(PatrolTask patrolTask) {
        String rebootCode = patrolTaskService.selectConfigByKey("rebootCode");
        String uavCode = patrolTaskService.selectConfigByKey("uavCode");
        SendTask sendTask = new SendTask();
        sendTask.setSendCode(patrolTask.getDevNo());
        if (patrolTask.getDevType().equals("0")) {
            sendTask.setReceiveCode(rebootCode);
        } else if (patrolTask.getDevType().equals("1")) {
            sendTask.setReceiveCode(uavCode);
        }

        sendTask.setCode(patrolTask.getTaskCode());
        sendTask.setCommand("1");
        String str = JSONObject.toJSONString(sendTask);
        System.out.println(str);
    }

    @GetMapping("/copyTask")
    public AjaxResult list(Long taskId, String time) {
        PatrolTask task = patrolTaskService.selectPatrolTaskByTaskId(taskId);
        if (task != null) {
            PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
            patrolTaskInfo.setTaskMajorId(String.valueOf(taskId));
            PatrolTask patrolTask = new PatrolTask();
            BeanUtils.copyBeanProp(patrolTask, task);
            patrolTask.setCycleExecuteTime(time);
            int taskIdRet = patrolTaskService.insertPatrolTask(patrolTask);
            List<PatrolTaskInfo> infos = patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
            if (!infos.isEmpty()) {
                for (PatrolTaskInfo info : infos) {
                    info.setLineId(null);
                    info.setTaskMajorId(String.valueOf(taskIdRet));
                    patrolTaskInfoService.insertPatrolTaskInfo(info);
                }
            }

            return toAjax(1);
        }

        return toAjax(0);
    }

    @GetMapping({"/test"})
    public AjaxResult test() {
        String message = "[{\n    \"taskName\":\"测试任务\",\n    \"region\":100,\n    \"cycleStartTime\":\"2024/07/07\",\n    \"cycleEndTime\":\"2024/09/30\",\n    \"taskCycle\":\"1\",\n    \"cycleMonth\":\"\",\n    \"cycleWeek\":\"1\",\n    \"prevPoints\":[\n        {\n            \"id\":9,\n            \"pid\":2,\n            \"topId\":1,\n            \"label\":\"robot1\"\n        },\n        {\n            \"id\":10,\n            \"pid\":2,\n            \"topId\":1,\n            \"label\":\"Robot2\"\n        }\n    ],\n    \"cycleExecuteTime\":\"2024/07/06 15:23:32\",\n    \"taskIsPoint\":\"0\"\n}]";
        List<PatrolTask> eqList = JSONArray.parseArray(message, PatrolTask.class);
        final String flag = "0";
        makeupPatrolTaskDetails(eqList, flag);
        return AjaxResult.success(eqList);
    }

    public void makeupPatrolTaskDetails(List<PatrolTask> patrolTaskList, String flag) {
        logger.info("[TASK] flag: {}", flag);
        Set<String> eqpBookIdSet = new HashSet<>();
        List<PrevPoint> prevPointList = patrolTaskList.get(0).getPrevPoints();
        if (prevPointList != null && !prevPointList.isEmpty()) {
            for (PrevPoint prevPoint : prevPointList) {
                if (StringUtils.isNotEmpty(prevPoint.getEqpBookId())) {
                    eqpBookIdSet.add(prevPoint.getEqpBookId());
                }
            }
        }

        StringBuilder stringBuilder = new StringBuilder();
        List<String> devList = new ArrayList<>();
        List<String> devTypeList = new ArrayList<>();
        List<String> devNoList = new ArrayList<>();

        if (!eqpBookIdSet.isEmpty()) {
            for (String pointId : eqpBookIdSet) {
                logger.info("[TASK] pointId: {}", pointId);
                Map<String, String> videoPosMap = patrolTaskInfoService.selectVideoPosByPointId(pointId);
                final String type = videoPosMap.get("type");
                if (type.equals("13")) {
                    devTypeList.add("0");
                } else if (!type.equals("1") && !type.equals("2") && !type.equals("3")) {
                    devTypeList.add("2");
                } else {
                    devTypeList.add("1");
                }
                final String patrolDeviceCode = videoPosMap.get("patrol_device_code");
                logger.info("[TASK] patrolDeviceCode: {}", patrolDeviceCode);
                devNoList.add(patrolDeviceCode);
            }
        }

        List<PatrolTaskInfo> patrolTaskInfos = new ArrayList<>();
        if (prevPointList != null && !prevPointList.isEmpty()) {
            for (PrevPoint prevPoint : prevPointList) {
                if (StringUtils.isEmpty(prevPoint.getParentId())) {
                    continue;
                }
                String[] parentIds = prevPoint.getParentId().split(StringUtils.DASH);
                if (parentIds.length < 2) {
                    continue;
                }

                if (!stringBuilder.toString().contains(parentIds[0])) {
                    stringBuilder.append(parentIds[0]).append(StringUtils.COMMA);
                    devList.add(parentIds[0]);
                }

                PatrolTaskInfo patrolTaskInfo;
                Map<String, String> videoPos;
                if (flag.equals("1")) {
                    videoPos = patrolTaskInfoService.selectVideoPosByPointId(prevPoint.getEqpBookId());
                    final String patrolDeviceCode = videoPos.get("patrol_device_code");
                    final String type = videoPos.get("type");
                    final String patrolDeviceName = videoPos.get("patrol_device_name");
                    patrolTaskInfo = patrolTaskInfoService.selectTaskInfoByBaseId(parentIds[1]);
                    patrolTaskInfo.setParentId(prevPoint.getParentId());
                    patrolTaskInfo.setEbookId(prevPoint.getEqpBookId());
                    if (StringUtils.isNotEmpty(prevPoint.getLabel())) {
                        patrolTaskInfo.setEbookName(prevPoint.getLabel());
                    }

                    patrolTaskInfo.setDeviceId(parentIds[1]);
                    if (StringUtils.isNotEmpty(patrolDeviceName)) {
                        patrolTaskInfo.setEbookName(patrolDeviceName);
                    }

                    patrolTaskInfo.setDevNo(patrolDeviceCode);
                    if (type.equals("13")) {
                        patrolTaskInfo.setDevType("0");
                    } else if (!type.equals("1") && !type.equals("2") && !type.equals("3")) {
                        patrolTaskInfo.setDevType("2");
                    } else {
                        patrolTaskInfo.setDevType("1");
                    }

                    patrolTaskInfos.add(patrolTaskInfo);
                } else {
                    videoPos = patrolTaskInfoService.selectVideoPosByPointId(prevPoint.getEqpBookId());
                    final String patrolDeviceCode = videoPos.get("patrol_device_code");
                    final String type = videoPos.get("type");
                    patrolTaskInfo = patrolTaskInfoService.selectTaskInfoByBaseId(parentIds[1]);
                    patrolTaskInfo.setPresetCode(prevPoint.getPresetCode());
                    patrolTaskInfo.setDeviceId(parentIds[1]);
                    if (type.equals("13")) {
                        patrolTaskInfo.setDevType("0");
                    } else if (!type.equals("1") && !type.equals("2") && !type.equals("3")) {
                        patrolTaskInfo.setDevType("2");
                    } else {
                        patrolTaskInfo.setDevType("1");
                    }

                    patrolTaskInfo.setDevNo(patrolDeviceCode);
                    patrolTaskInfo.setParentId(prevPoint.getParentId());
                    patrolTaskInfo.setEbookId(prevPoint.getEqpBookId());
                    if (StringUtils.isNotEmpty(prevPoint.getLabel())) {
                        patrolTaskInfo.setEbookName(prevPoint.getLabel());
                    }

                    if (StringUtils.isNotEmpty(prevPoint.getEbookName())) {
                        patrolTaskInfo.setEbookName(prevPoint.getEbookName());
                    }

                    patrolTaskInfos.add(patrolTaskInfo);
                }
            }
        }

        if (!devTypeList.isEmpty()) {
            patrolTaskList.get(0).setDevType(String.join(StringUtils.COMMA, devTypeList));
        }

        if (!devNoList.isEmpty()) {
            patrolTaskList.get(0).setDevNo(String.join(StringUtils.COMMA, devNoList));
        }

        if (!patrolTaskInfos.isEmpty()) {
            patrolTaskList.get(0).setEqpointList(patrolTaskInfos);
        }

    }

    public List<PatrolTask> toPatrolTaskList(JSONObject jsonObject, String flag) {
        logger.info(Color.GREEN + "[MAIN] toPatrolTaskList jsonObject: {}" + Color.END, jsonObject);
        List<PatrolTask> patrolTaskList = new ArrayList<>();
        PatrolTask patrolTask = new PatrolTask();
        try {
            String jsonObjectString;
            if (jsonObject.get("taskId") != null) {
                jsonObjectString = jsonObject.get("taskId").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setTaskId(Long.valueOf(jsonObjectString));
                    patrolTask.setCreateTime(patrolTaskService.selectPatrolTaskByTaskId(Long.valueOf(jsonObjectString)).getCreateTime());
                }
            }

            if (jsonObject.get("stationName") != null) {
                jsonObjectString = jsonObject.get("stationName").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setStationName(jsonObjectString);
                }
            }

            if (jsonObject.get("areaId") != null) {
                jsonObjectString = jsonObject.get("areaId").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setAreaId(jsonObjectString);
                }
            }

            if (jsonObject.get("areaName") != null) {
                jsonObjectString = jsonObject.get("areaName").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setAreaName(jsonObjectString);
                }
            }

            if (jsonObject.get("stationCode") != null) {
                jsonObjectString = jsonObject.get("stationCode").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setStationCode(jsonObjectString);
                }
            }

            if (jsonObject.get("type") != null) {
                jsonObjectString = jsonObject.get("type").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setType(jsonObjectString);
                }
            }

            if (jsonObject.get("taskCode") != null) {
                jsonObjectString = jsonObject.get("taskCode").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setTaskCode(jsonObjectString);
                }
            }

            if (jsonObject.get("taskName") != null) {
                jsonObjectString = jsonObject.get("taskName").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setTaskName(jsonObjectString);
                }
            }

            if (jsonObject.get("priority") != null) {
                jsonObjectString = jsonObject.get("priority").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setPriority(jsonObjectString);
                }
            }

            if (jsonObject.get("deviceLevel") != null) {
                jsonObjectString = jsonObject.get("deviceLevel").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDeviceLevel(jsonObjectString);
                }
            }

            if (jsonObject.get("deviceList") != null) {
                jsonObjectString = jsonObject.get("deviceList").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDeviceList(jsonObjectString);
                }
            }

            if (jsonObject.get("fixedStartTime") != null) {
                jsonObjectString = jsonObject.get("fixedStartTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setFixedStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("cycleMonth") != null) {
                jsonObjectString = jsonObject.get("cycleMonth").toString();
                if (jsonObjectString != null && StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleMonth(jsonObjectString);
                }
            }

            if (jsonObject.get("cycleWeek") != null) {
                jsonObjectString = jsonObject.get("cycleWeek").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleWeek(jsonObjectString);
                }
            }

            if (jsonObject.get("cycleExecuteTime") != null) {
                jsonObjectString = jsonObject.get("cycleExecuteTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleExecuteTime(jsonObjectString);
                }
            }

            if (jsonObject.get("cycleStartTime") != null) {
                jsonObjectString = jsonObject.get("cycleStartTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("cycleEndTime") != null) {
                jsonObjectString = jsonObject.get("cycleEndTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("intervalNumber") != null) {
                jsonObjectString = jsonObject.get("intervalNumber").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalNumber(Integer.parseInt(jsonObjectString));
                }
            }

            if (jsonObject.get("intervalType") != null) {
                jsonObjectString = jsonObject.get("intervalType").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalType(jsonObjectString);
                }
            }

            if (jsonObject.get("intervalExecuteTime") != null) {
                jsonObjectString = jsonObject.get("intervalExecuteTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalExecuteTime(jsonObjectString);
                }
            }

            if (jsonObject.get("intervalStartTime") != null) {
                jsonObjectString = jsonObject.get("intervalStartTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("intervalEndTime") != null) {
                jsonObjectString = jsonObject.get("intervalEndTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("invalidStartTime") != null) {
                jsonObjectString = jsonObject.get("invalidStartTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setInvalidStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("invalidEndTime") != null) {
                jsonObjectString = jsonObject.get("invalidEndTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setInvalidEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("isenable") != null) {
                jsonObjectString = jsonObject.get("isenable").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIsEnable(jsonObjectString);
                }
            }

            if (jsonObject.get("devType") != null) {
                jsonObjectString = jsonObject.get("devType").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDevType(jsonObjectString);
                }
            }

            if (jsonObject.get("creator") != null) {
                jsonObjectString = jsonObject.get("creator").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDrafter(jsonObjectString);
                }
            }

            if (jsonObject.get("executionStatus") != null) {
                jsonObjectString = jsonObject.get("executionStatus").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setExecutionStatus(jsonObjectString);
                }
            }

            if (jsonObject.get("taskCycle") != null) {
                jsonObjectString = jsonObject.get("taskCycle").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setTaskCycle(jsonObjectString);
                }
            }

            if (jsonObject.get("devNo") != null) {
                jsonObjectString = jsonObject.get("devNo").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDevNo(jsonObjectString);
                }
            }

            if (jsonObject.get("executionMode") != null) {
                jsonObjectString = jsonObject.get("executionMode").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setExecutionMode(jsonObjectString);
                }
            }

            if (jsonObject.get("linkageState") != null) {
                jsonObjectString = jsonObject.get("linkageState").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setLinkageState(jsonObjectString);
                }
            }

            if (jsonObject.get("areaIdS") != null) {
                jsonObjectString = jsonObject.get("areaIdS").toString();
                if (jsonObjectString != null && StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setAreaIdS(jsonObjectString);
                    String areaNameS = getAreaNameSByAreaIdS(jsonObjectString);
                    patrolTask.setAreaName(areaNameS);
                }
            }

            if (jsonObject.get("taskId") != null) {
                jsonObjectString = jsonObject.get("taskId").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setTaskId(Long.valueOf(jsonObjectString));
                }
            }

            if (jsonObject.get("stationName") != null) {
                jsonObjectString = jsonObject.get("stationName").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setStationName(jsonObjectString);
                }
            }

            if (jsonObject.get("areaId") != null) {
                jsonObjectString = jsonObject.get("areaId").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setAreaId(jsonObjectString);
                }
            }

//            if (jsonObject.get("areaName") != null) {
//                jsonObjectString = jsonObject.get("areaName").toString();
//                if (StringUtils.isNotEmpty(jsonObjectString)) {
//                    patrolTask.setAreaName(jsonObjectString);
//                }
//            }

            if (jsonObject.get("stationCode") != null) {
                jsonObjectString = jsonObject.get("stationCode").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setStationCode(jsonObjectString);
                }
            }

            if (jsonObject.get("type") != null) {
                jsonObjectString = jsonObject.get("type").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setType(jsonObjectString);
                }
            }

            if (jsonObject.get("taskCode") != null) {
                jsonObjectString = jsonObject.get("taskCode").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setTaskCode(jsonObjectString);
                }
            }

            if (jsonObject.get("taskName") != null) {
                jsonObjectString = jsonObject.get("taskName").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setTaskName(jsonObjectString);
                }
            }

            if (jsonObject.get("priority") != null) {
                jsonObjectString = jsonObject.get("priority").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setPriority(jsonObjectString);
                }
            }

            if (jsonObject.get("deviceLevel") != null) {
                jsonObjectString = jsonObject.get("deviceLevel").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDeviceLevel(jsonObjectString);
                }
            }

            if (jsonObject.get("deviceList") != null) {
                jsonObjectString = jsonObject.get("deviceList").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDeviceList(jsonObjectString);
                }
            }

            if (jsonObject.get("fixedStartTime") != null) {
                jsonObjectString = jsonObject.get("fixedStartTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setFixedStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("cycleMonth") != null) {
                jsonObjectString = jsonObject.get("cycleMonth").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleMonth(jsonObjectString);
                }
            }

            if (jsonObject.get("cycleWeek") != null) {
                jsonObjectString = jsonObject.get("cycleWeek").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleWeek(jsonObjectString);
                }
            }

            if (jsonObject.get("cycleExecuteTime") != null) {
                jsonObjectString = jsonObject.get("cycleExecuteTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleExecuteTime(jsonObjectString);
                }
            }

            if (jsonObject.get("cycleStartTime") != null) {
                jsonObjectString = jsonObject.get("cycleStartTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("cycleEndTime") != null) {
                jsonObjectString = jsonObject.get("cycleEndTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setCycleEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("intervalNumber") != null) {
                jsonObjectString = jsonObject.get("intervalNumber").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalNumber(Integer.parseInt(jsonObjectString));
                }
            }

            if (jsonObject.get("intervalType") != null) {
                jsonObjectString = jsonObject.get("intervalType").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalType(jsonObjectString);
                }
            }

            if (jsonObject.get("intervalExecuteTime") != null) {
                jsonObjectString = jsonObject.get("intervalExecuteTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalExecuteTime(jsonObjectString);
                }
            }

            if (jsonObject.get("intervalStartTime") != null) {
                jsonObjectString = jsonObject.get("intervalStartTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("intervalEndTime") != null) {
                jsonObjectString = jsonObject.get("intervalEndTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setIntervalEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("invalidStartTime") != null) {
                jsonObjectString = jsonObject.get("invalidStartTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setInvalidStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("invalidEndTime") != null) {
                jsonObjectString = jsonObject.get("invalidEndTime").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setInvalidEndTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, jsonObjectString));
                }
            }

            if (jsonObject.get("devType") != null) {
                jsonObjectString = jsonObject.get("devType").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDevType(jsonObjectString);
                }
            }

            if (jsonObject.get("executionStatus") != null) {
                jsonObjectString = jsonObject.get("executionStatus").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setExecutionStatus(jsonObjectString);
                }
            }

            if (jsonObject.get("taskCycle") != null) {
                jsonObjectString = jsonObject.get("taskCycle").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setTaskCycle(jsonObjectString);
                }
            }

            if (jsonObject.get("devNo") != null) {
                jsonObjectString = jsonObject.get("devNo").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setDevNo(jsonObjectString);
                }
            }

            if (jsonObject.get("executionMode") != null) {
                jsonObjectString = jsonObject.get("executionMode").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setExecutionMode(jsonObjectString);
                }
            }

            if (jsonObject.get("linkageState") != null) {
                jsonObjectString = jsonObject.get("linkageState").toString();
                if (StringUtils.isNotEmpty(jsonObjectString)) {
                    patrolTask.setLinkageState(jsonObjectString);
                }
            }

            if (StringUtils.isNotEmpty(flag)) {
                if (flag.equals("0")) {
                    if (jsonObject.get("prevPoints") != null) {
                        List<PrevPoint> prevPointList = JSONArray.parseArray(jsonObject.get("prevPoints").toString(), PrevPoint.class);
                        patrolTask.setPrevPoints(prevPointList);
                    }
                } else if (jsonObject.get("prevPoints") != null) {
                    JSONArray parseObject = JSONObject.parseArray(jsonObject.get("prevPoints").toString());
                    if (parseObject != null) {
                        List<PrevPoint> prevPointList = new ArrayList<>();
                        for (Object object : parseObject) {
                            JSONObject parsedObject = JSONArray.parseObject(object.toString());
                            if (parsedObject.get("parentId") != null) {
                                String parentId = parsedObject.getString("parentId");
                                String id = parsedObject.getString("id");
                                String stand = parsedObject.getString("stand");
                                String presetCode = parsedObject.getString("presetCode");
                                PrevPoint prevPoint = new PrevPoint();
                                prevPoint.setParentId(parentId);
                                prevPoint.setEqpBookId(id);
                                prevPoint.setPresetCode(presetCode);
                                prevPointList.add(prevPoint);
                                patrolTask.setPrevPoints(prevPointList);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        patrolTaskList.add(patrolTask);
        return patrolTaskList;
    }

    @GetMapping({"/TaskStatusBydevNo"})
    public AjaxResult channelByEqBookId(String devNo) {
        PatrolTask patrolTask = new PatrolTask();
        patrolTask.setDevNo(devNo);
        List<PatrolTask> list = patrolTaskService.selectPatrolTaskList(patrolTask);
        Iterator<PatrolTask> iterator = list.iterator();

        PatrolTask patrolTaskTemp;
        List<PatrolTaskStatus> patrolTaskStatusList;
        List<PatrolTaskStatus> patrolTaskStatusListEx;
        do {
            if (!iterator.hasNext()) {
                return AjaxResult.success(new PatrolTask());
            }

            patrolTaskTemp = iterator.next();
            PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
            patrolTaskStatus.setTaskCode(patrolTaskTemp.getTaskCode());
            patrolTaskStatus.setTaskState("2");
            patrolTaskStatusList = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
            if (!patrolTaskStatusList.isEmpty()) {
                patrolTaskTemp.setTaskState("2");
                patrolTaskTemp.setTaskProgress(patrolTaskStatusList.get(0).getTaskProgress());
                return AjaxResult.success(patrolTaskTemp);
            }

            patrolTaskStatus.setTaskCode(patrolTaskTemp.getTaskCode());
            patrolTaskStatus.setTaskState("3");
            patrolTaskStatusListEx = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
        } while (patrolTaskStatusListEx.isEmpty());

        patrolTaskTemp.setTaskState("3");
        patrolTaskTemp.setTaskProgress(patrolTaskStatusList.get(0).getTaskProgress());
        return AjaxResult.success(patrolTaskTemp);
    }

    @GetMapping({"/changeStatus"})
    public AjaxResult changeStatus(
            @RequestParam("taskId") Long taskId,
            @RequestParam("isenable") String isEnable) {
        return taskId == null ? error("taskId absent!") :
                StringUtils.isEmpty(isEnable) ? error("switch status absent!") :
                        toAjax(patrolTaskService.updatePatrolTask(
                                PatrolTask.builder()
                                        .taskId(taskId)
                                        .isEnable(isEnable)
                                        .build()
                        ));
    }

    public String checkType(String devNo) {
        String str = "";
        BasedataEqpBookMoMain patrolResult = new BasedataEqpBookMoMain();
        patrolResult.setPatrolDeviceCode(devNo);
        List<BasedataEqpBookMoMain> list = patrolResultService.selectBasedataEqpBookList(patrolResult);
        if (!list.isEmpty()) {
            str = list.get(0).getType();
        }

        return str;
    }

    @GetMapping({"/taskByEqbookchannel11"})
    public AjaxResult taskByEqBookChannel11(PatrolTask patrolTask) {
        if (patrolTask.getTaskCode() == null) {
            return error("未发现该任务code");
        } else {
            List<TreeByEqBook> list = new ArrayList<>();
            List<PatrolTask> taskList = patrolTaskService.selectPatrolTaskList(patrolTask);
            if (taskList != null && !taskList.isEmpty()) {
                PatrolTask plTask = taskList.get(0);
                if (StringUtils.isNotEmpty(plTask.getDevNo())) {
                    String[] devNos = plTask.getDevNo().split(StringUtils.COMMA);
                    for (String devNo : devNos) {
                        TreeByEqBook treeByEqbook = new TreeByEqBook();
                        Map<String, Object> eqInfoMap = resultAnalysisService.selectEqInfoByCode(devNo);
                        if (eqInfoMap != null) {
                            String name = String.valueOf(eqInfoMap.get("patrol_device_name"));
                            String id = String.valueOf(eqInfoMap.get("eqp_book_id"));
                            String code = String.valueOf(eqInfoMap.get("patrol_device_code"));
                            treeByEqbook.setName(name);
                            treeByEqbook.setCode(code);
                            treeByEqbook.setId(id);
                            treeByEqbook.setType("dev");
                            List<TreeByEqBook> child = new ArrayList<>();
                            List<Map<String, String>> channelMap = resultAnalysisService.selectChannelByEqId(id);
                            if (channelMap != null && !channelMap.isEmpty()) {
                                for (Map<String, String> channelKey : channelMap) {
                                    if (channelKey.get("channel_code") != null) {
                                        TreeByEqBook tyEqBook = new TreeByEqBook();
                                        tyEqBook.setCode(channelKey.get("channel_code"));
                                        tyEqBook.setName(channelKey.get("channel_name"));
                                        tyEqBook.setType("channel");
                                        child.add(tyEqBook);
                                    }
                                }
                            }

                            if (!child.isEmpty()) {
                                treeByEqbook.setChildren(child);
                            }
                        }

                        list.add(treeByEqbook);
                    }
                }
            }

            return AjaxResult.success(list);
        }
    }

    @GetMapping({"/taskByEqbookchannel"})
    public AjaxResult taskByPointEqBookChannel(PatrolTask patrolTask) {
        if (patrolTask.getTaskCode() == null) {
            return error("未发现该任务code");
        } else {
            List<TreeByEqBook> list = new ArrayList<>();
            List<PatrolTask> taskList = patrolTaskService.selectPatrolTaskList(patrolTask);
            if (taskList != null && !taskList.isEmpty()) {
                PatrolTask plTask = taskList.get(0);
                PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
                patrolTaskInfo.setTaskMajorId(String.valueOf(plTask.getTaskId()));
                List<PatrolTaskInfo> taskInfoList = patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
                List<Long> deviceIdS = new ArrayList<>();

                for (PatrolTaskInfo info : taskInfoList) {
                    deviceIdS.add(Long.parseLong(info.getDeviceId()));
                }

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("patrolPointIdS", deviceIdS);
                Object presetListObject = basedataPatrolPointPresetServiceClient.getPatrolPointPresetListByDeviceIdS(jsonObject).getRows();
                JSONArray presetListObjects = JSONArray.parseArray(JSONObject.toJSONString(presetListObject));
                Map<String, String> presetMap = new HashMap<>();
                if (null != presetListObjects && !presetListObjects.isEmpty()) {
                    for (int i = 0; i < presetListObjects.size(); ++i) {
                        JSONObject item = presetListObjects.getJSONObject(i);
                        String channelCode = item.getString("channelCode");
                        presetMap.put(channelCode, channelCode);
                    }
                }

                if (StringUtils.isNotEmpty(plTask.getDevNo())) {
                    String[] devNos = plTask.getDevNo().split(StringUtils.COMMA);
                    for (String devNo : devNos) {
                        TreeByEqBook treeByEqbook = new TreeByEqBook();
                        Map<String, Object> map = resultAnalysisService.selectEqInfoByCode(devNo);
                        if (map != null) {
                            String name = map.get("patrol_device_name") + "";
                            String id = map.get("eqp_book_id") + "";
                            String code = map.get("patrol_device_code") + "";
                            treeByEqbook.setName(name);
                            treeByEqbook.setCode(code);
                            treeByEqbook.setId(id);
                            treeByEqbook.setType("dev");
                            List<TreeByEqBook> child = new ArrayList<>();
                            List<Map<String, String>> channelMap = resultAnalysisService.selectChannelByEqId(id);
                            if (channelMap != null && !channelMap.isEmpty()) {

                                for (Map<String, String> channelKey : channelMap) {
                                    if (channelKey.get("channel_code") != null
                                            && presetMap.containsKey(channelKey.get("channel_code"))) {
                                        TreeByEqBook tyEqBook = new TreeByEqBook();
                                        tyEqBook.setCode(channelKey.get("channel_code"));
                                        tyEqBook.setName(channelKey.get("channel_name"));
                                        tyEqBook.setType("channel");
                                        child.add(tyEqBook);
                                    }
                                }
                            }

                            if (!child.isEmpty()) {
                                treeByEqbook.setChildren(child);
                            }
                        }

                        list.add(treeByEqbook);
                    }
                }
            }

            return AjaxResult.success(list);
        }
    }

    @GetMapping({"/shengwen"})
    public AjaxResult voicePrint(String devId, String flag) {
        String url = patrolTaskService.selectConfigByKey("SW_URL");
        if (StringUtils.isEmpty(url)) {
            return error("未配置声纹系统路径");
        } else {
            logger.info("[TASK] voicePrint url: {}", url);
            try {
                HttpClientUtils.get(url, "devId=" + devId + "&flag=" + flag);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return success();
        }
    }

    public void sendJQR(PatrolTask patrolTask) {
        String sendCode = "";
        String receiveCode = "";
        BasedataEqpBookMoMain based = new BasedataEqpBookMoMain();
        based.setType("20");
        List<BasedataEqpBookMoMain> basedataEqpBookMoMains = patrolResultService.selectBasedataEqpBookList(based);
        if (!basedataEqpBookMoMains.isEmpty()) {
            sendCode = basedataEqpBookMoMains.get(0).getPatrolDeviceCode();
        }

        BasedataEqpBookMoMain basedataEqpbookMomain = new BasedataEqpBookMoMain();
        List<BasedataEqpBookMoMain> eqpBookMoMains = patrolResultService.selectBasedataEqpBookList(basedataEqpbookMomain);
        if (!eqpBookMoMains.isEmpty()) {
            Set<String> wrjCode = new HashSet<>();
            Iterator<BasedataEqpBookMoMain> iterator = eqpBookMoMains.iterator();
            while (true) {
                String arr;
                SendTask sendTaskcontrol;
                String type;
                String patrolDeviceCode;
                do {
                    if (!iterator.hasNext()) {
                        if (!wrjCode.isEmpty()) {
                            Iterator<String> iterator1 = wrjCode.iterator();

                            while (iterator1.hasNext()) {
                                arr = iterator1.next();
                                sendTaskcontrol = new SendTask();
                                sendTaskcontrol.setReceiveCode(arr);
                                sendTaskcontrol.setSendCode(sendCode);
                                sendTaskcontrol.setCode(patrolTask.getTaskCode());
                                sendTaskcontrol.setType("41");
                                sendTaskcontrol.setCommand(patrolTask.getExecutionStatus());
                                String str = JSONObject.toJSONString(sendTaskcontrol);
                                feignTaskClient.sendCommand(str);
                            }
                        }

                        return;
                    }
                    basedataEqpbookMomain = iterator.next();
                    arr = basedataEqpbookMomain.getMainSystemCode();
                    type = basedataEqpbookMomain.getType();
                    patrolDeviceCode = basedataEqpbookMomain.getPatrolDeviceCode();

                } while (!type.equals("1") && !type.equals("2") && !type.equals("3") && !type.equals("13"));

                if (StringUtils.isNotEmpty(arr)) {
                    // 机器狗，无人机
                    // 任务模式
                    wrjCode.add(arr);
                    sendTaskcontrol = new SendTask();
                    sendTaskcontrol.setReceiveCode(arr);
                    sendTaskcontrol.setSendCode(sendCode);
                    sendTaskcontrol.setCode(patrolDeviceCode);
                    sendTaskcontrol.setType("1");
                    sendTaskcontrol.setCommand("5");
                    List<PatrolSendTask> patrolSendTasks = new ArrayList<>();
                    PatrolSendTask patrolSendTask = new PatrolSendTask();
                    patrolSendTask.setValue("1");
                    patrolSendTasks.add(patrolSendTask);
                    sendTaskcontrol.setItems(patrolSendTasks);
                    String strSendTaskcontrol = JSONObject.toJSONString(sendTaskcontrol);
                    feignTaskClient.sendCommand(strSendTaskcontrol);
                }
            }
        }
    }

    public void syncTaskToUpperSystem(PatrolTask patrolTask) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sendCode = "";
        String receiveCode = "";
        Map<String, String> stationMap = patrolResultService.selectBasedataStation();
        String stationNo = stationMap.get("station_no");
        String stationName = stationMap.get("station_name");
        BasedataEqpBookMoMain based = new BasedataEqpBookMoMain();
        based.setType("20");
        List<BasedataEqpBookMoMain> basedataEqpBookMoMains = patrolResultService.selectBasedataEqpBookList(based);
        if (!basedataEqpBookMoMains.isEmpty()) {
            sendCode = basedataEqpBookMoMains.get(0).getPatrolDeviceCode();
        }

        PatrolTaskFtp patrolTaskFtp = patrolTaskFtpService.selectPatrolTaskFtpByLineId(3L);
        String filepath = "";
        String filename = "";
        String modelXml = null;
        List<PatrolTask> maintAreaList = patrolTaskService.selectPatrolTaskList(patrolTask);
        ArrayList items;
        if (null != maintAreaList && !maintAreaList.isEmpty()) {
            items = new ArrayList<>();

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

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

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

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

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

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

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

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

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

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

            GenXmlByBean<Object> pulseGet = new GenXmlByBean<>();
            PatrolTaskModuleXml pd = new PatrolTaskModuleXml();
            pd.setItem(items);
            modelXml = pulseGet.getXml(pd);
        } else {
            items = new ArrayList<>();
            PatrolTaskXML PatrolTaskXML = new PatrolTaskXML();
            items.add(PatrolTaskXML);
            GenXmlByBean<Object> pulseGet = new GenXmlByBean<>();
            PatrolTaskModuleXml pd = new PatrolTaskModuleXml();
            pd.setItem(items);
            modelXml = pulseGet.getXml(pd);
        }

        InputStream in_nocode = new ByteArrayInputStream(modelXml.getBytes());
        filename = "task_" + System.currentTimeMillis();
        String algorithmBaseImagePath = stationNo + "/Model/";
        DataMsg DataMsg = new DataMsg();
        DataMsg.setIp(patrolTaskFtp.getFtpIp());
        DataMsg.setPort(patrolTaskFtp.getFtpPort());
        DataMsg.setUsername(patrolTaskFtp.getFtpUserName());
        DataMsg.setPassword(patrolTaskFtp.getFtpPwd());
        DataMsg.setBasePath(patrolTaskFtp.getFtpPath());
        DataMsg.setType("0");
        DataMsg.setFilePath(algorithmBaseImagePath);
        DataMsg.setFileName(filename + ".xml");
        DataMsg.setInputStream(in_nocode);
        DataMsg.setIsImplicit("true");
        SFTPUtil.uploadFileForXml(DataMsg);
        SendTask sendTask = new SendTask();
        sendTask.setReceiveCode("");
        sendTask.setSendCode(sendCode);
        sendTask.setCode(stationMap.get("station_no"));
        sendTask.setType("11");
        List<PatrolSendTask> taskLis = new ArrayList<>();
        PatrolSendTask patrolSendTask = new PatrolSendTask();
        patrolSendTask.setTime(sdf.format(new Date()));
        patrolSendTask.setType("7");
        patrolSendTask.setFilePath(algorithmBaseImagePath + filename + ".xml");
        taskLis.add(patrolSendTask);
        sendTask.setItems(taskLis);
        String str = JSONObject.toJSONString(sendTask);
        System.out.println(str);
        syncDataToUpstreamService.postMessage(str);
    }

    @GetMapping({"/taskRationalList"})
    public AjaxResult taskRationalList() {
        List<Map<String, Long>> taskNumList = patrolTaskService.selectTaskRationalGroupByType();
        List<Map<String, String>> taskRationalList = new ArrayList<>();
        List<SysDictData> patrolTypes = DictUtils.getDictCache("patrol_type");
        if (patrolTypes != null) {
            patrolTypes.forEach((item) -> taskNumList.forEach((map) -> {
                if (item.getDictValue().equals(String.valueOf(map.get("type")))) {
                    Map<String, String> res = new HashMap<>();
                    res.put("type", item.getDictLabel());
                    res.put("ration", String.valueOf(map.get("num")));
                    taskRationalList.add(res);
                }
            }));
        }

        return AjaxResult.success(taskRationalList);
    }

    @GetMapping({"/defectList"})
    public AjaxResult defectList() {
        List<Map<String, String>> defectResList = new ArrayList<>();
        List<Map<String, String>> defectList1 = patrolTaskService.defectList1();
        if (!defectList1.isEmpty()) {
            for (Map<String, String> defectMap : defectList1) {
                Map<String, String> map = new HashMap<>();
                map.put("type", String.valueOf(defectMap.get("type")));
                map.put("address", String.valueOf(defectMap.get("area_name")));
                map.put("num", String.valueOf(defectMap.get("num")));
                defectResList.add(map);
            }
        }

        List<Map<String, String>> defectList2 = patrolTaskService.defectList2();
        if (!defectList2.isEmpty()) {
            for (Map<String, String> defectMap : defectList2) {
                Map<String, String> map = new HashMap<>();
                map.put("type", String.valueOf(defectMap.get("type")));
                map.put("address", String.valueOf(defectMap.get("area_name")));
                map.put("num", String.valueOf(defectMap.get("num")));
                defectResList.add(map);
            }
        }

        List<Map<String, String>> defectList3 = patrolTaskService.defectList3();
        if (!defectList3.isEmpty()) {
            for (Map<String, String> defectMap : defectList3) {
                Map<String, String> map = new HashMap<>();
                map.put("type", String.valueOf(defectMap.get("type")));
                map.put("address", String.valueOf(defectMap.get("area_name")));
                map.put("num", String.valueOf(defectMap.get("num")));
                defectResList.add(map);
            }
        }

        return AjaxResult.success(defectResList);
    }

    @GetMapping({"/pointStatistics"})
    public AjaxResult pointStatistics() {
        return AjaxResult.success(patrolTaskService.pointStatistics());
    }

    private String getAreaNameSByAreaIdS(String areaIdS) {
        AjaxResult ajaxResult = FeignBasedataAreaService.selectAreaNameSForTaskByAreaIdS((new JSONObject()).fluentPut("areaIdS", areaIdS));
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(ajaxResult));
        return jsonObject.get("data").toString();
    }

    /**
     * 新的关系树
     * @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();
    }

    @Log(
            title = "导出任务详情数据",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/taskInfoExport"})
    public ResponseEntity taskInfoExport(HttpServletResponse response, PatrolTaskStatus patrolTaskStatus) throws Exception {
        long start = System.currentTimeMillis();
        PatrolTaskStatus patro = this.patrolTaskStatusService.selectPatrolTaskStatusByLineId(patrolTaskStatus.getLineId());
        List<PatrolData> newList = getNewList(patrolTaskStatus, patro.getTaskPatrolledId());
        logger.info("数据处理耗时: {} ms", (System.currentTimeMillis() - start));
        long startExport = System.currentTimeMillis();
        exportExcelV2(response, newList);
        logger.info("任务详情导出耗时: {} ms", (System.currentTimeMillis() - startExport));
        logger.info("任务详情导出总流程耗时: {} ms", (System.currentTimeMillis() - start));
        return ResponseEntity.ok("数据导出成功！");

    }

    private void exportExcelV2(HttpServletResponse response, List<PatrolData> dataList) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"task_export_" + System.currentTimeMillis() + ".xlsx\"");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        logger.info("[EXCEL]开始导出");
        printMemoryInfo("开始导出");

        // 使用SXSSFWorkbook来处理大数据量，避免内存溢出
        try (SXSSFWorkbook workbook = new SXSSFWorkbook(100); ServletOutputStream out = response.getOutputStream()) {
            Sheet sheet = workbook.createSheet(MessageUtils.get("任务详情"));
            workbook.setCompressTempFiles(true);

            // 创建标题行
            createHeaderRow(sheet);

            final int BatchSize = 300;
            // 临时目录
            Files.createDirectories(Paths.get(TEMP_DIR));
            // 写入数据
            for (int i = 0; i < dataList.size(); i += BatchSize) {
                List<PatrolData> subList = dataList.subList(i, Math.min(i + BatchSize, dataList.size()));
                // 获取去重图片
                Set<String> uniqueImages = new HashSet<>();
                for (PatrolData data : subList) {
                    addImagesToSet(uniqueImages, data.getImageNormalUrlPath());
                    addImagesToSet(uniqueImages, data.getImg());
                    addImagesToSet(uniqueImages, data.getImgAnalyse());
                    addImagesToSet(uniqueImages, data.getBrightImgAnalyse());
                }
                logger.info("图片{}去重后总数: {}", i, uniqueImages.size());
                Map<String, Path> pathMap = downloadBatch(uniqueImages);

                for (int j = 0; j < subList.size(); j++) {
                    PatrolData data = subList.get(j);
                    // +1 因为标题栏占一行
                    Row row = sheet.createRow(i + j + 1);
                    // 创建数据单元格
                    createDataCells(row, data);
                    // 插入图片
                    addImageToExcel(workbook, sheet, data, row, pathMap);
                }
                // 每批次 flush一次，释放内存
                ((SXSSFSheet) sheet).flushRows(BatchSize);
                // gc
                uniqueImages.clear();
                pathMap.values().forEach(path -> {
                    try {
                        Files.deleteIfExists(path);
                    } catch (IOException ignored) {}
                });
                pathMap = null;
            }

            response.setHeader("Transfer-Encoding", "chunked");
            workbook.write(out);
        } catch (IOException e) {
            logger.error("导出异常：{}", e);
            printMemoryInfo("导出异常");
        } finally {
            Path start = Paths.get(TEMP_DIR);
            Files.walk(start)
                    .sorted(Comparator.reverseOrder())
                    .forEach(path -> {
                        try {
                            Files.deleteIfExists(path);
                        } catch (IOException ignored) {
                        }
                    });
            Files.deleteIfExists(start);
        }
    }

    // 将图插入到指定单元格
    private void addImageToExcel(SXSSFWorkbook workbook, Sheet sheet, PatrolData data, Row row, Map<String, Path> pathMap) {
        try {
            Drawing<?> drawing = sheet.createDrawingPatriarch();
            // 获取第一张基准图片（如果有）
            String firstImageNormal = getFirstImage(data.getImageNormalUrlPath());
            if (firstImageNormal != null) {
                Path path = pathMap.get(firstImageNormal);
                if (path != null) {
                    byte[] imageData = Files.readAllBytes(path);
                    // 插入基准图片（第9列）
                    insertImage(workbook, drawing, row, 9, imageData);
                }
            }

            // 获取第一张初筛图片（如果有）
            String firstImage = getFirstImage(data.getImg());
            if (firstImage != null) {
                Path path = pathMap.get(firstImage);
                if (path != null) {
                    byte[] imageData = Files.readAllBytes(path);
                    // 插入初筛图片（第10列）
                    insertImage(workbook, drawing, row, 10, imageData);
                }
            }

            // 获取第一张分析图片（如果有）
            String firstImgAnalyse = getFirstImage(data.getImgAnalyse());
            if (firstImgAnalyse != null) {
                Path path = pathMap.get(firstImgAnalyse);
                if (path != null) {
                    byte[] imageData = Files.readAllBytes(path);
                    // 插入分析图片（第11列）
                    insertImage(workbook, drawing, row, 12, imageData);
                }
            }

            // 获取第一张光明大模型复核结果图（如果有）
            String firstBrightImgAnalyse = getFirstImage(data.getBrightImgAnalyse());
            if (firstBrightImgAnalyse != null) {
                Path path = pathMap.get(firstBrightImgAnalyse);
                if (path != null) {
                    byte[] imageData = Files.readAllBytes(path);
                    // 插入光明大模型复核结果图（第12列）
                    insertImage(workbook, drawing, row, 15, imageData);
                }
            }
        } catch (Exception e) {
            logger.warn("图片插入失败", e);
        }
    }

    // 批量下载图片
    private Map<String, Path> downloadBatch(Set<String> uniqueImages) {
        Map<String, Path> files = new HashMap<>();
        ExecutorService executor = Executors.newFixedThreadPool(10);
        for (String imageUrl : uniqueImages) {
            executor.submit(() -> {
                try {
                    String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
                    Path imgPath = Paths.get(TEMP_DIR, fileName);
                    if (Files.exists(imgPath)) {
                        files.put(imageUrl, imgPath);
                        return;
                    }

                    sftpClient.downLoad(imageUrl, (inputStream) -> {
                        // 使用Thumbnails压缩图片
                        byte[] originalBytes = getStringByInputStream(inputStream);
                        byte[] compressedBytes = compressImage(originalBytes);

                        // 将压缩后的图片保存到文件
                        Files.write(imgPath, compressedBytes);
                        files.put(imageUrl, imgPath);
                    });
                } catch (Exception e) {
                    logger.warn("图片下载失败: {}", imageUrl, e);
                }
            });
        }
        executor.shutdown();
        try {
            executor.awaitTermination(30, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return files;
    }

    // 辅助方法：提取图像路径到集合中
    private void addImagesToSet(Set<String> imageSet, String imagePathStr) {
        if (StringUtils.isNotEmpty(imagePathStr)) {
            Collections.addAll(imageSet, imagePathStr.split(StringUtils.COMMA));
        }
    }

    // 打印内存占用情况
    public void printMemoryInfo(String tag) {
        Runtime runtime = Runtime.getRuntime();
        long max = runtime.maxMemory();    // JVM 最大可用内存（-Xmx）
        long total = runtime.totalMemory(); // 当前 JVM 已申请内存
        long free = runtime.freeMemory();   // 当前空闲内存
        long used = total - free;           // 已使用内存

        logger.info("#{} maxMemory:{}MB,totalMemory:{}MB,used:{}MB,free:{}MB", tag, max / 1024.0 / 1024, total / 1024.0 / 1024, used / 1024.0 / 1024, free / 1024.0 / 1024);
    }

    private void exportExcelStream(HttpServletResponse response, List<PatrolData> dataList, Map<String, byte[]> imageCache) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"task_export_" + System.currentTimeMillis() + ".xlsx\"");

        // 使用SXSSFWorkbook来处理大数据量，避免内存溢出
        try (SXSSFWorkbook workbook = new SXSSFWorkbook(20); ServletOutputStream out = response.getOutputStream()) {

            Sheet sheet = workbook.createSheet(MessageUtils.get("任务详情"));

            // 创建标题行
            createHeaderRow(sheet);

            // 创建绘图控制器
            Drawing<?> drawing = sheet.createDrawingPatriarch();

            // 写入数据
            for (int i = 0; i < dataList.size(); i++) {
                PatrolData item = dataList.get(i);
                Row row = sheet.createRow(i + 1);

                // 创建数据单元格
                createDataCells(row, item);

                // 插入图片
                insertImages(workbook, drawing, sheet, row, item, imageCache);
            }

            workbook.write(out);
        }
    }

    private byte[] downloadAndCompressImage(String imagePath) {
        try {
            // 直接下载并压缩图片
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            sftpClient.downLoad(imagePath, inputStream -> {
                // 压缩图片
                Thumbnails.of(inputStream)
                        .size(300, 300) // 限制最大尺寸
                        .outputQuality(0.5) // 50%质量
                        .outputFormat("JPEG")
                        .toOutputStream(output);
            });
            return output.toByteArray();
        } catch (Exception e) {
            logger.warn("图片下载压缩失败: {}", imagePath);
            return new byte[0];
        }
    }

    private void createHeaderRow(Sheet sheet) {
        String[] headers = {
                "编号", "设备", "相机名", "系统", "点位id", "点位名称", "状态",
                "算法名称", "读数", "基准图", "初筛图片", "初筛结果", "分析图片", "分析结果",
                "复核结果", "复核详情"
        };

        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(MessageUtils.get(headers[i]));
            sheet.setColumnWidth(i, 20 * 256); // 20字符宽
        }
    }

    private void createDataCells(Row row, PatrolData item) {
        int col = 0;
        // 编号
        row.createCell(col++).setCellValue(row.getRowNum());
        // 设备信息
        row.createCell(col++).setCellValue(item.getDeviceName());
        row.createCell(col++).setCellValue(item.getChannelName());
        row.createCell(col++).setCellValue(item.getDeviceSource());
        row.createCell(col++).setCellValue(item.getPointId());
        row.createCell(col++).setCellValue(item.getPointName());
        // 状态
        String status;
        if (StringUtils.isNotEmpty(item.getPointStatus())) {
            switch (item.getPointStatus()) {
                case "1":
                    status = MessageUtils.get("正常");
                    break;
                case "0":
                    status = MessageUtils.get("异常");
                    break;
                case "2":
                    status = MessageUtils.get("待人工确认");
                    break;
                case "3":
                    status = MessageUtils.get("忽略");
                    break;
                case "4":
                    status = MessageUtils.get("跟踪");
                    break;
                case "5":
                    status = MessageUtils.get("确认");
                    break;
                case "6":
                    status = MessageUtils.get("缺陷");
                    break;
                default:
                    status = item.getPointStatus(); // 或默认值
                    break;
            }
        } else {
            status = ""; // 或默认值
        }
        row.createCell(col++).setCellValue(status);
        // 算法信息
        row.createCell(col++).setCellValue(item.getAlgName());
        row.createCell(col++).setCellValue(item.getResValue());
        // 文本信息
        row.createCell(11).setCellValue(item.getFilterDesc()); // 筛选结果
        row.createCell(13).setCellValue(item.getDesc());      // 分析结果
        row.createCell(14).setCellValue(item.getBrightResStatus());      // 复核结果
//        row.createCell(14).setCellValue(item.getBrightDesc());      // 复核详情
    }

    private void insertImages(SXSSFWorkbook workbook, Drawing<?> drawing, Sheet sheet,
                              Row row, PatrolData item, Map<String, byte[]> imageCache) {

        try {
            // 获取第一张基准图片（如果有）
            String firstImageNormal = getFirstImage(item.getImageNormalUrlPath());
            if (firstImageNormal != null) {
                byte[] imageData = imageCache.getOrDefault(firstImageNormal, new byte[0]);
                // 插入基准图片（第9列）
                insertImage(workbook, drawing, row, 9, imageData);
            }

            // 获取第一张初筛图片（如果有）
            String firstImage = getFirstImage(item.getImg());
            if (firstImage != null) {
                byte[] imageData = imageCache.getOrDefault(firstImage, new byte[0]);
                // 插入筛选图片（第9列）
                insertImage(workbook, drawing, row, 10, imageData);
            }

            // 获取第一张分析图片（如果有）
            String firstImgAnalyse = getFirstImage(item.getImgAnalyse());
            if (firstImgAnalyse != null) {
                byte[] imageData = imageCache.getOrDefault(firstImgAnalyse, new byte[0]);
                // 插入分析图片（第11列）
                insertImage(workbook, drawing, row, 12, imageData);
            }

            // 获取第一张光明大模型复核结果图（如果有）
            String firstBrightImgAnalyse = getFirstImage(item.getBrightImgAnalyse());
            if (firstBrightImgAnalyse != null) {
                byte[] imageData = imageCache.getOrDefault(firstBrightImgAnalyse, new byte[0]);
                // 插入筛选图片（第14列）
                insertImage(workbook, drawing, row, 15, imageData);
            }
        } catch (Exception e) {
            logger.warn("图片插入失败", e);
        }
    }

    private String getFirstImage(String imgPaths) {
        if (StringUtils.isEmpty(imgPaths)) {
            return null;
        }
        String[] images = imgPaths.split(StringUtils.COMMA);
        return (images.length > 0) ? images[0] : null;
    }

    private void insertImage(SXSSFWorkbook workbook, Drawing<?> drawing, Row row,
                             int colIndex, byte[] imageData) {

        // 计算图片位置
        ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
        anchor.setCol1((short) colIndex);
        anchor.setRow1(row.getRowNum());
        anchor.setCol2((short) (colIndex + 1));
        anchor.setRow2(row.getRowNum() + 1);

        // 添加图片到工作簿
        int pictureIdx = workbook.addPicture(imageData, Workbook.PICTURE_TYPE_JPEG);
        drawing.createPicture(anchor, pictureIdx);
    }

    private void exportExcel(HttpServletResponse response, List<PatrolData> newList) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"example.xlsx\"");
        HSSFWorkbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet(MessageUtils.get("任务详情") + "_" + System.currentTimeMillis());
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue(MessageUtils.get("编号"));
        Cell cell1 = row.createCell(1);
        cell1.setCellValue(MessageUtils.get("设备"));
        Cell cell2 = row.createCell(2);
        cell2.setCellValue(MessageUtils.get("相机名"));
        Cell cell3 = row.createCell(3);
        cell3.setCellValue(MessageUtils.get("系统"));
        Cell cell4 = row.createCell(4);
        cell4.setCellValue(MessageUtils.get("点位名称"));
        Cell cell5 = row.createCell(5);
        cell5.setCellValue(MessageUtils.get("状态"));
        Cell cell6 = row.createCell(6);
        cell6.setCellValue(MessageUtils.get("算法名称"));
        Cell cell7 = row.createCell(7);
        cell7.setCellValue(MessageUtils.get("读数"));
        Cell cell8 = row.createCell(8);
        cell8.setCellValue(MessageUtils.get("筛选图片"));
        Cell cell9 = row.createCell(9);
        cell9.setCellValue(MessageUtils.get("筛选结果"));
        Cell cell10 = row.createCell(10);
        cell10.setCellValue(MessageUtils.get("分析图片"));
        Cell cell11 = row.createCell(11);
        cell11.setCellValue(MessageUtils.get("分析结果"));
        HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch();
        for (int i = 0; i < newList.size(); ++i) {
            Row row1 = sheet.createRow(i + 1);
            Cell cell12 = row1.createCell(0);
            cell12.setCellValue(i + 1);
            Cell cell13 = row1.createCell(1);
            cell13.setCellValue(newList.get(i).getDeviceName());
            Cell cell14 = row1.createCell(2);
            cell14.setCellValue(newList.get(i).getChannelName());
            Cell cell15 = row1.createCell(3);
            cell15.setCellValue(newList.get(i).getDeviceSource());
            Cell cell16 = row1.createCell(4);
            cell16.setCellValue(newList.get(i).getPointName());
            Cell cell17 = row1.createCell(5);
            cell17.setCellValue("1".equals(newList.get(i).getPointStatus()) ? MessageUtils.get("正常") : "0".equals(newList.get(i).getPointStatus()) ? MessageUtils.get("异常") : MessageUtils.get("待人工确认"));
            Cell cell18 = row1.createCell(6);
            cell18.setCellValue(newList.get(i).getAlgName());
            Cell cell19 = row1.createCell(7);
            cell19.setCellValue(newList.get(i).getResValue());
            try {
                insertImage(workbook, patriarch, this.images(newList.get(i).getImg(), this.inputStreamMap(newList.get(i).getImg())), 8, i + 1, 8);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Cell cell21 = row1.createCell(9);
            cell21.setCellValue(newList.get(i).getFilterDesc());
            try {
                insertImage(workbook, patriarch, this.images(newList.get(i).getImgAnalyse(), this.inputStreamMap(newList.get(i).getImgAnalyse())), 10, i + 1, 10);
            } catch (Exception e) {
                e.printStackTrace();
            }

            Cell cell23 = row1.createCell(11);
            cell23.setCellValue(newList.get(i).getDesc());
        }

        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        workbook.close();
        outputStream.flush();
        outputStream.close();
    }

    private static void insertImage(HSSFWorkbook wb, HSSFPatriarch pa, byte[] data, int cell, int row, int cell1) {
        int x1 = 0;
        int y1 = 0;
        int x2 = 45;
        int y2 = 0;
        HSSFClientAnchor anchor = new HSSFClientAnchor(x1, y1, x2, y2, (short) cell, row, (short) cell1, row);
        pa.createPicture(anchor, wb.addPicture(data, 5)).resize(1.0D);
    }

    public byte[] images(String imgSrc, Map<String, byte[]> inputStreamMap) {
        return inputStreamMap.get(imgSrc);
    }

    private Map<String, byte[]> inputStreamMap(String imgPath) throws IOException {
        Map<String, byte[]> streamHashMap = new HashMap<>();
        String[] images = imgPath.split(StringUtils.COMMA);
        for (String image : images) {
            try {
                sftpClient.downLoad(image, (inputStream) -> {
                    byte[] shm = streamHashMap.get(image);
                    byte[] bytes = getStringByInputStream(inputStream);
                    if (shm == null) {
                        streamHashMap.put(image, bytes);
                    }

                });
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("sss: {}", e.getMessage());
            }
        }

        return streamHashMap;
    }

    protected TableDataInfo getDataTable(int flag, List<?> list2, List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(list2);
        if (flag == 0) {
            rspData.setMsg("查询成功");
            rspData.setTotal((new PageInfo<>(list)).getTotal());
        } else if (flag == 1) {
            rspData.setMsg("lineId为空");
        } else if (flag == 2) {
            rspData.setMsg("任务不存在");
        } else if (flag == 3) {
            rspData.setMsg("查询列表为空");
        }

        return rspData;
    }

    @GetMapping({"/getPatrolPointName"})
    public AjaxResult getPatrolPointName(PatrolTaskStatus patrolTaskStatus) {
        ResultAnalysis resultAnalysis = new ResultAnalysis();
        resultAnalysis.setTaskPatrolId(patrolTaskStatus.getTaskPatrolledId());
        resultAnalysis.setFilter("1");
        resultAnalysis.setDeviceName(patrolTaskStatus.getDeviceName());
        resultAnalysis.setPointName(patrolTaskStatus.getPointName());
        resultAnalysis.setChannelName(patrolTaskStatus.getChannelName());
        resultAnalysis.setDeviceSource(patrolTaskStatus.getDeviceSource());
        resultAnalysis.setPointStatus(patrolTaskStatus.getPointStatus());
        resultAnalysis.setAlgName(patrolTaskStatus.getAlgName());
        resultAnalysis.setFilterDesc(patrolTaskStatus.getFilterDesc());
        resultAnalysis.setDesc(patrolTaskStatus.getDesc());
        resultAnalysis.setAbnormal(patrolTaskStatus.getAbnormal());
        resultAnalysis.setPosType(patrolTaskStatus.getPosType());
        resultAnalysis.setResultType(patrolTaskStatus.getResultType());
        List<PatrolData> filterList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
        resultAnalysis.setFilter("0");
        List<PatrolData> newList = patrolResultService.selectPatrolDataResultByTaskCodeV2(resultAnalysis);
        List<AlgInfo> algInfos = patrolResultService.selectAlgInfo(new PatrolResult());
        Map<String, Object> map = new HashMap<>();
        List<String> listPointName = new ArrayList<>();
        List<String> listPointStatus = new ArrayList<>();
        List<String> listDeviceSource = new ArrayList<>();
        List<String> listChannelName = new ArrayList<>();
        List<String> listDeviceName = new ArrayList<>();
        List<String> listDesc = new ArrayList<>();
        List<String> listFilterDesc = new ArrayList<>();
        List<String> listAlgName = new ArrayList<>();
        List<Map<String, String>> mapList = new ArrayList<>();
        for (PatrolData item : newList) {
            Optional<AlgInfo> first = algInfos.stream().filter(
                    (alg) -> alg.getAlgSubtypeCode().equals(item.getAlgType())).findFirst();
            if (first.isPresent()) {
                item.setAlgName(first.get().getAlgSubtypeName());
            } else {
                item.setAlgName(item.getAlgType());
            }
            if ("0".equals(item.getFilter())) {
                List<PatrolData> filterDatas = filterList
                        .stream()
                        .filter((data) -> 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());
                    filterList.removeAll(filterDatas);
                }
//                else {
//                    item.setImg("");
//                }
//            } else {
//                item.setImg(item.getImgAnalyse());
//                item.setImgAnalyse("");
//                item.setFilterDesc(item.getDesc());
//                item.setDesc("");
            }

            if (!listPointName.contains(item.getPointName())) {
                listPointName.add(item.getPointName());
            }

            Map<String, String> map1 = new HashMap<>();
            if (!listPointStatus.contains(item.getPointStatus())) {
                // 点位状态 0-异常 1-正常 2-待人工确认 3-已撤销（忽略） 4-跟踪（告警） 5-确认（告警） 6-缺陷
                if (StringUtils.isNotEmpty(item.getPointStatus())) {
                    if (item.getPointStatus().equals("1")) {
                        map1.put("value", "1");
                        map1.put("label", MessageUtils.get("正常"));
                    }

                    if (item.getPointStatus().equals("0")) {
                        map1.put("value", "0");
                        map1.put("label", MessageUtils.get("异常"));
                    }

                    if (item.getPointStatus().equals("2")) {
                        map1.put("value", "2");
                        map1.put("label", MessageUtils.get("待人工确认"));
                    }

                    if (item.getPointStatus().equals("3")) {
                        map1.put("value", "3");
                        map1.put("label", MessageUtils.get("忽略"));
                    }

                    if (item.getPointStatus().equals("4")) {
                        map1.put("value", "4");
                        map1.put("label", MessageUtils.get("跟踪"));
                    }

                    if (item.getPointStatus().equals("5")) {
                        map1.put("value", "5");
                        map1.put("label", MessageUtils.get("确认"));
                    }

                    if (item.getPointStatus().equals(PointStatusEnum.DEFECT.getCode())) {
                        map1.put("value", "6");
                        map1.put("label", MessageUtils.get("缺陷"));
                    }

                    listPointStatus.add(item.getPointStatus());
                    mapList.add(map1);
                } else {
                    logger.info("GET_PATROL_POINT_NAME taskPatrolId: {} result_analysis point_status is null, item: {}",
                            patrolTaskStatus.getTaskPatrolledId(),
                            item);
                }
            }

            if (!listDeviceSource.contains(item.getDeviceSource())) {
                listDeviceSource.add(item.getDeviceSource());
            }
            if (!listChannelName.contains(item.getChannelName())) {
                listChannelName.add(item.getChannelName());
            }

            if (!listDeviceName.contains(item.getDeviceName())) {
                listDeviceName.add(item.getDeviceName());
            }

            if (!listDesc.contains(item.getDesc()) && StringUtils.isNotEmpty(item.getDesc())) {
                listDesc.add(item.getDesc());
            }

            if (!listFilterDesc.contains(item.getFilterDesc()) && StringUtils.isNotEmpty(item.getFilterDesc())) {
                listFilterDesc.add(item.getFilterDesc());
            }

            if (!listAlgName.contains(item.getAlgName())) {
                listAlgName.add(item.getAlgName());
            }
        }

        for (PatrolData item : filterList) {
            item.setAlgName(algInfos.stream().filter(
                    (alg) -> alg.getAlgSubtypeCode().equals(item.getAlgType())).findFirst().get().getAlgSubtypeName()
            );
            item.setFilterDesc(item.getDesc());
            item.setDesc("");

            if (!listPointName.contains(item.getPointName())) {
                listPointName.add(item.getPointName());
            }

            Map<String, String> map1 = new HashMap<>();
            if (!listPointStatus.contains(item.getPointStatus())) {
                if (item.getPointStatus().equals("1")) {
                    map1.put("value", "1");
                    map1.put("label", MessageUtils.get("正常"));
                }

                if (item.getPointStatus().equals("0")) {
                    map1.put("value", "0");
                    map1.put("label", MessageUtils.get("异常"));
                }

                if (item.getPointStatus().equals("2")) {
                    map1.put("value", "2");
                    map1.put("label", MessageUtils.get("待人工确认"));
                }

                if (item.getPointStatus().equals("3")) {
                    map1.put("value", "3");
                    map1.put("label", MessageUtils.get("忽略"));
                }

                if (item.getPointStatus().equals("4")) {
                    map1.put("value", "4");
                    map1.put("label", MessageUtils.get("跟踪"));
                }

                if (item.getPointStatus().equals("5")) {
                    map1.put("value", "5");
                    map1.put("label", MessageUtils.get("确认"));
                }

                if (item.getPointStatus().equals(PointStatusEnum.DEFECT.getCode())) {
                    map1.put("value", "6");
                    map1.put("label", MessageUtils.get("缺陷"));
                }

                listPointStatus.add(item.getPointStatus());
                mapList.add(map1);
            }

            if (!listDeviceSource.contains(item.getDeviceSource())) {
                listDeviceSource.add(item.getDeviceSource());
            }
            if (!listChannelName.contains(item.getChannelName())) {
                listChannelName.add(item.getChannelName());
            }

            if (!listDeviceName.contains(item.getDeviceName())) {
                listDeviceName.add(item.getDeviceName());
            }

            if (!listDesc.contains(item.getDesc()) && StringUtils.isNotEmpty(item.getDesc())) {
                listDesc.add(item.getDesc());
            }

            if (!listFilterDesc.contains(item.getFilterDesc()) && !"".equals(item.getFilterDesc())) {
                listFilterDesc.add(item.getFilterDesc());
            }

            if (!listAlgName.contains(item.getAlgName())) {
                listAlgName.add(item.getAlgName());
            }
        }
        map.put("listPointName", listPointName);
        map.put("listPointStatus", mapList);
        map.put("listDeviceSource", listDeviceSource);
        map.put("listChannelName", listChannelName);
        map.put("listDeviceName", listDeviceName);
        map.put("listDesc", listDesc);
        map.put("listFilterDesc", listFilterDesc);
        map.put("listAlgName", listAlgName);
        return AjaxResult.success(map);
    }
}
