package com.inspect.exec.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.constant.RedisConst;
import com.inspect.base.core.constant.Tags;
import com.inspect.base.core.domain.maintain.MaintainRegion;
import com.inspect.base.core.enums.ExecStatus;
import com.inspect.base.core.enums.IntervalType;
import com.inspect.base.core.enums.TaskStatus;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.JwtUtils;
import com.inspect.base.core.utils.LambdaUtils;

import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.constant.Color;
import com.inspect.base.redis.service.RedisService;
import com.inspect.common.security.utils.DictUtils;
import com.inspect.exec.domain.DBPatrolPoint;
import com.inspect.exec.domain.EqpBook;
import com.inspect.exec.domain.EqpBookChannel;
import com.inspect.exec.domain.PatrolTaskExecRecord;
import com.inspect.exec.domain.PatrolTaskPointExecRecord;
import com.inspect.exec.domain.SilenceTaskPointExecRecord;
import com.inspect.exec.service.IDBPatrolPointService;
import com.inspect.exec.service.IEqpBookChannelService;
import com.inspect.exec.service.IEqpBookService;
import com.inspect.exec.service.IPatrolTaskExecRecordService;
import com.inspect.exec.service.IPatrolTaskPointExecRecordService;
import com.inspect.exec.service.ISilenceTaskPointExecRecordService;
import com.inspect.maintain.service.IMaintainRegionService;
import com.inspect.partrolresult.domain.PatrolResult;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.patrol.domain.PatrolPresetAction;
import com.inspect.patrol.domain.PatrolPresetParam;
import com.inspect.patrol.domain.PatrolPresetPos;
import com.inspect.patrol.domain.PatrolPresetPosSlim;
import com.inspect.patrol.service.IPatrolPresetActionService;
import com.inspect.patrol.service.IPatrolPresetParamService;
import com.inspect.patrol.service.IPatrolPresetPosService;
import com.inspect.system.base.domain.SysDictData;
import com.inspect.system.base.openDomain.BasedataEqpBookMoMain;
import com.inspect.task.domain.PatrolTask;
import com.inspect.task.domain.SendTask;
import com.inspect.task.service.IPatrolTaskService;
import com.inspect.taskinfo.domain.PatrolTaskInfo;
import com.inspect.taskinfo.service.IPatrolTaskInfoService;
import com.inspect.taskstatus.client.FeignTaskClient;
import com.inspect.taskstatus.controller.PatrolTaskStatusController;
import com.inspect.taskstatus.domain.PatrolTaskStatus;
import com.inspect.taskstatus.service.IPatrolTaskStatusService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({"/exec"})
public class PatrolTaskExecController extends BaseController {
    final private Logger log = LoggerFactory.getLogger(PatrolTaskExecController.class);

    private final IPatrolTaskService patrolTaskService;
    private final IPatrolTaskStatusService patrolTaskStatusService;
    private final IPatrolTaskInfoService patrolTaskInfoService;
    private final IPatrolPresetPosService patrolPresetPosService;
    private final IPatrolPresetActionService patrolPresetActionService;
    private final IPatrolTaskExecRecordService patrolTaskExecRecordService;
    private final IPatrolTaskPointExecRecordService patrolTaskPointExecRecordService;
    private final IMaintainRegionService maintainRegionService;
    private final IPatrolPresetParamService patrolPresetParamService;
    private final ISilenceTaskPointExecRecordService silenceTaskPointExecRecordService;
    private final IEqpBookService eqpBookService;
    private final IEqpBookChannelService eqpBookChannelService;
    private final IDBPatrolPointService dbPatrolPointService;
    private final RedisService redisService;

    private final IPatrolResultService patrolResultService;

    @Resource
    private FeignTaskClient feignTaskClient;

    @Resource
    private PatrolTaskStatusController patrolTaskStatusController;

    public PatrolTaskExecController(IPatrolTaskInfoService patrolTaskInfoService, IPatrolTaskService patrolTaskService, RedisService redisService, IPatrolTaskStatusService patrolTaskStatusService, IDBPatrolPointService dbPatrolPointService, IPatrolPresetPosService patrolPresetPosService, IPatrolPresetActionService patrolPresetActionService, IPatrolTaskExecRecordService patrolTaskExecRecordService, IPatrolTaskPointExecRecordService patrolTaskPointExecRecordService, IMaintainRegionService maintainRegionService, IPatrolPresetParamService patrolPresetParamService, ISilenceTaskPointExecRecordService silenceTaskPointExecRecordService, IEqpBookChannelService eqpBookChannelService, IPatrolResultService patrolResultService, IEqpBookService eqpBookService) {
        this.patrolTaskInfoService = patrolTaskInfoService;
        this.patrolTaskService = patrolTaskService;
        this.redisService = redisService;
        this.patrolTaskStatusService = patrolTaskStatusService;
        this.dbPatrolPointService = dbPatrolPointService;
        this.patrolPresetPosService = patrolPresetPosService;
        this.patrolPresetActionService = patrolPresetActionService;
        this.patrolTaskExecRecordService = patrolTaskExecRecordService;
        this.patrolTaskPointExecRecordService = patrolTaskPointExecRecordService;
        this.maintainRegionService = maintainRegionService;
        this.patrolPresetParamService = patrolPresetParamService;
        this.silenceTaskPointExecRecordService = silenceTaskPointExecRecordService;
        this.eqpBookChannelService = eqpBookChannelService;
        this.patrolResultService = patrolResultService;
        this.eqpBookService = eqpBookService;
    }

    @PostMapping({"/selectTaskList"})
    @ResponseBody
    public List<PatrolTask> selectTaskList(@RequestBody PatrolTask patrolTask) {
        List<PatrolTask> resultList = new ArrayList<>();
        patrolTaskService.selectPatrolTaskList(patrolTask).stream()
                .filter(task -> !StringUtils.isEmpty(task.getDevType()) && !StringUtils.isEmpty(task.getDevNo()))
                .forEach(task -> {
                    final String[] devNos = task.getDevNo().split(StringUtils.COMMA);
                    final String[] devTypes = task.getDevType().split(StringUtils.COMMA);
                    if (devNos.length == devTypes.length) {
                        Arrays.stream(devTypes)
                                .forEach(LambdaUtils.consumerWithIndex((item, index) -> {
                                    if ("2".equals(item)) {
                                        resultList.add(PatrolTask.builder()
                                                .taskId(task.getTaskId())
                                                .stationName(task.getStationName())
                                                .stationCode(task.getTaskCode())
                                                .taskName(task.getTaskName())
                                                .priority(task.getPriority())
                                                .deviceLevel(task.getDeviceLevel())
                                                .deviceList(task.getDeviceList())
                                                .fixedStartTime(task.getFixedStartTime())
                                                .cycleMonth(task.getCycleMonth())
                                                .cycleWeek(task.getCycleWeek())
                                                .cycleExecuteTime(task.getCycleExecuteTime())
                                                .cycleStartTime(task.getCycleStartTime())
                                                .cycleEndTime(task.getCycleEndTime())
                                                .intervalNumber(task.getIntervalNumber())
                                                .intervalType(task.getIntervalType())
                                                .intervalExecuteTime(task.getIntervalExecuteTime())
                                                .intervalStartTime(task.getIntervalStartTime())
                                                .intervalEndTime(task.getIntervalEndTime())
                                                .invalidStartTime(task.getInvalidStartTime())
                                                .invalidEndTime(task.getInvalidEndTime())
                                                .isEnable(task.getIsEnable())
                                                .linkageState(task.getLinkageState())
                                                .devType("2")
                                                .drafter(task.getDrafter())
                                                .executionStatus(task.getExecutionStatus())
                                                .fileStatus(task.getFileStatus())
                                                .taskCycle(task.getTaskCycle())
                                                .devNo(devNos[index])
                                                .storage(task.getStorage())
                                                .taskProgress(task.getTaskProgress())
                                                .taskState(task.getTaskState())
                                                .executionMode(task.getExecutionMode())
                                                .beginTime(task.getBeginTime())
                                                .endTime(task.getEndTime())
                                                .areaId(task.getAreaId())
                                                .areaName(task.getAreaName())
                                                .build());
                                    }
                                }));
                    } else {
                        log.warn(Color.YELLOW + "[GABRIEL] devNos:{} not equal devTypes:{}" + Color.END, devNos.length, devTypes.length);
                    }
                });
        return resultList;
    }

