package com.inspect.taskstatus.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.inspect.analysis.domain.ResultAnalysis;
import com.inspect.analysis.domain.ResultAnalysisSummaryDTO;
import com.inspect.analysis.service.IResultAnalysisService;
import com.inspect.base.core.constant.AlgConstants;
import com.inspect.base.core.constant.RedisConst;
import com.inspect.base.core.domain.maintain.MaintainRegion;
import com.inspect.base.core.enums.TaskStatus;
import com.inspect.base.core.enums.TaskType;
import com.inspect.base.core.utils.DateUtils;
import com.inspect.base.core.utils.DescUtil;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.PageDomain;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.base.core.web.page.TableSupport;
import com.inspect.base.redis.service.RedisService;
import com.inspect.calender.domain.DailyTaskStatsDTO;
import com.inspect.calender.enums.TaskStateEnum;
import com.inspect.calender.service.TaskCalendarGenerator;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.maintain.service.IMaintainRegionService;
import com.inspect.partrolresult.service.IPatrolResultService;
import com.inspect.resultmain.domain.PatrolTaskResultMain;
import com.inspect.resultmain.service.IPatrolTaskResultMainService;
import com.inspect.system.base.openDomain.BasedataEqpBookMoMain;
import com.inspect.task.controller.PatrolTaskController;
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.FeignJobTaskClient;
import com.inspect.taskstatus.client.FeignTaskClient;
import com.inspect.taskstatus.domain.PatrolTaskStatus;
import com.inspect.taskstatus.domain.TaskCount;
import com.inspect.taskstatus.service.IPatrolTaskStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

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

    private final IPatrolTaskStatusService patrolTaskStatusService;
    private final IPatrolResultService patrolResultService;
    private final IPatrolTaskService patrolTaskService;
    private final FeignTaskClient feignTaskClient;
    private final FeignJobTaskClient feignJobTaskClient;
    private final RedisService redisService;
    private PatrolTaskController patrolTaskController;
    private IPatrolTaskResultMainService patrolTaskResultMainService;

    @Resource
    private IResultAnalysisService resultAnalysisService;

    @Resource
    private IPatrolTaskInfoService patrolTaskInfoService;

    @Resource
    private TaskCalendarGenerator taskCalendarGenerator;

    @Resource
    private IMaintainRegionService maintainRegionService;

    public PatrolTaskStatusController(
            PatrolTaskController patrolTaskController,
            IPatrolTaskStatusService patrolTaskStatusService,
            IPatrolResultService patrolResultService,
            IPatrolTaskService patrolTaskService,
            FeignTaskClient feignTaskClient,
            FeignJobTaskClient feignJobTaskClient,
            RedisService redisService,
            IPatrolTaskResultMainService patrolTaskResultMainService) {
        this.patrolTaskController = patrolTaskController;
        this.patrolTaskStatusService = patrolTaskStatusService;
        this.patrolResultService = patrolResultService;
        this.patrolTaskService = patrolTaskService;
        this.feignTaskClient = feignTaskClient;
        this.feignJobTaskClient = feignJobTaskClient;
        this.redisService = redisService;
        this.patrolTaskResultMainService = patrolTaskResultMainService;
    }