    @PostMapping({"/selectPatrolTaskList"})
    @ResponseBody
    public List<PatrolTask> selectPatrolTaskList(@RequestBody PatrolTask patrolTask) {
        return patrolTaskService.selectPatrolTaskList(patrolTask);
    }

    @PostMapping({"/selectTaskInfoList"})
    @ResponseBody
    public List<PatrolTaskInfo> selectTaskInfoList(@RequestBody PatrolTaskInfo patrolTask) {
        return patrolTaskInfoService.selectPatrolTaskInfoList(patrolTask);
    }

    @PostMapping({"/selectPatrolPresetPosList"})
    @ResponseBody
    public List<PatrolPresetPos> selectPatrolPresetPosList(@RequestBody PatrolPresetPos patrolPresetPos) {
        log.info(Color.RED + "selectPatrolPresetPosList patrolPresetPos: {}" + Color.END, patrolPresetPos.getPatrolPointId());
        return patrolPresetPosService.selectPatrolPresetPosList(patrolPresetPos);
    }

    @PostMapping({"/selectPresetCodeSlimByPatrolPointId"})
    @ResponseBody
    public PatrolPresetPosSlim selectPatrolPresetPosByPatrolPointId(@RequestBody PatrolPresetPosSlim patrolPresetPos) {
        log.info(Color.RED + "selectPatrolPresetPosByPatrolPointId patrolPresetPos: {}" + Color.END, patrolPresetPos.getPatrolPointId());
        return patrolPresetPosService.selectPresetCodeSlimByPatrolPointId(patrolPresetPos);
    }

    @PostMapping({"/selectPatrolPresetActionList"})
    @ResponseBody
    public List<PatrolPresetAction> selectPatrolPresetActionList(@RequestBody PatrolPresetAction patrolPresetAction) {
        return patrolPresetActionService.selectPatrolPresetActionList(patrolPresetAction);
    }

    @PostMapping({"/selectMaintainRegionList"})
    @ResponseBody
    public List<MaintainRegion> selectMaintainRegionList(@RequestBody MaintainRegion region) {
        return maintainRegionService.selectMaintainRegionList(region);
    }

    @PostMapping({"/addPatrolTaskExecRecord"})
    public int addPatrolTaskExecRecord(@RequestBody PatrolTaskExecRecord patrolTaskExecRecord) {
        return patrolTaskExecRecordService.insertPatrolTaskExecRecord(patrolTaskExecRecord);
    }

    @PostMapping({"/selectCameraPatrolTaskExecRecordList"})
    @ResponseBody
    public List<PatrolTaskExecRecord> selectCameraPatrolTaskExecRecordList(@RequestParam(value = "devNo", required = false) String devNo, @RequestParam(value = "taskStates", required = false) List<String> taskStates) {
        return patrolTaskExecRecordService.selectCameraPatrolTaskExecRecordList(StringUtils.EMPTY, devNo, taskStates);
    }

    @PostMapping({"/updatePatrolTaskExecRecord"})
    public int updatePatrolTaskExecRecord(@RequestBody PatrolTaskExecRecord patrolTaskExecRecord) {
//      if("2".equals(patrolTaskExecRecord.getTaskState())) {
//
//      }
        return patrolTaskExecRecordService.updatePatrolTaskExecRecord(patrolTaskExecRecord);
    }

    @PostMapping({"/selectPatrolTaskExecRecordByTaskPatrolId"})
    public PatrolTaskExecRecord selectPatrolTaskExecRecordByTaskPatrolId(@RequestBody String taskPatrolledId) {
        return patrolTaskExecRecordService.selectPatrolTaskExecRecordByTaskPatrolId(taskPatrolledId);
    }

    @PostMapping({"/addPatrolTaskPointExecRecord"})
    public int addPatrolTaskPointExecRecord(@RequestBody PatrolTaskPointExecRecord patrolTaskPointExecRecord) {
        return patrolTaskPointExecRecordService.insertPatrolTaskPointExecRecord(patrolTaskPointExecRecord);
    }

    @PostMapping({"/updatePatrolTaskPointExecRecord"})
    public int updatePatrolTaskPointExecRecord(@RequestBody PatrolTaskPointExecRecord patrolTaskPointExecRecord) {
        return patrolTaskPointExecRecordService.updatePatrolTaskPointExecRecord(patrolTaskPointExecRecord);
    }

    @PostMapping({"/selectPatrolPresetParamList"})
    public List<PatrolPresetParam> selectPatrolPresetParamList(@RequestBody PatrolPresetParam patrolPresetParam) {
        return patrolPresetParamService.selectPatrolPresetParamList(patrolPresetParam);
    }

    @PostMapping({"/selectPatrolTaskPointExecRecordList"})
    public List<PatrolTaskPointExecRecord> selectPatrolTaskPointExecRecordList(@RequestBody PatrolTaskPointExecRecord patrolTaskPointExecRecord) {
        return patrolTaskPointExecRecordService.selectPatrolTaskPointExecRecordList(patrolTaskPointExecRecord);
    }

    @PostMapping({"/selectPatrolTaskStatusByTaskPatrolledId"})
    public PatrolTaskStatus selectPatrolTaskStatusByTaskPatrolledId(String taskPatrolledId) {
        //log.info("taskPatrolledId: {}", taskPatrolledId);
        return patrolTaskStatusService.selectPatrolTaskStatusByTaskPatrolledId(taskPatrolledId);
    }

    @PostMapping({"/selectPatrolTaskStatusList"})
    public List<PatrolTaskStatus> selectPatrolTaskStatusList(@RequestBody PatrolTaskStatus patrolTaskStatus) {
        return patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
    }

    @PostMapping({"/selectPatrolTaskExecRecordList"})
    public List<PatrolTaskExecRecord> selectPatrolTaskExecRecordList(@RequestBody PatrolTaskExecRecord patrolTaskExecRecord) {
        return patrolTaskExecRecordService.selectPatrolTaskExecRecordList(patrolTaskExecRecord);
    }

    @PostMapping({"/selectPatrolTaskExecRecordAbeyanceList"})
    public List<PatrolTaskExecRecord> selectAbeyancePatrolTaskExecRecordList(@RequestBody PatrolTaskExecRecord patrolTaskExecRecord) {
        //logger.info("[GABRIEL] call selectAbeyancePatrolTaskExecRecordList!!!");
        return patrolTaskExecRecordService.selectAbeyancePatrolTaskExecRecordList(patrolTaskExecRecord);
    }

    @PostMapping({"/addSilenceTaskPointExecRecord"})
    public int addSilenceTaskPointExecRecord(@RequestBody SilenceTaskPointExecRecord silenceTaskPointExecRecord) {
        return silenceTaskPointExecRecordService.insertSilenceTaskPointExecRecord(silenceTaskPointExecRecord);
    }

    @PostMapping({"/updatePatrolTask"})
    public int updatePatrolTask(@RequestBody PatrolTask patrolTask) {
        return patrolTaskService.updatePatrolTask(patrolTask);
    }

    @PostMapping({"/updateCameraPatrolTaskExecRecordState"})
    public void updateCameraPatrolTaskExecRecordState(String taskCode, String devNo, String state) {
        log.info("[TASK] UPDATE TASK EXEC STATUS, taskCode: {}, devNo: [{}], state: [{}]", devNo, state, taskCode);
        List<String> taskStates = new ArrayList<>();
        switch (state) {
            case "2":
                taskStates.add("3");
                break;
            case "3":
                taskStates.add("2");
                break;
            case "4":
                taskStates.add("2");
                taskStates.add("3");
                break;
        }

        List<PatrolTaskExecRecord> execRecords
                = patrolTaskExecRecordService.selectCameraPatrolTaskExecRecordList(taskCode, devNo, taskStates);
        //log.info("TASK EXEC RECORD LIST: {}", execRecords);
        if (!execRecords.isEmpty()) {
            if (TaskStatus.PAUSED.getCode().equals(state)) {
                updateTaskExecRecord(TaskStatus.PAUSED.getCode(), execRecords);
            } else if (TaskStatus.RUNNING.getCode().equals(state)) {
                updateTaskExecRecord(TaskStatus.RUNNING.getCode(), execRecords);
            } else if (TaskStatus.HALTED.getCode().equals(state)) {
                updateTaskExecRecord(TaskStatus.HALTED.getCode(), execRecords);
                redisService.deleteObjectOfTask(RedisConst.IMMEDIATELY_EXEC_TASK_TIME, taskCode);
                redisService.deleteObject(RedisConst.TASK_PATROL_STATE);
                redisService.deleteObject(RedisConst.TASK_PATROL_ID);

                String key = redisService.getCacheObjectOfTask(RedisConst.TASK_CURRENT_CODE, taskCode);
                if (key != null) {
                    log.info("[TASK] [{}] FINISH", key);
                    redisService.deleteObjectOfTask(RedisConst.TASK_CURRENT_CODE, taskCode);
                    log.info("[TASK] [{}] REMOVE FROM QUEUE", key);
                    redisService.deleteObject(key);
                }
            }
        }
    }

    private void updateTaskExecRecord(String state, List<PatrolTaskExecRecord> patrolTaskExecRecordList) {
        PatrolTaskExecRecord execRecord = patrolTaskExecRecordList.get(0);
        log.info("[TASK] MODIFY devNo:{},patrolId:{}", execRecord.getDevNo(), execRecord.getTaskPatrolId());
        List<PatrolTaskPointExecRecord> patrolTaskPointExecRecordList
                = patrolTaskPointExecRecordService.selectPatrolTaskPointExecRecordList(
                PatrolTaskPointExecRecord
                        .builder()
                        .patrolDeviceCode(execRecord.getDevNo())
                        .taskPatrolledId(execRecord.getTaskPatrolId())
                        .build()
        );
        if (!patrolTaskPointExecRecordList.isEmpty()) {
            PatrolTaskPointExecRecord patrolTaskPointExecRecord = patrolTaskPointExecRecordList.get(patrolTaskPointExecRecordList.size() - 1);
            log.info("[TASK] MODIFY devId:{}, pointId: {}", patrolTaskPointExecRecord.getDeviceId(), patrolTaskPointExecRecord.getPointId());
            execRecord.setExecPointId(patrolTaskPointExecRecord.getPointId());
            execRecord.setDeviceId(patrolTaskPointExecRecord.getDeviceId());
        } else {
            log.info("[TASK] MODIFY LIST EMPTY");
            List<PatrolTaskInfo> patrolTaskInfos = patrolTaskInfoService.selectPatrolTaskInfoList(
                    PatrolTaskInfo
                            .builder()
                            .devNo(execRecord.getDevNo())
                            .taskMajorId(execRecord.getTaskId().toString())
                            .build()
            );
            //log.info("[TASK] MODIFY LIST EMPTY, taskInfos:{}", patrolTaskInfos);
            if (!patrolTaskInfos.isEmpty()) {
                execRecord.setExecPointId(0L);
                execRecord.setDeviceId((patrolTaskInfos.get(0)).getDeviceId());
                //log.info("[TASK] MODIFY LIST EMPTY, taskInfos[0]:{}", patrolTaskInfos.get(0));
            }
        }

        execRecord.setTaskState(state);
        patrolTaskExecRecordService.updatePatrolTaskExecRecord(execRecord);
    }

    @PostMapping({"/isManualControl"})
    public boolean isManualControlPTZ(String devNo, HttpServletRequest request) {
        List<String> taskStates = new ArrayList<>();
        taskStates.add("2");
        List<PatrolTaskExecRecord> patrolTaskExecRecordList = patrolTaskExecRecordService.selectCameraPatrolTaskExecRecordList(StringUtils.EMPTY, devNo, taskStates);
        if (CollectionUtils.isNotEmpty(patrolTaskExecRecordList)) {
            return false;
        } else if (!patrolTaskExecRecordList.isEmpty()) {
            PatrolTaskExecRecord execRecord = patrolTaskExecRecordList.get(0);
            return JwtUtils.isAdmin(request) ? this.updatePatrolTaskExecRecordState(execRecord) : ("1".equals(execRecord.getTaskPriority()) && this.updatePatrolTaskExecRecordState(execRecord));
        } else {
            return true;
        }
    }

    private boolean updatePatrolTaskExecRecordState(PatrolTaskExecRecord execRecord) {
        PatrolTaskPointExecRecord patrolTaskPointExecRecord = new PatrolTaskPointExecRecord();
        patrolTaskPointExecRecord.setTaskPatrolledId(execRecord.getTaskPatrolId());
        List<PatrolTaskPointExecRecord> patrolTaskPointExecRecordList = patrolTaskPointExecRecordService.selectPatrolTaskPointExecRecordList(patrolTaskPointExecRecord);
        if (!patrolTaskPointExecRecordList.isEmpty()) {
            patrolTaskPointExecRecord = patrolTaskPointExecRecordList.get(patrolTaskPointExecRecordList.size() - 1);
            execRecord.setExecPointId(patrolTaskPointExecRecord.getPointId());
            execRecord.setDeviceId(patrolTaskPointExecRecord.getDeviceId());
        } else {
            PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
            patrolTaskInfo.setTaskMajorId(execRecord.getTaskId().toString());
            List<PatrolTaskInfo> patrolTaskInfoList = patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
            if (!patrolTaskInfoList.isEmpty()) {
                patrolTaskInfo = patrolTaskInfoList.get(0);
                execRecord.setExecPointId(Long.parseLong(patrolTaskInfo.getPresetCode()));
                execRecord.setDeviceId(patrolTaskInfo.getDeviceId());
            }
        }

        execRecord.setTaskState("3");
        execRecord.setManualPauseState("1");
        this.patrolTaskExecRecordService.updatePatrolTaskExecRecord(execRecord);
        return true;
    }