//    @GetMapping({"/list"})
//    public TableDataInfo list(PatrolTaskStatus patrolTaskStatus) {
//        this.startPage();
//        List<PatrolTaskStatus> patrolTaskStatusList = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
//        for (PatrolTaskStatus taskStatus : patrolTaskStatusList) {
//            if (StringUtils.isNotEmpty(taskStatus.getTaskCode())) {
//                List<PatrolTask> patrolTaskList = patrolTaskService.selectPatrolTaskList(PatrolTask.builder().taskCode(taskStatus.getTaskCode()).build());
//                if (!patrolTaskList.isEmpty()) {
//                    PatrolTask task = patrolTaskList.get(0);
//                    if (StringUtils.isNotEmpty(task.getType())) {
//                        taskStatus.setPatrolType(task.getType());
//                    }
//                }
//            }
//
//            if (StringUtils.isNotEmpty(taskStatus.getTaskPatrolledId())) {
//                PatrolResult patrolResult = new PatrolResult();
//                patrolResult.setTaskPatrolledId(taskStatus.getTaskPatrolledId());
//                List<PatrolResult> patrolResultList = patrolResultService.selectPatrolResultList(patrolResult);
//                if (!patrolResultList.isEmpty()) {
//                    taskStatus.setPointCount(String.valueOf(patrolResultList.size()));
//                    for (PatrolResult patrolResultTemp : patrolResultList) {
//                        if (StringUtils.isNotEmpty(patrolResultTemp.getValid())) {
//                            if (patrolResultTemp.getValid().equals("0")) {
//                                taskStatus.setPatrolStatus("0");
//                            } else {
//                                taskStatus.setPatrolStatus("1");
//                            }
//                        } else {
//                            taskStatus.setPatrolStatus("1");
//                        }
//                    }
//                } else {
//                    taskStatus.setPatrolStatus("1");
//                }
//            } else {
//                taskStatus.setPatrolStatus("1");
//            }
//        }
//        log.info("[GAB] count: {}", patrolTaskStatusList.size());
//        return getDataTable(patrolTaskStatusList);
//    }
    // 仅支持查询一天的任务
    @GetMapping({"/v2/list"})
    public TableDataInfo listV2(PatrolTaskStatus patrolTaskStatus) {
        String beginTime = patrolTaskStatus.getBeginTime();
        LocalDate beginLocalDate = LocalDate.parse(beginTime);
        Date beginDate = Date.from(beginLocalDate.atStartOfDay(java.time.ZoneId.systemDefault()).toInstant());
        patrolTaskStatus.setCreateTime(beginDate);
        List<PatrolTaskStatus> list = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
        if (StringUtils.isNotEmpty(beginTime)) {
            String[] beginTimeArr = beginTime.split("-");
            int year = Integer.parseInt(beginTimeArr[0]);
            int month = Integer.parseInt(beginTimeArr[1]);
            int day = Integer.parseInt(beginTimeArr[2]);
            List<DailyTaskStatsDTO> futureCalendar = taskCalendarGenerator.getFutureCalendar(year, month, day);
            List<PatrolTaskStatus> futureList = futureCalendar.stream().map(item ->
                    PatrolTaskStatus.builder()
                            .startTime(Date.from(item.getStartTime().atZone(ZoneId.systemDefault()).toInstant()))
                            .taskName(item.getName())
                            .taskCode(item.getId())
                            .taskPatrolledId(item.getId())
                            .patrolStatus(item.getTaskState().toString())
                            .taskState(item.getTaskState().toString())
                            .taskProgress("0")
                            .taskEstimatedTime("0")
                            .build()
            ).collect(Collectors.toList());
            list.addAll(futureList);
        }
        list.sort(Comparator.comparing(PatrolTaskStatus::getStartTime).reversed());
        // 分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, list.size());
        log.info("[GAB] listV2: {} {}", pageNum, pageSize);
        List<PatrolTaskStatus> pageList = list.subList(start, end);

        // 更新结果
        List<String> taskPatrolIds = list.stream().filter(item -> !item.getTaskState().equals(TaskStateEnum.PENDING.getCode())).map(PatrolTaskStatus::getTaskPatrolledId).collect(Collectors.toList());
        if (taskPatrolIds.size() > 0) {
            List<PatrolTaskResultMain> resultMains = patrolTaskResultMainService.selectMainFileStatus(taskPatrolIds);
            List<String> taskCodeIds = list.stream().map(PatrolTaskStatus::getTaskCode).collect(Collectors.toList());
            List<Map<String, Object>> pointList = patrolTaskInfoService.selectPatrolTaskInfoCount(taskCodeIds);
            Map<String, String> pointMap = pointList.stream().collect(Collectors.toMap((item) -> (String) item.get("taskMajorId"), (item) -> {
                return String.valueOf(item.get("num"));
            }));
            Map<String, ResultAnalysis> abnormalDataBatchMap = resultAnalysisService.selectTaskAbnormalDataBatch(taskPatrolIds);
            List<ResultAnalysis> allQxAnalysisList = resultAnalysisService.selectResultAnalysisListBatch(taskPatrolIds, "0");
            Map<String, Map<GroupKey, List<ResultAnalysis>>> groupedAnalysisMap = allQxAnalysisList.stream()
                    .collect(Collectors.groupingBy(
                            ResultAnalysis::getTaskPatrolId,
                            Collectors.groupingBy(data -> new GroupKey(data.getObjectId(), data.getAlgType()))
                    ));
            list.forEach((item) -> {
                item.setPatrolStatus("1");
                item.setPointCount(pointMap.get(item.getTaskCode()));
                if (!item.getTaskProgress().contains("100")) {
                    item.setFileStatus("0");
                } else {
                    List<PatrolTaskResultMain> collect = resultMains.stream().filter((res) -> {
                        return res.getTaskPatrolledId().equals(item.getTaskPatrolledId());
                    }).collect(Collectors.toList());
                    if (!collect.isEmpty()) {
                        item.setFileStatus((collect.get(0)).getFileStatus());
                    } else {
                        item.setFileStatus("0");
                    }
                }
                // 异常数据统计
                ResultAnalysis resultAnalysis = abnormalDataBatchMap.getOrDefault(item.getTaskPatrolledId(), new ResultAnalysis());
                item.setCsQxNum(resultAnalysis.getCsQxNum());
                item.setAiQxNum(resultAnalysis.getAiQxNum());
                item.setCsYcNum(resultAnalysis.getCsYcNum());
                item.setAiYcNum(resultAnalysis.getAiYcNum());
                Map<GroupKey, List<ResultAnalysis>> groupKeyListMap = groupedAnalysisMap.get(item.getTaskPatrolledId());
                item.setQxNum(groupKeyListMap == null ? 0 : groupKeyListMap.size());
                if (StringUtils.isEmpty(item.getTaskEstimatedTime())) {
                    item.setTaskEstimatedTime("0");
                }
            });
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(pageList);
        rspData.setMsg("Query Ok");
        rspData.setTotal((new PageInfo<>(list)).getTotal());

        return rspData;
    }

    @GetMapping({"/list"})
    public TableDataInfo list(PatrolTaskStatus patrolTaskStatus) {
        this.startPage();
        patrolTaskStatus.setFilterTaskType("2");
        // 分页查询执行任务列表
        List<PatrolTaskStatus> list = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
        if (list == null || list.size() == 0) {
            return this.getDataTable(list);
        }
        // 收集执行id
        List<String> taskPatrolIds = list.stream().map(PatrolTaskStatus::getTaskPatrolledId).collect(Collectors.toList());
        // 查询归档信息
        List<PatrolTaskResultMain> resultMains = patrolTaskResultMainService.selectMainFileStatus(taskPatrolIds);
        // 收集任务code
        List<String> taskCodeIds = list.stream().map(PatrolTaskStatus::getTaskCode).collect(Collectors.toList());
        // 查询任务详情
        List<Map<String, Object>> pointList = patrolTaskInfoService.selectPatrolTaskInfoCount(taskCodeIds);
        Map<String, String> pointMap = pointList.stream().collect(Collectors.toMap((item) -> {
            return (String) item.get("taskMajorId");
        }, (item) -> {
            return String.valueOf(item.get("num"));
        }));
        // 填充每个任务的扩展统计信息
        list.forEach((item) -> {
            item.setPatrolStatus("1");
            item.setPointCount(pointMap.get(item.getTaskCode()));
            // 任务指定算法类型：当为纠偏时，返回值便于前端做样式处理
            if (AlgConstants.CORRECTION.equals(item.getSpecifiedAlg())) {
                item.setAlgName(AlgConstants.CORRECTION);
            }
            // 根据任务进度和归档信息设置文件状态
            if (!item.getTaskProgress().contains("100")) {
                item.setFileStatus("0");
            } else {
                List<PatrolTaskResultMain> collect = resultMains.stream().filter((res) -> {
                    return res.getTaskPatrolledId().equals(item.getTaskPatrolledId());
                }).collect(Collectors.toList());
                if (!collect.isEmpty()) {
                    item.setFileStatus((collect.get(0)).getFileStatus());
                } else {
                    item.setFileStatus("0");
                }
            }
            List<ResultAnalysisSummaryDTO> summaryDTOList;
            if (item.getTaskType().equals(TaskType.MAIN.getCode())) {
                List<String> taskPatrolledIds = item.getChildren().stream().map(PatrolTaskStatus::getTaskPatrolledId).collect(Collectors.toList());
                summaryDTOList = resultAnalysisService.countResultAnalysisSummary(taskPatrolledIds);
            } else {
                summaryDTOList = resultAnalysisService.countResultAnalysisSummary(Collections.singletonList(item.getTaskPatrolledId()));
            }
            if (summaryDTOList != null && !summaryDTOList.isEmpty()) {
                summaryDTOList.forEach(summaryDTO -> {
                    if (summaryDTO != null) {
                        // 使用 Optional 或三元运算符防止 null 值累加
                        item.setCsQxNum(item.getCsQxNum() + summaryDTO.getCsQxNum());
                        item.setAiQxNum(item.getAiQxNum() + summaryDTO.getAiQxNum());
                        item.setCsYcNum(item.getCsYcNum() + summaryDTO.getCsYcNum());
                        item.setAiYcNum(item.getAiYcNum() + summaryDTO.getAiYcNum());
                        item.setQxNum(item.getQxNum() + summaryDTO.getQxNum());
                    }
                });
            }
            if (StringUtils.isEmpty(item.getTaskEstimatedTime())) {
                item.setTaskEstimatedTime("0");
            }
        });
        return this.getDataTable(list);
    }

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

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

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

        }

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

    @Log(title = "任务状态数据", businessType = BizType.EXPORT)
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, PatrolTaskStatus patrolTaskStatus) {
        List<PatrolTaskStatus> list = this.patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
        ExcelUtil<PatrolTaskStatus> util = new ExcelUtil<>(PatrolTaskStatus.class);
        util.exportExcel(response, list, "Task Status Data");
    }

    @GetMapping({"/{lineId}"})
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId) {
        return AjaxResult.success(this.patrolTaskStatusService.selectPatrolTaskStatusByLineId(lineId));
    }

    @Log(title = "任务状态数据", businessType = BizType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PatrolTaskStatus patrolTaskStatus) {
        patrolTaskStatus.setStartTime(new Date());
        return this.toAjax(this.patrolTaskStatusService.insertPatrolTaskStatus(patrolTaskStatus));
    }

    @Log(title = "任务状态数据", businessType = BizType.UPDATE)
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody PatrolTaskStatus patrolTaskStatus) {
        return this.toAjax(this.patrolTaskStatusService.updatePatrolTaskStatus(patrolTaskStatus));
    }

    @Log(title = "任务状态数据", businessType = BizType.DELETE)
    @PostMapping({"/remove/{lineIds}"})
    public AjaxResult remove(@PathVariable Long[] lineIds) {
        return this.toAjax(this.patrolTaskStatusService.deletePatrolTaskStatusByLineIds(lineIds));
    }

    @GetMapping({"/taskcount"})
    public Map<String, Object> taskCount(PatrolTaskStatus patrolTaskStatus) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        try {
            if (StringUtils.isNotEmpty(patrolTaskStatus.getTimeType())) {
                List<PatrolTask> patrolTaskList = this.patrolTaskService.selectPatrolTaskList(new PatrolTask());
                Map<String, String> chineseDayMap = new HashMap<>();
                chineseDayMap.put("MONDAY", "星期一");
                chineseDayMap.put("TUESDAY", "星期二");
                chineseDayMap.put("WEDNESDAY", "星期三");
                chineseDayMap.put("THURSDAY", "星期四");
                chineseDayMap.put("FRIDAY", "星期五");
                chineseDayMap.put("SATURDAY", "星期六");
                chineseDayMap.put("SUNDAY", "星期日");
                String dayOfMonth;
                ArrayList taskCountList;
                if (patrolTaskStatus.getTimeType().equals("0")) {
                    int year = Integer.parseInt(patrolTaskStatus.getTimeConditions());
                    List<String> months = new ArrayList<>();

                    for (int month = 1; month <= 12; ++month) {
                        YearMonth yearMonth = YearMonth.of(year, month);
                        dayOfMonth = yearMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                        months.add(dayOfMonth);
                    }

                    taskCountList = new ArrayList<>();
                    Iterator<String> iterator = months.iterator();
                    while (true) {
                        if (!iterator.hasNext()) {
                            map.put("year", taskCountList);
                            break;
                        }

                        dayOfMonth = iterator.next();
                        patrolTaskStatus.setTimeConditions(dayOfMonth);
                        taskCountList = (ArrayList) this.month(patrolTaskStatus, chineseDayMap, patrolTaskList);
                        TaskCount tc = new TaskCount();
                        int cn = 0;

                        for (Object object : taskCountList) {
                            TaskCount taskCount = (TaskCount) object;
                            cn += Integer.parseInt(taskCount.getCompleteName().replace(StringUtils.PERCENT, StringUtils.EMPTY));
                            tc.setCallName(taskCount.getCallName());
                        }

                        tc.setCompleteName(String.valueOf(cn / taskCountList.size()));
                        taskCountList.add(tc);
                    }
                }

                if (patrolTaskStatus.getTimeType().equals("1")) {
                    List<TaskCount> taskCounts = this.month(patrolTaskStatus, chineseDayMap, patrolTaskList);
                    map.put("month", taskCounts);
                }

                if (patrolTaskStatus.getTimeType().equals("2")) {
                    LocalDate localDate = LocalDate.parse(patrolTaskStatus.getTimeConditions());
                    LocalDateTime localDateTime = LocalDateTime.parse(patrolTaskStatus.getTimeConditions() + "T00:00");
                    taskCountList = new ArrayList<>();
                    String dayOfWeek = chineseDayMap.get(localDate.getDayOfWeek().name());
                    dayOfMonth = localDate.getDayOfMonth() + "号";

                    for (PatrolTask pr : patrolTaskList) {
                        int dsCount = 0;
                        int jgCount = 0;
                        int zqCount = 0;
                        int all;
                        PatrolTaskStatus taskStatus = new PatrolTaskStatus();
                        taskStatus.setTaskCode(pr.getTaskId() + "");
                        taskStatus.setTaskState("1");
                        taskStatus.setBeginTime(patrolTaskStatus.getTimeConditions());
                        List<PatrolTaskStatus> list = this.patrolTaskStatusService.selectPatrolTaskStatusCount(taskStatus);
                        PatrolTaskStatus taskStatus2 = new PatrolTaskStatus();
                        taskStatus2.setTaskCode(pr.getTaskId() + "");
                        taskStatus2.setTaskState("1");
                        taskStatus2.setBeginTime(patrolTaskStatus.getTimeConditions());
                        taskStatus2.setDescription("1");
                        List<PatrolTaskStatus> list2 = this.patrolTaskStatusService.selectPatrolTaskStatusCount(taskStatus2);
                        int size2 = list2.size();
                        int all_yj = list.size();
                        if ("2".equals(pr.getExecutionStatus())) {
                            LocalDate localDate1 = pr.getFixedStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                            if (dayOfMonth.equals(localDate1.getDayOfMonth() + "号")) {
                                dsCount = 1;
                            }
                        }

                        int as;
                        if ("4".equals(pr.getExecutionStatus())) {
                            LocalDateTime t1 = pr.getIntervalStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                            LocalDateTime t2 = pr.getIntervalEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                            int comparisonResult1 = localDateTime.compareTo(t1);
                            as = localDateTime.compareTo(t2);
                            if (comparisonResult1 >= 0 && as <= 0) {
                                LocalTime parsedTime = LocalTime.parse(pr.getIntervalExecuteTime());
                                t1 = t1.withHour(parsedTime.getHour()).withMinute(parsedTime.getMinute()).withSecond(parsedTime.getSecond());
                                Duration duration = Duration.between(t1, localDateTime);
                                int hours = (int) duration.toHours();
                                int remainder = hours % pr.getIntervalNumber();
                                jgCount = 24 - pr.getIntervalNumber() - remainder / pr.getIntervalNumber();
                                if (remainder == 0) {
                                    ++jgCount;
                                } else {
                                    jgCount += 2;
                                }
                            }
                        }

                        if ("1".equals(pr.getExecutionStatus())) {
                            String[] str1;
                            int j;
                            if ("1".equals(pr.getTaskCycle())) {
                                str1 = pr.getCycleWeek().split(StringUtils.COMMA);

                                for (j = 0; j < str1.length; ++j) {
                                    if (dayOfWeek.equals(str1[j])) {
                                        ++zqCount;
                                    }
                                }
                            }

                            if ("0".equals(pr.getTaskCycle())) {
                                str1 = pr.getCycleMonth().split(StringUtils.COMMA);

                                for (j = 0; j < str1.length; ++j) {
                                    if (dayOfMonth.equals(str1[j])) {
                                        ++zqCount;
                                    }
                                }
                            }
                        }

                        all = dsCount + jgCount + zqCount;
                        TaskCount taskCount = new TaskCount();
                        taskCount.setCallName(patrolTaskStatus.getTimeConditions());
                        taskCount.setDescName(pr.getTaskName());
                        double d;
                        as = all + size2;
                        if (as != 0) {
                            if (all_yj > 0) {
                                if (all_yj > as) {
                                    d = 100.0D;
                                    taskCount.setCount(all_yj + "/" + all_yj);
                                } else {
                                    d = (double) all_yj / (double) as * 100.0D;
                                    taskCount.setCount(all_yj + "/" + as);
                                }
                            } else {
                                d = (double) all_yj / (double) as * 100.0D;
                                taskCount.setCount(all_yj + "/" + as);
                            }

                            taskCount.setCompleteName(Math.round(d) + "%");
                            taskCountList.add(taskCount);
                        }
                    }

                    map.put("day", taskCountList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    public List<TaskCount> month(PatrolTaskStatus patrolTaskStatus, Map<String, String> chineseDayMap, List<PatrolTask> patrolTaskList) throws ParseException {
        String dateStr = patrolTaskStatus.getTimeConditions() + "-01";
        LocalDate localDate = LocalDate.parse(dateStr);
        LocalDateTime firstDayOfMonth = localDate.atStartOfDay();
        LocalDateTime lastDayOfMonth = localDate.withDayOfMonth(localDate.lengthOfMonth()).atTime(LocalTime.MAX);
        List<TaskCount> taskCountList = new ArrayList<>();
        for (PatrolTask patrolTask : patrolTaskList) {
            int dsCount = 0;
            int jgCount = 0;
            int zqCount = 0;
            int all;
            PatrolTaskStatus taskStatus = new PatrolTaskStatus();
            taskStatus.setTaskCode(patrolTask.getTaskId() + "");
            taskStatus.setTaskState("1");

            taskStatus.setStartTime(DateUtils.parse(DateUtils.yyyy_MM, patrolTaskStatus.getTimeConditions()));
            List<PatrolTaskStatus> list = this.patrolTaskStatusService.selectPatrolTaskStatusCount(taskStatus);
            PatrolTaskStatus taskStatus2 = new PatrolTaskStatus();
            taskStatus2.setTaskCode(patrolTask.getTaskId() + "");
            taskStatus2.setTaskState("1");
            taskStatus2.setDescription("1");
            taskStatus2.setStartTime(DateUtils.parse(DateUtils.yyyy_MM, patrolTaskStatus.getTimeConditions()));
            List<PatrolTaskStatus> list2 = this.patrolTaskStatusService.selectPatrolTaskStatusCount(taskStatus2);
            int size2 = list2.size();
            int all_yj = list.size();
            LocalDateTime localDateTime;
            if ("2".equals(patrolTask.getExecutionStatus())) {
                localDateTime = patrolTask.getFixedStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                if (localDateTime.isAfter(firstDayOfMonth) && localDateTime.isBefore(lastDayOfMonth)) {
                    dsCount = 1;
                }
            }

            LocalDateTime localDateTime2;
            int dayOfMonth;
            int i;
            if ("4".equals(patrolTask.getExecutionStatus())) {
                localDateTime = patrolTask.getIntervalStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                localDateTime2 = patrolTask.getIntervalEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                if (localDateTime.isBefore(firstDayOfMonth)) {
                    localDateTime = firstDayOfMonth;
                }

                if (localDateTime.isAfter(lastDayOfMonth)) {
                    localDateTime = null;
                }

                if (localDateTime2.isAfter(lastDayOfMonth)) {
                    localDateTime2 = lastDayOfMonth;
                }

                if (localDateTime2.isBefore(firstDayOfMonth)) {
                    localDateTime2 = null;
                }

                LocalTime parsedTime = LocalTime.parse(patrolTask.getIntervalExecuteTime());
                if (localDateTime != null && localDateTime2 != null) {
                    localDateTime = localDateTime.withHour(parsedTime.getHour()).withMinute(parsedTime.getMinute()).withSecond(parsedTime.getSecond());
                    Duration duration = Duration.between(localDateTime, localDateTime2);
                    dayOfMonth = (int) duration.toHours();
                    jgCount = dayOfMonth / patrolTask.getIntervalNumber();
                    i = dayOfMonth / patrolTask.getIntervalNumber();
                    if (i == 0) {
                        ++jgCount;
                    } else {
                        jgCount += 2;
                    }
                }
            }

            if ("1".equals(patrolTask.getExecutionStatus())) {
                localDateTime = patrolTask.getCycleStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                localDateTime2 = patrolTask.getCycleEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                if (localDateTime.isBefore(firstDayOfMonth)) {
                    localDateTime = firstDayOfMonth;
                }

                if (localDateTime.isAfter(lastDayOfMonth)) {
                    localDateTime = null;
                }

                if (localDateTime2.isAfter(lastDayOfMonth)) {
                    localDateTime2 = lastDayOfMonth;
                }

                if (localDateTime2.isBefore(firstDayOfMonth)) {
                    localDateTime2 = null;
                }

                int[] dateCount;
                LocalDateTime currentDate;
                String[] str;
                if ("1".equals(patrolTask.getTaskCycle()) && localDateTime != null && localDateTime2 != null) {
                    System.out.println(localDateTime + "=======" + localDateTime2);
                    dateCount = new int[7];

                    for (currentDate = localDateTime; !currentDate.isAfter(localDateTime2); currentDate = currentDate.plusDays(1L)) {
                        DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
                        i = dayOfWeek.getValue();
                        ++dateCount[i - 1];
                    }

                    str = patrolTask.getCycleWeek().split(StringUtils.COMMA);
                    for (i = 0; i < 7; ++i) {
                        String dayOfWeekName = DayOfWeek.of(i + 1).toString();
                        for (String s : str) {
                            if (chineseDayMap.get(dayOfWeekName).equals(s)) {
                                zqCount += dateCount[i];
                            }
                        }
                    }
                }

                if ("0".equals(patrolTask.getTaskCycle())) {
                    dateCount = new int[31];
                    for (currentDate = localDateTime; !Objects.requireNonNull(currentDate).isAfter(localDateTime2); currentDate = currentDate.plusDays(1L)) {
                        dayOfMonth = currentDate.getDayOfMonth();
                        ++dateCount[dayOfMonth - 1];
                    }

                    str = patrolTask.getCycleMonth().split(StringUtils.COMMA);

                    for (i = 0; i < dateCount.length; ++i) {
                        for (String s : str) {
                            if (dateCount[i] > 0 && s.contains(String.valueOf(i + 1))) {
                                zqCount += dateCount[i];
                            }
                        }
                    }
                }
            }

            all = dsCount + jgCount + zqCount;
            TaskCount taskCount = new TaskCount();
            taskCount.setCallName(patrolTaskStatus.getTimeConditions());
            taskCount.setDescName(patrolTask.getTaskName());
            double d;
            int as = all + size2;
            if (all_yj > 0) {
                if (all_yj > as) {
                    d = 100.0D;
                    taskCount.setCount(all_yj + "/" + all_yj);
                } else {
                    d = (double) all_yj / (double) as * 100.0D;
                    taskCount.setCount(all_yj + "/" + as);
                }
            } else {
                d = (double) all_yj / (double) as * 100.0D;
                taskCount.setCount(all_yj + "/" + as);
            }

            taskCount.setCompleteName(Math.round(d) + "%");
            taskCountList.add(taskCount);
        }

        return taskCountList;
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        int currentYear = 0;
        int Year = 2;
        int current = 3;
        double d = (double) (Year + currentYear) / (double) current * 100.0D;
        System.out.println(Math.round(d) + "%");
    }

    public Map<String, Object> getMonth(int year, int month) {
        Map<String, Object> map = new HashMap<>();
        String beginTime = DateUtils.format(DateUtils.yyyyMMdd2, getFirstDay(year, month));
        String endTime = DateUtils.format(DateUtils.yyyyMMdd2, getLastDay(year, month));
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        return map;
    }

    public static Date getFirstDay(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1);
        c.set(Calendar.DATE, 1);
        return c.getTime();
    }

    public static Date getLastDay(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month - 1);
        int lastDay = c.getActualMaximum(Calendar.DATE);
        c.set(Calendar.DATE, lastDay);
        return c.getTime();
    }

    //立即执行任务
    @GetMapping({"/controlChange"})
    public AjaxResult controlChange(PatrolTask patrolTaskParam) {
        String taskCurrentCode = redisService.getCacheObjectOfTask(RedisConst.TASK_CURRENT_CODE, String.valueOf(patrolTaskParam.getTaskId()));
        log.info("CONTROL_CHANGE CURRENT EXEC TASK: taskId: {}, taskCurrentCode: {}", patrolTaskParam.getTaskId(), taskCurrentCode);
        if (!StringUtils.isEmpty(taskCurrentCode)) {
            return AjaxResult.error(501, "THE TASK " + taskCurrentCode + " IS RUNNING");
        } else {
            PatrolTask patrolTask = patrolTaskService.selectPatrolTaskByTaskId(patrolTaskParam.getTaskId());
            return issuePatrolTask(patrolTask);
        }
    }

    public void sendVideoLightTaskToScheduledJob(final PatrolTask patrolTask) {
        try {
            if ("1".equals(patrolTask.getDevType())) {
                return;
            }

            feignJobTaskClient.immediatelyExecTask(patrolTask);
//            (new Thread(() -> {
//                try {
//                    extracted(patrolTask);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//            })).start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //有何作用?
    private void extracted(PatrolTask patrolTask) throws InterruptedException {
        Thread.sleep(20000L);
        String taskCode = redisService.getCacheObjectOfTask(RedisConst.TASK_CURRENT_CODE, String.valueOf(patrolTask.getTaskId()));
        if (taskCode != null && taskCode.contains(String.valueOf(patrolTask.getTaskId()))) {
            this.log.info("[TASK STATUS] UPDATE TASK: {} STATUS to IMMEDIATE", taskCode);
            PatrolTaskStatus patrolTaskStatus = new PatrolTaskStatus();
            patrolTaskStatus.setTaskPatrolledId(taskCode.split(StringUtils.AT)[1] + "_" + taskCode.split(StringUtils.AT)[2]);
            List<PatrolTaskStatus> patrolTaskStatusList = patrolTaskStatusService.selectPatrolTaskStatusList(patrolTaskStatus);
            if (patrolTaskStatusList != null && !patrolTaskStatusList.isEmpty()) {
                patrolTaskStatus = patrolTaskStatusList.get(0);
                patrolTaskStatus.setDescription("1");
                this.patrolTaskStatusService.updatePatrolTaskStatus(patrolTaskStatus);
            } else {
                this.log.info("[TASK STATUS] UPDATE TASK: {} EMPTY!", taskCode);
            }
        }

    }

    public AjaxResult issuePatrolTask(final PatrolTask patrolTask) {
        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();
        }

        if (StringUtils.isNotEmpty(patrolTask.getDevNo())) {
            String[] devTypes = patrolTask.getDevType().split(StringUtils.COMMA);
            String[] devNos = patrolTask.getDevNo().split(StringUtils.COMMA);
            List<String> pilotTaskCmds = new ArrayList<>();
            List<String> devTypeList = new ArrayList<>();
            List<String> devNoList = new ArrayList<>();
            for (int i = 0; i < devNos.length; i++) {
                log.info("issuePatrolTask 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 (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.getTaskCode());
                        sendTask.setType("41");
                        sendTask.setCommand("1");
                        String pilotTaskCmd = JSONObject.toJSONString(sendTask);
                        pilotTaskCmds.add(pilotTaskCmd);
                    }
                } else {
                    log.info("可见光任务构建, 第 {} 个, devNo: {}", i + 1, devNos[i]);
                    devTypeList.add(devTypes[i]);
                    devNoList.add(devNos[i]);
                }
            }

            if (!pilotTaskCmds.isEmpty() || (!devTypeList.isEmpty() && !devNoList.isEmpty())) {
                String immediatelyExecTaskTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
                redisService.setCacheObjectOfTask(RedisConst.TASK_CURRENT_CODE, patrolTask.getTaskCode(), RedisConst.TASK_CODE + patrolTask.getTaskCode() + StringUtils.AT + immediatelyExecTaskTime, 1L, TimeUnit.HOURS);
            }

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

            // 下发可见光任务
            if (!devTypeList.isEmpty() && !devNoList.isEmpty()) {
                patrolTask.setDevType(StringUtils.join(devTypeList, StringUtils.COMMA));
                patrolTask.setDevNo(StringUtils.join(devNoList, StringUtils.COMMA));
                log.info("可见光任务下发, devType:{}, devNo:{}", patrolTask.getDevType(), patrolTask.getDevNo());
                sendVideoLightTaskToScheduledJob(patrolTask);
            }
        }
        return toAjax(1);
    }

    //设置任务暂停或终止接口
    @GetMapping({"/taskStatusChange"})
    public AjaxResult taskStatusChange(PatrolTaskStatus params) {
        if (StringUtils.isEmpty(params.getLineId() + "")) {
            return error("param lineId is null");
        } else if (StringUtils.isEmpty(params.getCommand())) {
            return error("param command is null");
        }

        PatrolTaskStatus patrolTaskStatus = patrolTaskStatusService.selectPatrolTaskStatusByLineId(params.getLineId());
        if (patrolTaskStatus == null) return error("no task: " + params.getLineId() + " exist");

        String command = params.getCommand();
        log.info("[TASK] task_status_change cmd: {}, task: {}", command, patrolTaskStatus);
        if (patrolTaskStatus.getTaskType().equals(TaskType.MAIN.getCode())) {
            for (PatrolTaskStatus status : patrolTaskStatus.getChildren()) {
                execCommand(command, status);
            }
        } else {
            execCommand(command, patrolTaskStatus);
        }
        return toAjax(1);
    }

    // 执行修改任务状态命令
    private void execCommand(String command, PatrolTaskStatus patrolTaskStatus) {
        log.info("[TASK] task_status_change cmd: {}, task: {}", command, patrolTaskStatus);
        // 任务为完成、终止、过期状态时，不允许改变状态
        if (Arrays.asList(TaskStatus.DONE.getCode(), TaskStatus.HALTED.getCode(), TaskStatus.EXPIRED.getCode()).contains(patrolTaskStatus.getTaskState())) {
            log.info("[TASK] STATUS CHANGE IS NOT ALLOWED cmd: {}, task: {}", command, patrolTaskStatus);
            return;
        }

        if (TaskStatus.DONE.getCode().equals(command)) {
            patrolTaskStatus.setTaskState(TaskStatus.RUNNING.getCode());
        } else if (TaskStatus.RUNNING.getCode().equals(command)) {
            patrolTaskStatus.setTaskState(TaskStatus.PAUSED.getCode());
        } else if (TaskStatus.PAUSED.getCode().equals(command)) {
            patrolTaskStatus.setTaskState(TaskStatus.RUNNING.getCode());
            feignJobTaskClient.resumeExecTask(patrolTaskStatus.getTaskPatrolledId());
        } else {
            patrolTaskStatus.setTaskState(TaskStatus.HALTED.getCode());
            feignJobTaskClient.resumeExecTask(patrolTaskStatus.getTaskPatrolledId());
        }

        patrolTaskStatusService.updateTaskProgress(patrolTaskStatus.getLineId(), null, null, patrolTaskStatus.getTaskState());
        patrolTaskStatus.setCommand(command);
        issuePatrolTask(patrolTaskStatus);
    }

    public void issuePatrolTask(PatrolTaskStatus patrolTaskStatus) {
        String posType = patrolTaskStatus.getPosType();//预置位类型 0-视频 1-机器人 2-无人机
        if (StringUtils.isEmpty(posType)) {
            log.warn("[TASK] posType is null");
            return;
        }

        List<PatrolTask> patrolTaskList = patrolTaskService.selectPatrolTaskList(PatrolTask.builder().taskCode(patrolTaskStatus.getTaskCode()).build());
        if (patrolTaskList.isEmpty() || StringUtils.isEmpty(patrolTaskList.get(0).getDevType()) || StringUtils.isEmpty(patrolTaskList.get(0).getDevNo())) {
            log.warn("[TASK] No illegal task: {} in patrol_task", patrolTaskStatus.getTaskCode());
            return;
        }
        PatrolTask patrolTask = patrolTaskList.get(0);

        /**
         * Calc receive code
         */

        final List<BasedataEqpBookMoMain> bookList = patrolResultService.selectBasedataEqpBookList(BasedataEqpBookMoMain.builder().build());
        String[] devNoArr = patrolTask.getDevNo().split(StringUtils.COMMA);
        Set<String> receiveCodeSet = new HashSet<>();
        for (int i = 0; i < devNoArr.length; i++) {
            BasedataEqpBookMoMain basedataEqpbookMomain = new BasedataEqpBookMoMain();
            basedataEqpbookMomain.setPatrolDeviceCode(devNoArr[i]);
            List<BasedataEqpBookMoMain> eqpBookMoMains = patrolResultService.selectBasedataEqpBookList(basedataEqpbookMomain);
            if (!eqpBookMoMains.isEmpty() && eqpBookMoMains.get(0).getMainSystemCode() != null) {
                String receiveCode = eqpBookMoMains.get(0).getMainSystemCode();
                receiveCodeSet.add(receiveCode);
            }
        }
//        for (BasedataEqpBookMoMain book : bookList) {
//            if (!StringUtils.isEmpty(receiveCode) || StringUtils.isEmpty(book.getMainSystemCode())) {
//                continue;
//            }
//
//            final String type = book.getType();
//            if(StringUtils.isEmpty(type)) {
//                continue;
//            }
//
//            if (posType.equals("0") && (type.equals("10") || type.equals("11"))) {
//                log.info("[DEBUG] receiveCode three: id: {}", book.getEqpBookId());
//                receiveCode = book.getMainSystemCode();
//            } else if (posType.equals("1") && ((type.equals("1") || type.equals("2") || type.equals("3")))) {
//                log.info("[DEBUG] receiveCode one: id: {}", book.getEqpBookId());
//                receiveCode = book.getMainSystemCode();
//            } else if (posType.equals("2") && type.equals("13")) {
//                log.info("[DEBUG] receiveCode two: id: {}", book.getEqpBookId());
//                receiveCode = book.getMainSystemCode();
//            }
//        }
        log.info("[TASK] receiveCodeSet: {}", receiveCodeSet);

        /**
         * Calc send code
         */
        String sendCode = "";
        List<BasedataEqpBookMoMain> bookList2 = patrolResultService.selectBasedataEqpBookList(BasedataEqpBookMoMain.builder().type("20").build());
        if (!bookList2.isEmpty()) {
            sendCode = bookList2.get(0).getPatrolDeviceCode();
        }

        /**
         * Calc wrj code
         */
        Set<String> wrjCode = new HashSet<>();//droneCode
        for (BasedataEqpBookMoMain book : bookList) {
            final String type = book.getType();
            if (StringUtils.isEmpty(type)) {
                continue;
            }
            if (!type.equals("1") && !type.equals("2") && !type.equals("3") && !type.equals("13")) {
                continue;
            }
            if (StringUtils.isEmpty(book.getPatrolDeviceCode())) {
                continue;
            }

            wrjCode.add(book.getPatrolDeviceCode());
        }

        PatrolTask patrolTaskTemp = patrolTaskList.get(0);
        if (posType.equals("0")) {
            String cmd = "";
            String redisTaskPatrolId;
            if (!TaskStatus.DONE.getCode().equals(patrolTaskStatus.getCommand())) {
                if (TaskStatus.RUNNING.getCode().equals(patrolTaskStatus.getCommand())) {
                    cmd = TaskStatus.PAUSED.getCode();
                    redisService.setCacheObject(RedisConst.TASK_PATROL_ID, patrolTaskStatus.getTaskPatrolledId());
                    redisService.setCacheObject(RedisConst.TASK_PATROL_STATE, cmd);
                    log.info("[TASK] PAUSE, UPDATE STATUS STATE: {}, patrolId: {}", DescUtil.getTaskStatusDesc(cmd), patrolTaskStatus.getTaskPatrolledId());
                } else if (TaskStatus.PAUSED.getCode().equals(patrolTaskStatus.getCommand())) {
                    cmd = TaskStatus.RUNNING.getCode();
                    redisService.deleteObject(RedisConst.TASK_PATROL_ID);
                    redisService.deleteObject(RedisConst.TASK_PATROL_STATE);
                    redisTaskPatrolId = redisService.getCacheObject(RedisConst.TASK_PATROL_ID);
                    String redisTaskPatrolState = redisService.getCacheObject(RedisConst.TASK_PATROL_STATE);
                    log.info("[TASK] CONTINUE, UPDATE STATUS STATE: {}, patrolId: {}", DescUtil.getTaskStatusDesc(redisTaskPatrolState), redisTaskPatrolId);
                    if (!StringUtils.isEmpty(redisTaskPatrolId) && TaskStatus.PAUSED.getCode().equals(redisTaskPatrolState)) {
                        redisService.deleteObject(RedisConst.TASK_PATROL_ID);
                        redisService.deleteObject(RedisConst.TASK_PATROL_STATE);
                    }
                } else if (TaskStatus.HALTED.getCode().equals(patrolTaskStatus.getCommand())) {
                    cmd = TaskStatus.HALTED.getCode();
                    redisService.setCacheObject(RedisConst.TASK_PATROL_ID, patrolTaskStatus.getTaskPatrolledId());
                    redisService.setCacheObject(RedisConst.TASK_PATROL_STATE, cmd);
                    log.info("[TASK] HALT, UPDATE STATUS STATE: [{}], ID: [{}]", cmd, patrolTaskStatus.getTaskPatrolledId());
                }
            }

            if (patrolTaskTemp != null) {
                String[] devTypes = patrolTaskTemp.getDevType().split(StringUtils.COMMA);
                String[] devNos = patrolTaskTemp.getDevNo().split(StringUtils.COMMA);
                for (int i = 0; i < devTypes.length; ++i) {
                    if ("2".equals(devTypes[i])) {
                        feignTaskClient.updateCameraPatrolTaskExecRecordState(patrolTaskStatus.getTaskCode(), devNos[i], cmd);
                    }
                }
            } else {
                feignTaskClient.updateCameraPatrolTaskExecRecordState(patrolTaskStatus.getTaskCode(), patrolTaskStatus.getCode(), cmd);
            }
        } else if (posType.equals("1") || posType.equals("2")) {
            // 机器人，无人机
            for (String receiveCode : receiveCodeSet) {
//                for (String wrj : wrjCode) {
//                    String strSendTaskControl = JSONObject.toJSONString(SendTask.builder().receiveCode(receiveCode).sendCode(sendCode).code(wrj).type("1").command("5").items(Collections.singletonList(PatrolSendTask.builder().value("1").build())).build());
//                    log.info("[TASK] MODE CHANGE: {}", strSendTaskControl);
//                    feignTaskClient.sendCommand(strSendTaskControl);
//                }
                SendTask sendTask = new SendTask();
                sendTask.setReceiveCode(receiveCode);
                sendTask.setSendCode(sendCode);
                if ("1".equals(patrolTaskStatus.getCommand())) {
                    sendTask.setCode(patrolTaskTemp.getTaskId() + "");
                } else {
                    sendTask.setCode(patrolTaskStatus.getTaskPatrolledId());
                }
                sendTask.setType("41");
                sendTask.setCommand(patrolTaskStatus.getCommand());
                String sendTaskCmd = JSONObject.toJSONString(sendTask);
                log.info("[TASK] TASK STATUS CONTROL: {}", sendTaskCmd);
                feignTaskClient.sendCommand(sendTaskCmd);
            }
        }
    }

    @GetMapping({"/test"})
    public AjaxResult test(String id) {
        PatrolTaskStatus var2 = this.patrolTaskStatusService.selectPatrolTaskStatusByLineId(1L);

        try {
            this.feignTaskClient.notify("test");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.success();
    }

    /**
     * 判断任务点位是否在检修区域内
     *
     * @param taskCode
     * @return
     */
    public boolean isWithinMaintainRegion(String taskCode, String devNo) {
        Date currentDate = new Date();
        MaintainRegion maintainRegion = MaintainRegion.builder()
                .startTime(currentDate)
                .endTime(currentDate)
                .enable("1")
                .build();
        List<MaintainRegion> maintainRegionList = maintainRegionService.selectMaintainRegionList(maintainRegion);
        log.info("[TASK] MAINTAIN REGION: {}", maintainRegionList);
        List<String> maintainIds = maintainRegionList.stream()
                .map(MaintainRegion::getDeviceList)
                .flatMap(ids -> Arrays.stream(ids.split(StringUtils.COMMA)))
                .collect(Collectors.toList());

        PatrolTaskInfo patrolTaskInfo = PatrolTaskInfo.builder()
                .taskMajorId(taskCode)
                .devNo(devNo)
                .build();
        List<PatrolTaskInfo> patrolTaskInfoList = patrolTaskInfoService.selectPatrolTask(patrolTaskInfo);
        boolean isWithin = false;
        for (PatrolTaskInfo info : patrolTaskInfoList) {
            final Long areaId = info.getAreaId();
            if (maintainIds.contains(String.valueOf(areaId))) {
                isWithin = true;
                break;
            }
        }

        return isWithin;
    }
}