    @PostMapping({"/selectBasedataEqpbookList"})
    public List<EqpBook> selectBasedataEqpbookList(@RequestBody EqpBook basedataEqpBook) {
        return this.eqpBookService.selectBasedataEqpbookList(basedataEqpBook);
    }

    @PostMapping({"/selectBasedataEqpbookChannelList"})
    public List<EqpBookChannel> selectBasedataEqpbookChannelList(@RequestBody EqpBookChannel basedataEqpBookChannel) {
        return this.eqpBookChannelService.selectBasedataEqpBookChannelList(basedataEqpBookChannel);
    }

    @PostMapping({"/selectBasedataPatrolpointByPatrolpointId"})
    public DBPatrolPoint selectBasedataPatrolPointByPatrolPointId(@RequestBody Long patrolpointId) {
        return this.dbPatrolPointService.selectBasedataPatrolPointByPatrolPointId(patrolpointId);
    }

    @PostMapping({"/selectDictDataList"})
    public List<SysDictData> selectDictDataList(@RequestBody SysDictData dictData) {
        return DictUtils.getDictCache(Tags.DEFECT_TYPE);
    }

    @PostMapping({"/updatePatrolTaskStatus"})
    public int updatePatrolTaskStatus(@RequestBody PatrolTask patrolTask) {
        PatrolTask oldPatrolTask = patrolTaskService.selectPatrolTaskByTaskId(patrolTask.getTaskId());
        oldPatrolTask.setExecutionStatus(patrolTask.getExecutionStatus());
        return patrolTaskService.updatePatrolTask(oldPatrolTask);
    }

    @PostMapping({"/deletePatrolTaskExecRecord"})
    public void deletePatrolTaskExecRecord() {
        this.patrolTaskExecRecordService.deletePatrolTaskExecRecordByTaskState("2");
        this.patrolTaskExecRecordService.deletePatrolTaskExecRecordByTaskState("3");
    }

    @PostMapping({"/taskResultExised"})
    public boolean taskResultExited(String patrolDeviceCode, String taskPatrolledId) {
        PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
        patrolTaskStatus.setTaskPatrolledId(taskPatrolledId);
        List<PatrolTaskStatus> patrolTaskStatusList = this.patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
        if (CollectionUtils.isNotEmpty(patrolTaskStatusList)) {
            patrolTaskStatus = patrolTaskStatusList.get(0);
            if (100 > Integer.parseInt(patrolTaskStatus.getTaskProgress()) && "2".equals(patrolTaskStatus.getTaskState())) {
                PatrolResult patrolResult = new PatrolResult();
                patrolResult.setPatrolDeviceCode(patrolDeviceCode);
                patrolResult.setTaskPatrolledId(taskPatrolledId);
                List<PatrolResult> patrolResultList = this.patrolResultService.selectPatrolResultListOrderBy(patrolResult);
                return CollectionUtils.isEmpty(patrolResultList);
            }
        }

        return false;
    }

    private boolean isFixedTask(final PatrolTask patrolTask) {
        return patrolTask.getFixedStartTime() != null
                && ExecStatus.REGULAR.getCode().equals(patrolTask.getExecutionStatus());
    }

    private boolean isCycleTask(final PatrolTask patrolTask) {
        return ExecStatus.PERIODIC.getCode().equals(patrolTask.getExecutionStatus())
                && !StringUtils.isEmpty(patrolTask.getCycleExecuteTime())
                && patrolTask.getCycleStartTime() != null && patrolTask.getCycleEndTime() != null
                && DateUtils.toInt(DateUtils.yyyyMMdd, new Date()) >= DateUtils.toInt(DateUtils.yyyyMMdd, patrolTask.getCycleStartTime())
                && DateUtils.toInt(DateUtils.yyyyMMdd, new Date()) <= DateUtils.toInt(DateUtils.yyyyMMdd, patrolTask.getCycleEndTime());
    }

    private boolean isCycleTaskByWeek(final PatrolTask patrolTask) {
        return !StringUtils.isEmpty(patrolTask.getCycleWeek());
    }

    private boolean isCycleTaskByMonth(final PatrolTask patrolTask) {
        return !StringUtils.isEmpty(patrolTask.getCycleMonth());
    }

    private boolean isInterTask(final PatrolTask patrolTask) {
        return ExecStatus.INTERVAL.getCode().equals(patrolTask.getExecutionStatus())
                && !StringUtils.isEmpty(patrolTask.getIntervalExecuteTime())
                && patrolTask.getIntervalStartTime() != null && patrolTask.getIntervalEndTime() != null
                && DateUtils.toInt(DateUtils.yyyyMMdd, new Date()) >= DateUtils.toInt(DateUtils.yyyyMMdd, patrolTask.getIntervalStartTime())
                && DateUtils.toInt(DateUtils.yyyyMMdd, new Date()) <= DateUtils.toInt(DateUtils.yyyyMMdd, patrolTask.getIntervalEndTime());
    }

    private boolean isInterTaskByHour(final PatrolTask patrolTask) {
        return IntervalType.BY_HOUR.getCode().equals(patrolTask.getIntervalType());
    }

    private boolean isInterTaskByMinute(final PatrolTask patrolTask) {
        return IntervalType.BY_MINUTE.getCode().equals(patrolTask.getIntervalType());
    }

    private boolean isInterTaskByDate(final PatrolTask patrolTask) {
        return IntervalType.BY_DATE.getCode().equals(patrolTask.getIntervalType());
    }

    @GetMapping({"/getFilterPatrolTaskList"})
    List<PatrolTask> getFilterPatrolTaskList(String taskCode) {
        logger.info("getFilterPatrolTaskList param: {}", taskCode);
        return filterPatrolTaskList(PatrolTask.builder().taskCode(taskCode).build());
    }

    @PostMapping({"/makeCurrentDayTask"})
    public Map<String, List<PatrolTask>> makeCurrentDayTask() {
        try {
            Map<String, List<PatrolTask>> taskMainMap = new HashMap<>();
            logger.debug("[GABRIEL] day: {}, hour: {}, minute: {}", DateUtils.getDayInt(), DateUtils.getHourInt(), DateUtils.getMinuteInt());
            List<PatrolTask> patrolTaskList = patrolTaskService.selectPatrolTaskList(PatrolTask.builder().isEnable("0").build());
            if (patrolTaskList.isEmpty())
                return taskMainMap;

            //List<Date> exeTimes;
            for (PatrolTask task : patrolTaskList) {
                if (StringUtils.isEmpty(task.getDevType())) {
                    continue;
                }
                // 定期执行
                if (isFixedTask(task)) {
                    //logger.info("[TASK] REGULAR fixedDay: {}", fixedDay);
                    String fixedDay = DateUtils.format(DateUtils.yyyyMMdd, task.getFixedStartTime());
                    if (DateUtils.format(DateUtils.yyyyMMdd, new Date()).equals(fixedDay)) {
                        log.debug("[GABRIEL] break the out while");
                        List<PatrolTask> patrolTasks = getPatrolTasks(task);
                        for (PatrolTask patrolTask : patrolTasks) {
                            String[] devNos = patrolTask.getDevNo().split(StringUtils.COMMA);
                            PatrolTaskExecRecord taskExecRecord = patrolTaskExecRecordService.selectPatrolTaskExecRecordByTaskPatrolId(devNos[0] + "_" + task.getTaskCode() + "_" + DateUtils.format(DateUtils.yyyyMMddHHmmss, task.getFixedStartTime()));
                            String key = RedisConst.TASK_CODE + task.getTaskCode() + StringUtils.AT + DateUtils.format(DateUtils.yyyyMMddHHmmss2, task.getFixedStartTime());
                            //log.info("[GABRIEL] key6: {}", key);
                            if (taskExecRecord == null) {
                                redisService.setCacheObject(key, JSONArray.toJSONString(patrolTasks));
                            }
                        }
                    }
                } else if (isCycleTask(task)) {
                    // 周期执行
                    if (isCycleTaskByWeek(task)) {
                        String[] weekList = task.getCycleWeek().split(StringUtils.COMMA);
                        String[] cycleTimes = task.getCycleExecuteTime().split(StringUtils.COMMA);
                        for (int i = 0; i < weekList.length; ++i) {
                            String dayOfWeek = weekList[i];
                            if (!DateUtils.getDayOfWeek(new Date()).equals(dayOfWeek)) {
                                continue;
                            }

                            task.setFixedStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, (DateUtils.format(DateUtils.yyyyMMdd2, new Date()) + " " + cycleTimes[i])));
                            final String taskType = "CYCLE-BY-WEEK";
                            parseTaskToRedis(taskType, task, null);
                        }
                    } else if (isCycleTaskByMonth(task)) {
                        String[] monthList = task.getCycleMonth().split(StringUtils.COMMA);
                        String[] cycleTimes = task.getCycleExecuteTime().split(StringUtils.COMMA);
                        for (int i = 0; i < monthList.length; ++i) {
                            String month = monthList[i];
                            if (DateUtils.getDayInt() != Integer.parseInt(month) || task.getCycleExecuteTime() == null) {
                                continue;
                            }

                            task.setFixedStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, (DateUtils.format(DateUtils.yyyyMMdd2, new Date()) + " " + cycleTimes[i])));
                            final String taskType = "CYCLE-BY-MONTH";
                            parseTaskToRedis(taskType, task, null);
                        }
                    }
                } else if (isInterTask(task)) {
                    // 间隔执行
                    String[] intervalExecuteTime = task.getIntervalExecuteTime().split(StringUtils.COLON);
                    if (isInterTaskByHour(task)) {
                        // 按小时执行
                        int intervalNumber = task.getIntervalNumber();
                        if (intervalNumber > 0) {
                            List<Date> exeTimes = getExecTimes(task.getIntervalExecuteTime(), DateUtils.format(DateUtils.yyyyMMddHHmmss2, task.getIntervalStartTime()), DateUtils.format(DateUtils.yyyyMMddHHmmss2, task.getIntervalEndTime()), intervalNumber);
//                            List<Date> exeTimes = getExecTimesOld(task.getIntervalExecuteTime(), intervalNumber);
                            for (Date exeTime : exeTimes) {
                                logger.debug("[TASK] {}， isInterTaskByHour exeTime: {}", task.getTaskCode(), DateUtils.format(DateUtils.yyyyMMddHHmmss2, exeTime));
                                task.setFixedStartTime(exeTime);
                                final String taskType = "INTER-BY-HOUR";
                                parseTaskToRedis(taskType, task, task.getIntervalEndTime());
                            }
                        } else {
                            log.info("[TASK] isInterTaskByHour intervalNumber error: {}", intervalNumber);
                        }
                    } else if (isInterTaskByMinute(task)) {
                        // 按分钟执行
                        int intervalNumber = task.getIntervalNumber();
                        if (intervalNumber > 0) {
                            // 取当天的执行时间
                            String endTime = DateUtils.format(DateUtils.YYYY_MM_DD, DateUtils.addDays(task.getIntervalStartTime(), 1)) + " 00:00:00";
                            List<Date> exeTimes = getExecTimesByMinute(task.getIntervalExecuteTime(), DateUtils.format(DateUtils.yyyyMMddHHmmss2, task.getIntervalStartTime()), endTime, intervalNumber);
                            if (exeTimes.size() > 0) {
//                                Date date = exeTimes.get(exeTimes.size() - 1);
                                for (Date exeTime : exeTimes) {
                                    task.setFixedStartTime(exeTime);
                                    final String taskType = "INTER-BY-MINUTE";
                                    parseTaskToRedis(taskType, task, task.getIntervalEndTime());
                                }
                            }
                        } else {
                            log.info("[TASK] isInterTaskByMinute intervalNumber error: {}", intervalNumber);
                        }
                    } else if (isInterTaskByDate(task)) {
                        for (int j = 0; j < task.getIntervalNumber(); ++j) {
                            if (j != 0) {
                                intervalExecuteTime[0] = String.valueOf(Integer.parseInt(intervalExecuteTime[0]) + 1);
                            }

                            String time = intervalExecuteTime[0] + ":" + DateUtils.getMinuteInt() + ":" + intervalExecuteTime[2];
                            task.setFixedStartTime(DateUtils.parse(DateUtils.yyyyMMddHHmmss2, (DateUtils.format(DateUtils.yyyyMMdd2, new Date()) + " " + time)));
                            final String taskType = "INTER-BY-DATE";
                            parseTaskToRedis(taskType, task, null);
                        }
                    }
                }
            }
            return taskMainMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void parseTaskToRedis(final String taskType, PatrolTask task, Date finalDate) {
        if (StringUtils.isNotEmpty(task.getDevNo())) {
            String[] devNos = task.getDevNo().split(StringUtils.COMMA);
            List<String> devNoList = new ArrayList<>();
            String[] devTypes = task.getDevType().split(StringUtils.COMMA);
            for (int i = 0; i < devTypes.length; ++i) {
//                if ("2".equals(devTypes[i])) {
                    devNoList.add(devNos[i]);
//                }
            }

            if(devNoList.isEmpty()) {
                log.info(Color.MAGENTA + "PARSE_TASK NON-VL TASK taskCode: {}, devType: {}, devNo: {}" + Color.END,
                        task.getTaskCode(),
                        task.getDevType(),
                        task.getDevNo());
                return;
            }

            String key = RedisConst.TASK_CODE + task.getTaskCode() + StringUtils.AT + DateUtils.format(DateUtils.yyyyMMddHHmmss2, task.getFixedStartTime());
            String taskPatrolledId = devNoList.get(0) + "_" + task.getTaskCode() + "_" + DateUtils.format(DateUtils.yyyyMMddHHmmss, task.getFixedStartTime());
            log.debug(Color.GREEN + "[TASK] TYPE: {}, DETACH PATROLLED ID: {}" + Color.END, taskType, taskPatrolledId);
            PatrolTaskExecRecord taskExecRecord
                    = patrolTaskExecRecordService.selectPatrolTaskExecRecordByTaskPatrolId(taskPatrolledId);
            if (taskExecRecord == null) {
                List<PatrolTask> patrolTasks = getPatrolTasks(task);
                if (!patrolTasks.isEmpty()) {
                    if(finalDate != null) {
                        Collection<String> redisKeys = redisService.keys(RedisConst.TASK_CODE + task.getTaskCode() + StringUtils.AT + "*");
                        for (String redisKey : redisKeys) {
                            String[] keywords = StringUtils.split(redisKey, StringUtils.AT);
                            if (keywords.length == 3) {
                                String fixedStartTime = keywords[2];
                                if (DateUtils.parse(DateUtils.yyyyMMddHHmmss2, fixedStartTime).after(finalDate)) {
                                    redisService.deleteObject(redisKey);
                                }
                            }
                        }
                    }
                    logger.debug(Color.GREEN + "[TASK] TYPE: {}, CYCLE BY WEEK key: {}, patrolId: {}" + Color.END, taskType, key, taskPatrolledId);
                    redisService.setCacheObject(key, JSONArray.toJSONString(patrolTasks));
                }
            }
        } else {
            logger.info(Color.RED + "[TASK] TASK TYPE: {}, devNo is empty!" + Color.END, taskType);
        }
    }

    private List<Date> getExecTimesOld(String exeTime, int num) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDay1 = sdf1.format(new Date());
        List<Date> exeTimes = new ArrayList<>();
        String format = "HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);

        try {
            Date startTime = sdf.parse("00:00:01");
            Date endTime = sdf.parse("24:00:00");
            if (DateUtil.isIn(sdf.parse(exeTime), startTime, endTime)) {
                exeTimes.add(sdfTime.parse(currentDay1 + " " + exeTime));
            }

            String hour = exeTime.split(StringUtils.COLON)[0];
            String minute = exeTime.split(StringUtils.COLON)[1];
            String second = exeTime.split(StringUtils.COLON)[2];
            int count = 24 / num;
            int hourNum = Integer.parseInt(hour);

            for (int i = 0; i < count; ++i) {
                hourNum += num;
                if (hourNum > Integer.parseInt(hour)) {
                    Date nowTime = sdf.parse(hourNum + StringUtils.COLON + minute + StringUtils.COLON + second);
                    if (DateUtil.isIn(nowTime, startTime, endTime)) {
                        exeTimes.add(sdfTime.parse(currentDay1 + " " + hourNum + ":" + minute + ":" + second));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return exeTimes;
    }

    private List<Date> getExecTimes(String exeTime, String intervalStartTime, String intervalEndTime, int intervalNumber) {
        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
        List<Date> exeTimes = new ArrayList<>();

        try {
            // 解析时间参数
            Date startDateTime = sdfDateTime.parse(intervalStartTime);
            Date endDateTime = sdfDateTime.parse(intervalEndTime);
            Date exeTimeToday = sdfDateTime.parse(
                    intervalStartTime.substring(0, 10) + " " + exeTime);

            // 确定实际开始时间（取exeTime和intervalStartTime中较晚的一个）
            Date actualStartTime = exeTimeToday.after(startDateTime) ? exeTimeToday : startDateTime;

            // 检查开始时间是否超过结束时间
            if (actualStartTime.after(endDateTime)) {
                return exeTimes; // 返回空列表
            }

            // 检查间隔是否有效
            if (intervalNumber <= 0) {
                exeTimes.add(actualStartTime);
                return exeTimes;
            }

            // 生成时间点列表
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(actualStartTime);

            while (!calendar.getTime().after(endDateTime)) {
                exeTimes.add(calendar.getTime());
                calendar.add(Calendar.HOUR_OF_DAY, intervalNumber);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return exeTimes;
    }

    private List<Date> getExecTimesByMinute(String exeTime, String intervalStartTime, String intervalEndTime, int intervalMinutes) {
        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
        List<Date> exeTimes = new ArrayList<>();

        try {
            // 解析时间参数
            Date startDateTime = sdfDateTime.parse(intervalStartTime);
            Date endDateTime = sdfDateTime.parse(intervalEndTime);

            // 构建当天的执行时间（使用intervalStartTime的日期部分）
            Date exeTimeToday = sdfDateTime.parse(
                    intervalStartTime.substring(0, 10) + " " + exeTime);

            // 确定实际开始时间（取exeTime和intervalStartTime中较晚的一个）
            Date actualStartTime = exeTimeToday.after(startDateTime) ? exeTimeToday : startDateTime;

            // 检查开始时间是否超过结束时间
            if (actualStartTime.after(endDateTime)) {
                return exeTimes; // 返回空列表
            }

            // 检查间隔是否有效
            if (intervalMinutes <= 0) {
                exeTimes.add(actualStartTime);
                return exeTimes;
            }

            // 生成时间点列表（按分钟间隔）
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(actualStartTime);

            while (!calendar.getTime().after(endDateTime)) {
                exeTimes.add(calendar.getTime());
                calendar.add(Calendar.MINUTE, intervalMinutes);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return exeTimes;
    }

    @PostMapping({"/execCurrentDayTask"})
    public void execCurrentDayTask() throws ParseException {
//        String taskCodeStr = redisService.getCacheObject(RedisConst.TASK_CURRENT_CODE);
//        if (!StringUtils.isEmpty(taskCodeStr)) {
//            this.log.info("      【当前正在执行的任务：{}, 其它任务不能执行！！！】", taskCodeStr);
//        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (String key : this.redisService.keys(RedisConst.TASK_CODE_EX)) {
                String fixedStartTime = key.split(StringUtils.AT)[2];
                long currentMinutes = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis());
                long fixedStartMinutes = TimeUnit.MILLISECONDS.toMinutes(sdf.parse(fixedStartTime).getTime());
                if (currentMinutes == fixedStartMinutes) {
                    extracted(key, key);
                } else if (currentMinutes > fixedStartMinutes) {
                    extracted(key, key);
                }
            }
//        }
    }

    @PostMapping({"/execDeviceTask"})
    private void execDeviceTask(@RequestBody List<PatrolTask> patrolTaskListEx) {
        String sendCode = "";
        BasedataEqpBookMoMain basedataEqpBookMoMain = new BasedataEqpBookMoMain();
        basedataEqpBookMoMain.setType("20");// type:20 - robot
        List<BasedataEqpBookMoMain> basedataEqpBookMoMains = this.patrolResultService.selectBasedataEqpBookList(basedataEqpBookMoMain);
        if (!basedataEqpBookMoMains.isEmpty()) {
            sendCode = basedataEqpBookMoMains.get(0).getPatrolDeviceCode();
        }
        for (PatrolTask patrolTask : patrolTaskListEx) {
            if (StringUtils.isNotEmpty(patrolTask.getDevNo())) {
                String[] devTypes = patrolTask.getDevType().split(StringUtils.COMMA);
                String[] devNos = patrolTask.getDevNo().split(StringUtils.COMMA);
                List<String> pilotTaskCmds = new ArrayList<>();
                for (int i = 0; i < devNos.length; i++) {
                    log.info("execDeviceTask devNo: {}, devType: {}", devNos[i], devTypes[i]);

                    BasedataEqpBookMoMain basedataEqpbookMomain = new BasedataEqpBookMoMain();
                    basedataEqpbookMomain.setPatrolDeviceCode(devNos[i]);
                    List<BasedataEqpBookMoMain> eqpBookMoMains = patrolResultService.selectBasedataEqpBookList(basedataEqpbookMomain);
                    String receiveCode = "";
                    if (!eqpBookMoMains.isEmpty() && eqpBookMoMains.get(0).getMainSystemCode() != null) {
                        receiveCode = eqpBookMoMains.get(0).getMainSystemCode();
                    }
                    if (StringUtils.isNotEmpty(receiveCode)) {
                        log.info("定时任务--无人机-机器人任务构建, receiveCode: {}, devType: {}, devNo: {}", receiveCode, patrolTask.getDevType(), patrolTask.getDevNo());
                        // 判断任务点位是否在检修区域内
                        if (patrolTaskStatusController.isWithinMaintainRegion(patrolTask.getTaskCode(), patrolTask.getDevNo())) {
                            log.info("该任务点位在检修区域内 taskCode: {}，sendCode: {}", patrolTask.getTaskCode(), patrolTask.getDevNo());
                        } else {
                            SendTask sendTask = new SendTask();
                            sendTask.setReceiveCode(receiveCode);
                            sendTask.setSendCode(sendCode);
                            sendTask.setCode(patrolTask.getTaskId() + "");
                            sendTask.setType("41");
                            sendTask.setCommand("1");
                            String pilotTaskCmd = JSONObject.toJSONString(sendTask);
                            pilotTaskCmds.add(pilotTaskCmd);
                        }
                    }
                }

                if (pilotTaskCmds.isEmpty()) {
                    redisService.deleteObjectOfTask(RedisConst.TASK_CURRENT_CODE, patrolTask.getTaskCode());
                }

                // 下发无人机-机器人任务
                for (String pilotTaskCmd : pilotTaskCmds) {
                    log.info("定时任务--无人机-机器人任务执行, pilotTaskCmd: {}", pilotTaskCmd);
                    try {
                        this.feignTaskClient.sendCommand(pilotTaskCmd);
                    } catch (Exception e) {
                        log.error("定时任务--无人机-机器人任务下发异常: {}", e.getMessage());
                    }
                }
            }
        }
    }

    private void extracted(String key, String taskCode) {
        log.info(Color.RED + "[EXEC] Add new task [{}]" + Color.END, key);//日志里没搜到
        redisService.setCacheObjectOfTask(RedisConst.TASK_CURRENT_CODE, taskCode, key, 4L, TimeUnit.HOURS);
        log.info("[EXEC] key: {}", key);
        List<PatrolTask> cameraPatrolTasks = redisService.getCacheObject(key);
        if (!cameraPatrolTasks.isEmpty()) {
            cameraPatrolTasks.forEach((patrolTask) -> {
                log.info("[EXEC] TASK CODE - {} - DEV NO- {}", patrolTask.getTaskCode(), patrolTask.getDevNo());
            });
        }

    }

    private List<PatrolTask> remakePatrolTaskList(PatrolTask task) {
        String[] devNos = task.getDevNo().split(StringUtils.COMMA);
        String[] devTypes = task.getDevType().split(StringUtils.COMMA);
        List<PatrolTask> patrolTaskList = new ArrayList<>();
        if (devNos.length != devTypes.length) {
            log.warn("[TASK] devNos length != devTypes.length: {}, {}", devNos.length, devTypes.length);
            return patrolTaskList;
        }
        List<String> devTypeList = new ArrayList<>();
        List<String> devNoList = new ArrayList<>();
        for (int i = 0; i < devTypes.length; ++i) {
//            if (!"2".equals(devTypes[i])) {
//                continue;
//            }
            devTypeList.add(devTypes[i]);
            devNoList.add(devNos[i]);

        }
        String devNoListStr = StringUtils.join(devNoList, StringUtils.COMMA);
        String devTypeListStr = StringUtils.join(devTypeList, StringUtils.COMMA);
        log.debug("[TASK] devNoListStr: {}", devNoListStr);
        log.debug("[TASK] devTypeListStr: {}", devTypeListStr);
        PatrolTask patrolTask = PatrolTask.builder()
                .taskId(task.getTaskId())
                .stationName(task.getStationName())
                .stationCode(task.getStationCode())
                .type(task.getType())
                .taskCode(task.getTaskCode())
                .taskName(task.getTaskName())
                .priority(task.getPriority())
                .deviceLevel(task.getDeviceLevel())
                .deviceList(task.getDeviceList())
                .fixedStartTime(task.getFixedStartTime())
                .cycleMonth(task.getCycleMonth())
                .cycleWeek(task.getCycleWeek())
                .cycleExecuteTime(task.getCycleExecuteTime())
                .cycleStartTime(task.getCycleStartTime())
                .cycleEndTime(task.getCycleEndTime())
                .intervalNumber(task.getIntervalNumber())
                .intervalType(task.getIntervalType())
                .intervalExecuteTime(task.getIntervalExecuteTime())
                .intervalStartTime(task.getIntervalStartTime())
                .intervalEndTime(task.getIntervalEndTime())
                .invalidStartTime(task.getInvalidStartTime())
                .invalidEndTime(task.getInvalidEndTime())
                .isEnable(task.getIsEnable())
                .linkageState(task.getLinkageState())
                .devType(devTypeListStr)
                .drafter(task.getDrafter())
                .fileStatus(task.getFileStatus())
                .taskCycle(task.getTaskCycle())
                .devNo(devNoListStr)
                .taskProgress(task.getTaskProgress())
                .taskState(task.getTaskState())
                .executionMode(task.getExecutionMode())
                .beginTime(task.getBeginTime())
                .endTime(task.getEndTime())
                .areaId(task.getAreaId())
                .areaName(task.getAreaName())
                .specifiedAlg(task.getSpecifiedAlg())
                .build();
        patrolTaskList.add(patrolTask);
        return patrolTaskList;
    }

    private List<PatrolTask> filterPatrolTaskList(PatrolTask taskParam) {
        List<PatrolTask> patrolTaskListEx = patrolTaskService.selectPatrolTaskList(taskParam);
        if (patrolTaskListEx.isEmpty())
            return new ArrayList<>();

        PatrolTask task = patrolTaskListEx.get(0);
        return remakePatrolTaskList(task);
    }

    private List<PatrolTask> getPatrolTasks(PatrolTask task) {
        return remakePatrolTaskList(task);
    }

    @PostMapping({"/getPatrolTaskStatusByTaskPatrolledId"})
    public PatrolTaskStatus getPatrolTaskStatusByTaskPatrolledId(String taskPatrolledId) {
        PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
        patrolTaskStatus.setTaskPatrolledId(taskPatrolledId);
        List<PatrolTaskStatus> list = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
        return CollectionUtils.isNotEmpty(list) ? list.get(0) : null;
    }

    @PostMapping({"/getConfigByKey"})
    public String getConfigByKey(@RequestBody String key) {
        String value = patrolTaskService.selectConfigByKey(key);
        logger.info("-------------------getConfigByKey key: {}, value: {}", key, value);
        if(StringUtils.isBlank(value)) {
            return "";
        } else {
            return value.trim();
        }
    }

    @PostMapping({"/getAlgTypeListByPatrolPointId"})
    public Map<String, String> getAlgTypeListByPatrolPointId(@RequestBody final String patrolPointId) {
        return patrolResultService.selectAlgorithmType(patrolPointId);
    }

    @PostMapping({"/getAlgSubtypeIdsByPatrolPointId"})
    public String getAlgSubtypeIdsByPatrolPointId(@RequestBody String patrolPointId) {
       return patrolTaskInfoService.selectAlgSubtypeIdsByPatrolPointId(patrolPointId);
    }

    public static void main(String[] args) throws ParseException {
//        PatrolTaskExecController patrolTaskExecController = new PatrolTaskExecController(null, null, null, null,null, null, null,null,null,null,null, null, null, null,null);
////        List<Date> execTimes = patrolTaskExecController.getExecTimes("09:00:00","2025-06-12 00:00:00","2025-06-12 16:00:00", 1);
////        System.out.println(execTimes);
//        System.out.println(DateUtils.format(DateUtils.yyyyMMddHHmmss2, new Date()));
//        List<Date> execTimesByMinute = patrolTaskExecController.getExecTimes("09:35:16", "2025-06-12 10:38:00", "2025-06-12 16:00:00", 2);
//        System.out.println(execTimesByMinute);
//        System.out.println("==========================================================");
//
//        List<Date> execTimesOld = patrolTaskExecController.getExecTimesOld("09:00:00", 1);
//        System.out.println(execTimesOld);
//
//        String redisKey = "TASK_CODE@1353@2025-06-12 16:01:00";
//        String[] keywords = StringUtils.split(redisKey, StringUtils.AT);
//        if (keywords.length == 3) {
//            String fixedStartTime = keywords[2];
//            if (DateUtils.parse(DateUtils.yyyyMMddHHmmss2,fixedStartTime).after(DateUtils.parse(DateUtils.yyyyMMddHHmmss2,"2025-06-12 16:00:00"))) {
//                System.out.println("111");
//            }
//        }
//        Date actualStartTime = DateUtils.parse(DateUtils.yyyyMMddHHmmss2, "2025-06-12 16:00:00");
//        if (actualStartTime.before(new Date())) {
//            System.out.println("2222");
//            actualStartTime = new Date();
//        }
//        List<Date> execTimes = patrolTaskExecController.getExecTimesByMinute("13:00:00", "2025-06-14 16:00:00", "2025-06-14 19:10:00", 4);
//        System.out.println("=================================");
//        System.out.println(execTimes);
//        System.out.println("============");
////        Date parse = DateUtils.parse(DateUtils.yyyyMMddHHmmss2, "2025-06-13 17:07:32");
////        long planTime = DateUtils.parse(DateUtils.yyyyMMddHHmmss2, "2025-06-13 17:07:32").getTime();
////        System.out.println(parse);
////        System.out.println(planTime);
//
//        String fixedStartTime = "2025-06-14 08:47:32";
//        long planTime = DateUtils.parse(DateUtils.yyyyMMddHHmmss2, fixedStartTime).getTime();
//        long fixedDays = TimeUnit.MILLISECONDS.toDays(planTime);
//        long fixedStartMinutes = TimeUnit.MILLISECONDS.toMinutes(planTime);
//        System.out.println("fixedDays: " + fixedDays);
//        System.out.println("fixedStartMinutes: " + fixedStartMinutes);
//        System.out.println("planTime: "+ planTime);
//
//        long currentTime = DateUtils.parse(DateUtils.yyyyMMddHHmmss2, "2025-06-14 09:07:32").getTime();
//        long currentDays = TimeUnit.MILLISECONDS.toDays(currentTime);
//        long currentMinutes = TimeUnit.MILLISECONDS.toMinutes(currentTime);
//        System.out.println("currentDays: " + currentDays);
//        System.out.println("currentMinutes: " + currentMinutes);
//        System.out.println("currentTime: "+ currentTime);
//
//        if (currentDays == fixedDays && currentMinutes >= fixedStartMinutes) {
//            System.out.println("333");
//        }
//        System.out.println("============下面开始===============");
//
//        fixedStartTime = "2025-06-14 00:07:32";
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        // 解析字符串为 Date
//        Date fixedDate = sdf.parse(fixedStartTime);
//        Date currentDate = sdf.parse(fixedStartTime); // 当前时间
//
//        // 比较时间（精确到分钟）
//        SimpleDateFormat minuteFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        String fixedMinute = minuteFormat.format(fixedDate);
//        String currentMinute = minuteFormat.format(currentDate);
//
////        if (fixedMinute.equals(currentMinute)) {
////            System.out.println("fixedStartTime 和当前时间完全相同（精确到分钟）");
////        } else {
//            // 计算分钟差值（绝对值）
//            long diffMinutes = Math.abs((fixedDate.getTime() - currentDate.getTime()) / (60 * 1000));
//
//            if (diffMinutes <= 1) {
//                System.out.println("fixedStartTime 和当前时间相差不超过1分钟");
//            } else if (fixedDate.after(currentDate)) {
//                System.out.println("fixedStartTime 是未来时间（相差超过1分钟）");
//            } else {
//                System.out.println("fixedStartTime 是过去时间（相差超过1分钟）");
//            }
////        }
//
//        // 判断是否同一天
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        String fixedDay = dateFormat.format(fixedDate);
//        String currentDay = dateFormat.format(currentDate);
//
//        if (fixedDay.equals(currentDay)) {
//            System.out.println("fixedStartTime 和当前时间是同一天");
//        } else {
//            System.out.println("fixedStartTime 和当前时间不是同一天");
//        }


        System.out.println("====================");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 解析字符串为 Date
        String fixedStartTime = "2025-06-16 11:30:00";
        Date fixedDate1 = sdf.parse(fixedStartTime);

        Date currentDate1 = sdf.parse("2025-06-16 11:30:11"); // 当前时间

        // 判断是否同一天
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String fixedDay1 = dateFormat1.format(fixedDate1);
        String currentDay1 = dateFormat1.format(currentDate1);

        long value = currentDate1.getTime() - fixedDate1.getTime();
        System.out.println(value);
        long diffMinutes1 = (currentDate1.getTime() - fixedDate1.getTime()) / (60 * 1000);
        System.out.println(diffMinutes1);
        if(fixedDay1.equals(currentDay1) && (diffMinutes1 >= 0 && diffMinutes1 <= 1 && fixedDate1.before(currentDate1) || fixedDate1.getTime() == currentDate1.getTime())) {
            System.out.println("hhhrhheh");
        }

        if(fixedDay1.equals(currentDay1) && (value >= 0 && value <= 60000 && fixedDate1.before(currentDate1) || fixedDate1.getTime() == currentDate1.getTime())) {
            System.out.println("过期时间没超过1分钟");
        }
    }
}
