package com.yfd.platform.modules.patroltask.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.HackLoopTableRenderPolicy;
import com.deepoove.poi.util.PoitlIOUtils;
import com.yfd.platform.config.HttpServerConfig;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.constant.SystemCode;
import com.yfd.platform.modules.basedata.domain.Substation;
import com.yfd.platform.modules.basedata.domain.SubstationDevice;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.mapper.SubstationDeviceMapper;
import com.yfd.platform.modules.basedata.service.ISubstationDeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationService;
import com.yfd.platform.modules.basedata.service.IWeatherLogService;
import com.yfd.platform.modules.patroltask.domain.DefectDevice;
import com.yfd.platform.modules.patroltask.domain.Task;
import com.yfd.platform.modules.patroltask.domain.TaskResult;
import com.yfd.platform.modules.patroltask.domain.TaskTodo;
import com.yfd.platform.modules.patroltask.service.IDefectDeviceService;
import com.yfd.platform.modules.patroltask.service.ITaskService;
import com.yfd.platform.modules.patroltask.service.ITaskTodoService;
import com.yfd.platform.modules.robotapi.domain.PlatformParentSystem;
import com.yfd.platform.modules.robotapi.service.IPlatformParentSystemService;
import com.yfd.platform.modules.robotapi.service.IStationRobotService;
import com.yfd.platform.system.service.ISysDictionaryItemsService;
import com.yfd.platform.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.renderable.RenderableImageProducer;
import java.io.*;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 巡视任务执行表 前端控制器
 * </p>
 *
 * @since 2023-04-08
 */
@RestController
@RequestMapping("/patroltasks/task-todo")
@Api(value = "TaskTodoController", tags = "任务执行情况")
@Slf4j
public class TaskTodoController {

    @Resource
    private ITaskTodoService taskTodoService;

    @Resource
    private ITaskService taskService;

    @Resource
    private SubstationDeviceMapper substationDeviceMapper;

    @Resource
    private ISubstationDeviceService substationDeviceService;

    @Resource
    private ISubstationService substationService;

    @Resource
    private ISysDictionaryItemsService sysDictionaryItemsService;

    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;

    @Resource
    private IWeatherLogService weatherLogService;

    @Resource
    private IStationRobotService stationRobotService;
    @Resource
    private HttpServerConfig httpServerConfig;
    @Resource
    IPlatformParentSystemService platformParentSystemService;
    @Resource
    private FtpClient ftpClient;
    @Resource
    private IDefectDeviceService defectDeviceService;
    @Resource
    private TLSFTPUtils tlsftpUtils;

    @GetMapping("/getTaskToDoList")
    @ApiOperation("分页查询巡视任务执行情况")
    public ResponseResult getTaskToDoList(Page<Map<String, Object>> page, String taskId, String taskState) {
        if (StrUtil.isBlank(taskId) || StrUtil.isBlank(taskState)) {
            return ResponseResult.error("参数为空");
        }
        LambdaQueryWrapper<TaskTodo> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(taskState)) {
            List<String> idList = new ArrayList<>();
            if ("0".equals(taskState)) {
                idList.add("0");
                idList.add("2");
                idList.add("3");
                idList.add("5");
            } else {
                idList.add("1");
                idList.add("4");
                idList.add("6");
            }
            queryWrapper.in(TaskTodo::getTaskState, idList);
        }
        queryWrapper.eq(TaskTodo::getTaskId, taskId).orderByAsc(TaskTodo::getPlanStartTime);
        Page<Map<String, Object>> mapPage = taskTodoService.pageMaps(page, queryWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        records.forEach(r -> {

            if (!Objects.isNull(r.get("stationId"))) {
                String stationId = r.get("stationId").toString();
                Substation substation = substationService.getById(stationId);
                r.put("isStationFlag", substation.getIsStationFlag());
                r.put("online", substation.getOnline());
            }

        });
        mapPage.setRecords(records);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getTaskToDo")
    @ApiOperation("查询巡视任务执行情况详情")
    public ResponseResult getTaskToDo(String taskTodoId) {
        Map<String, Object> map = taskTodoService.getTaskToDo(taskTodoId);
        return ResponseResult.successData(map);
    }

    /**********************************
     * 用途说明: 根据任务ID,处理待处理任务
     * 参数说明 taskTodoId 待处理任务ID  optType操作类型
     *  pause：暂停；resume:暂停后恢复 runNow:立即执行 delete: 删除  stop：终止（不可恢复）;
     * optType=delete  删除或取消
     * 返回值说明: 当前任务信息
     ***********************************/
    @PostMapping("/doCurrentTask")
    @ApiOperation("操作当前巡视任务")
    public ResponseResult doCurrentTask(String taskTodoId, String optType) throws InterruptedException {
        TaskTodo taskTodo = taskTodoService.getById(taskTodoId);
        String robotCode = taskTodo.getRobotCode();
        String dockInfo = taskTodo.getDockInfo();
        if (StrUtil.isNotBlank(robotCode) && StrUtil.isBlank(dockInfo)) {
            String Command = "";
            String Code = taskTodo.getTaskTodoId();
            String taskState = "";
            if (SystemCode.TASK_PAUSE_CODE.getCode().equals(optType)) {
                Command = SystemCode.COMMAND_TASK_PAUSE_CODE.getCode();
                taskState = "3";
            } else if (SystemCode.TASK_RESUME_CODE.getCode().equals(optType)) {
                Command = SystemCode.COMMAND_TASK_RESUME_CODE.getCode();
                taskState = "2";
            } else if (SystemCode.TASK_RUN_CODE.getCode().equals(optType)) {
                Command = SystemCode.COMMAND_TASK_START_CODE.getCode();
                taskState = "2";
                Code = taskTodo.getTaskCode();
            } else if (SystemCode.TASK_STOP_CODE.getCode().equals(optType)) {
                Command = SystemCode.COMMAND_TASK_STOP_CODE.getCode();
                taskState = "4";
            }
            List<SubstationPatroldevice> list = substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getPatroldeviceCode, robotCode));
            if (list.size() > 0) {
                SubstationPatroldevice substationPatroldevice = list.get(0);
                stationRobotService.sendCommand(substationPatroldevice.getInternationalId(), httpServerConfig.getPatrolServerid(), substationPatroldevice.getInternationalId(), SystemCode.TYPE_TASK_CONTROL_CODE.getCode(),
                        Command, Code, null);
            }
            LambdaUpdateWrapper<TaskTodo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TaskTodo::getTaskTodoId, taskTodoId).set(TaskTodo::getTaskState, taskState);
            taskTodoService.update(updateWrapper);
            return ResponseResult.success();
        }
        TaskTodo resut = taskTodoService.doCurrentTask(taskTodoId, optType);
        return ResponseResult.successData(resut);
    }

    /**********************************
     * 用途说明: 根据任务识别结果更新数据，功能智能识别程序回调
     * 参数说明 taskResult 任务识别处理结果
     * 返回值说明: 当前任务信息
     ***********************************/
    @PostMapping("/callBackTaskResult")
    @ApiOperation("更新当前任务智能识别结果")
    public ResponseResult callBackTaskResult(TaskResult taskResult) {
        boolean resut = taskTodoService.updateTaskResult(taskResult);
        return ResponseResult.successData(resut);
    }

    @GetMapping("/getTaskToDoByTaskId")
    @ApiOperation("根据巡视任务查询任务执行情况")
    public ResponseResult addTaskToDo(String taskId, String taskState) {
        LambdaQueryWrapper<TaskTodo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskTodo::getTaskId, taskId).eq(TaskTodo::getTaskState, taskState);
        List<Map<String, Object>> listMaps = taskTodoService.listMaps(queryWrapper);
        return ResponseResult.successData(listMaps);
    }

    @GetMapping("/getTaskTodoStat")
    @ApiOperation("巡视任务统计")
    public ResponseResult getTaskTodoStat(String stationCode, String type) {
        if (StrUtil.isBlank(stationCode)) {
            return ResponseResult.error("未传变电站信息");
        }
        Map<String, Object> mapTodo = new HashMap<>();
        mapTodo.put("toBeExecute", 0);
        mapTodo.put("execute", 0);
        mapTodo.put("unExecute", 0);
        mapTodo.put("executeRate", 0);
        mapTodo.put("toBeExecuteRate", 0);
        mapTodo.put("allCount", 0);
        LambdaQueryWrapper<TaskTodo> todoQueryWrapper = new LambdaQueryWrapper<>();
        todoQueryWrapper.eq(TaskTodo::getDatastatus, "1").in(TaskTodo::getStationCode, stationCode);
        DateTime date = DateUtil.date();
        String formatDate;
        if ("1".equals(type)) {
            int year = DateUtil.year(date);
            todoQueryWrapper.like(TaskTodo::getPlanStartTime, year);
        }
        if ("2".equals(type)) {
            String format = DateUtil.format(date, "yyyy-MM");
            todoQueryWrapper.like(TaskTodo::getPlanStartTime, format);
        }
        if ("3".equals(type)) {
            List<String> weekDays = DateUtils.getWeekDays(date);
            String start = weekDays.get(0);
            String end = weekDays.get(weekDays.size() - 1);
            Date parseEnd = DateUtil.parse(end);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            String endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
            todoQueryWrapper.le(TaskTodo::getPlanStartTime, endFormat);
            todoQueryWrapper.ge(TaskTodo::getPlanStartTime, start);
        }
        if ("4".equals(type)) {
            formatDate = DateUtil.formatDate(date);
            todoQueryWrapper.like(TaskTodo::getPlanStartTime, formatDate);
        }
        List<TaskTodo> listTodo = taskTodoService.list(todoQueryWrapper);
        if (listTodo == null || listTodo.size() == 0) {
            return ResponseResult.successData(mapTodo);
        }
        /*Map<String, List<TaskTodo>> collect =
                listTodo.stream().collect(Collectors.groupingBy(TaskTodo::getStationCode));
        for (String code : collect.keySet()) {


        }*/
        List<TaskTodo> executed =
                listTodo.stream().filter(t -> ("1".equals(t.getTaskState()) || "2".equals(t.getTaskState()))).collect(Collectors.toList());
        List<TaskTodo> toBeExecuted =
                listTodo.stream().filter(t -> ("0".equals(t.getTaskState()) || "3".equals(t.getTaskState()))).collect(Collectors.toList());
        List<TaskTodo> unExecuted =
                listTodo.stream().filter(t -> ("4".equals(t.getTaskState()) || "5".equals(t.getTaskState()) || "6".equals(t.getTaskState()))).collect(Collectors.toList());
        int execute = executed.size();
        // 已执行
        mapTodo.put("execute", execute);
        int toBeExecute = toBeExecuted.size();
        // 待执行
        mapTodo.put("toBeExecute", toBeExecute);
        int allCount = listTodo.size();
        mapTodo.put("allCount", allCount);
        mapTodo.put("executeRate", (int) (((float) execute / allCount) * 100 + 0.5));
        mapTodo.put("toBeExecuteRate", (int) (((float) toBeExecute / allCount) * 100 + 0.5));
        mapTodo.put("unExecute", unExecuted.size());
        return ResponseResult.successData(mapTodo);
    }

    @GetMapping("/getAreaTaskTodoStat")
    @ApiOperation("巡视任务统计(区域)")
    public ResponseResult getAreaTaskTodoStat(String stationCode, String type) {
        if (StrUtil.isBlank(stationCode)) {
            return ResponseResult.error("未传变电站信息");
        }
        LambdaQueryWrapper<TaskTodo> todoQueryWrapper = new LambdaQueryWrapper<>();
        List<String> codeList = Arrays.asList(stationCode.split(","));
        todoQueryWrapper.eq(TaskTodo::getDatastatus, "1").in(TaskTodo::getStationCode, codeList);
        //DateTime date = DateUtil.date();
        DateTime date = DateUtil.parse("2023-5-21");
        String formatDate;
        if ("1".equals(type)) {
            List<String> weekDays = DateUtils.getWeekDays(date);
            String start = weekDays.get(0);
            String end = weekDays.get(weekDays.size() - 1);
            Date parseEnd = DateUtil.parse(end);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            String endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
            todoQueryWrapper.le(TaskTodo::getPlanStartTime, endFormat);
            todoQueryWrapper.ge(TaskTodo::getPlanStartTime, start);
        }
        if ("2".equals(type)) {
            formatDate = DateUtil.formatDate(date);
            todoQueryWrapper.like(TaskTodo::getPlanStartTime, formatDate);
        }
        List<TaskTodo> listTodo = new ArrayList<>(taskTodoService.list(todoQueryWrapper));
        Map<String, List<TaskTodo>> collect =
                listTodo.stream().collect(Collectors.groupingBy(TaskTodo::getStationCode));
        Map<String, Object> map = new HashMap<>();
        List<String> stationList = new ArrayList<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (String code : codeList) {
            Substation substation =
                    substationService.getOne(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode, code));
            stationList.add(substation.getStationName());
            List<TaskTodo> taskTodoList = collect.get(code);
            Map<String, Object> mapTodo = new HashMap<>();
            if (taskTodoList != null && taskTodoList.size() > 0) {
                long execute =
                        taskTodoList.stream().filter(t -> ("1".equals(t.getTaskState()) || "2".equals(t.getTaskState()))).count();
                long toBeExecute =
                        taskTodoList.stream().filter(t -> ("0".equals(t.getTaskState()) || "3".equals(t.getTaskState()))).count();
                long unExecute =
                        taskTodoList.stream().filter(t -> ("4".equals(t.getTaskState()) || "5".equals(t.getTaskState()) || "6".equals(t.getTaskState()))).count();
                // 已执行
                mapTodo.put("execute", execute);
                // 待执行
                mapTodo.put("toBeExecute", toBeExecute);
                int allCount = listTodo.size();
                mapTodo.put("allCount", allCount);
                mapTodo.put("executeRate", (int) (((float) execute / allCount) * 100 + 0.5));
                mapTodo.put("toBeExecuteRate", (int) (((float) toBeExecute / allCount) * 100 + 0.5));
                mapTodo.put("unExecute", unExecute);
            } else {
                // 已执行
                mapTodo.put("execute", 0);
                // 待执行
                mapTodo.put("toBeExecute", 0);
                mapTodo.put("allCount", 0);
                mapTodo.put("executeRate", 0);
                mapTodo.put("toBeExecuteRate", 0);
                mapTodo.put("unExecute", 0);
            }
            mapList.add(mapTodo);
        }
        map.put("xData", stationList);
        map.put("yData", mapList);
        return ResponseResult.successData(map);
    }

    @GetMapping("/getTaskToDoListByStation")
    @ApiOperation("巡视任务列表（前后10条）")
    public ResponseResult getTaskToDoListByStation(String stationCode, String taskName) {
        long position = taskTodoService.getLastTimePosition(stationCode, null, null, null, null);
        // 获取正在执行中任务的前后十条
        LambdaQueryWrapper<TaskTodo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskTodo::getStationCode, stationCode);
//        if (StrUtil.isNotBlank(taskName)) {
//            queryWrapper.like(TaskTodo::getTaskName, taskName);
//        }
        queryWrapper.ne(TaskTodo::getTaskType, "4");
        queryWrapper.orderByAsc(TaskTodo::getPlanStartTime).orderByAsc(TaskTodo::getTaskTodoId);
        List<Map<String, Object>> mapList = taskTodoService.listMaps(queryWrapper);
        long start = 0;
        long end = 0;
        long size = mapList.size();
        if (position == 0 && size > 0) {
            start = (size - 11) < 0 ? 0 : (size - 11);
            end = size;
        }
        if (position > 0) {
            start = (position - 11) < 0 ? 0 : (position - 11);
            end = Math.min((position + 10), size);
        }
        List<Map<String, Object>> mapList1 = mapList.subList((int) start, (int) end);
        mapList1.forEach(m -> {
            if (ObjectUtil.isNotEmpty(m.get("taskId"))) {
                String taskId = m.get("taskId").toString();
                Task task = taskService.getById(taskId);
                m.put("deviceLevel", task.getDeviceLevel());
            }
            if (!Objects.isNull(m.get("planStartTime"))) {
                DateTime dateTime = DateUtil.parse(m.get("planStartTime").toString());
                String dateFormat = DateUtil.format(dateTime, "dd日 HH:mm");
                m.put("formatDate", dateFormat);
            }

        });
        if (StrUtil.isNotBlank(taskName)) {
            List<Map<String, Object>> mapList2 =
                    mapList1.stream().filter(m -> m.get("taskName").toString().contains(taskName)).collect(Collectors.toList());
            return ResponseResult.successData(mapList2);
        }
        return ResponseResult.successData(mapList1);
    }

    @GetMapping("/getTaskToDoPage")
    @ApiOperation("分页查询巡视任务执行情况（日历）")
    public ResponseResult getTaskToDoPage(Page<Map<String, Object>> page, String stationCode, String currentDate,
                                          String startDate, String endDate, String status, String taskState, String taskName) {
        /*List<Task> list = taskService.list(new LambdaQueryWrapper<Task>().eq(Task::getStationCode, stationCode));
        Set<String> collect = list.stream().map(Task::getTaskId).collect(Collectors.toSet());*/
        // 获取当前时间最近的数据行
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }

        Map<String, Object> map2 = new HashMap<>();
        long position = taskTodoService.getLastTimePosition(stationCode, taskName, startFormat, endFormat, taskState);
        long pageSize = 0;
        if (position != 0) {
            long size = page.getSize();
            pageSize = (position % size) == 0 ? (position / size) : (position / size) + 1;
        }
        map2.put("page", pageSize);
        if ("1".equals(status)) {
            if (pageSize == 0) {
                pageSize = pageSize + 1;
            }
            page.setCurrent(pageSize);
        }
        Page<Map<String, Object>> mapPage = taskTodoService.getTaskImplementation(page, stationCode, currentDate,
                startFormat, endFormat, taskState, taskName);
        map2.put("mapPage", mapPage);
        return ResponseResult.successData(map2);
    }

    @GetMapping("/getTaskToDoMonthPage")
    @ApiOperation("分页查询巡视任务执行情况（月历）")
    public ResponseResult getTaskToDoMonthPage(String stationCode, String year, String month) {
        if (month.length() == 1) {
            month = "0" + month;
        }
        LambdaQueryWrapper<TaskTodo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(TaskTodo::getTaskType, "4").eq(TaskTodo::getStationCode, stationCode).like(TaskTodo::getPlanStartTime, year + "-" + month);
        List<Map<String, Object>> maps = taskTodoService.listMaps(queryWrapper);
        maps.forEach(m -> {
            String planStartTime = m.get("planStartTime").toString();
            DateTime parse = DateUtil.parse(planStartTime);
            String dateStr = parse.toDateStr();
            m.put("groupDate", dateStr);
        });
        Map<Object, List<Map<String, Object>>> groupDate = maps.stream().collect(Collectors.groupingBy(m -> m.get(
                "groupDate")));
        List<Map<String, Object>> listMap = new ArrayList<>();
        for (Object o : groupDate.keySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("date", o.toString());
            List<Map<String, Object>> maps1 = groupDate.get(o);
            //将处理后的list3集合按日期升序排序
            //按照时间升序排列
            maps1.sort(Comparator.comparing(o2 -> o2.get("planStartTime").toString()));
            map.put("list", maps1);
            if (maps1.size() >= 3) {
                List<Map<String, Object>> maps2 = maps1.subList(0, 3);
                map.put("list1", maps2);
            } else {
                map.put("list1", maps1);
            }
            map.put("status", "0");
            map.put("count", maps1.size());
            listMap.add(map);
        }
        return ResponseResult.successData(listMap);
    }


    @GetMapping("/getTaskToDoStatPage")
    @ApiOperation("分页查询巡视任务执行情况统计（日历）")
    public ResponseResult getTaskToDoStatList(String stationCode, String currentDate, String startDate,
                                              String endDate, String taskName) {

        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        List<Map<String, Object>> taskToDoStatList = taskTodoService.getTaskToDoStatList(stationCode, currentDate, startFormat, endFormat, null);
        Map<String, Object> map = new HashMap<>();
        map.put("allCount", taskToDoStatList.size());

        List<Map<String, Object>> taskState =
                taskToDoStatList.stream().filter(m -> "2".equals(m.get("taskState").toString())).collect(Collectors.toList());
        map.put("executing", taskState.size());
        List<Map<String, Object>> taskState1 =
                taskToDoStatList.stream().filter(m -> "1".equals(m.get("taskState").toString())).collect(Collectors.toList());
        map.put("execute", taskState1.size());
        List<Map<String, Object>> taskState2 =
                taskToDoStatList.stream().filter(m -> "3".equals(m.get("taskState").toString())).collect(Collectors.toList());
        map.put("suspend", taskState2.size());
        List<Map<String, Object>> taskState3 =
                taskToDoStatList.stream().filter(m -> "4".equals(m.get("taskState").toString())).collect(Collectors.toList());
        map.put("stop", taskState3.size());
        List<Map<String, Object>> taskState0 =
                taskToDoStatList.stream().filter(m -> "0".equals(m.get("taskState").toString())).collect(Collectors.toList());
        map.put("executed", taskState0.size());
        List<Map<String, Object>> taskState5 =
                taskToDoStatList.stream().filter(m -> "5".equals(m.get("taskState").toString())).collect(Collectors.toList());
        map.put("unexecuted", taskState5.size());
        List<Map<String, Object>> taskState6 =
                taskToDoStatList.stream().filter(m -> "6".equals(m.get("taskState").toString())).collect(Collectors.toList());
        map.put("overdue", taskState6.size());
        return ResponseResult.successData(map);
    }

    @GetMapping("/getTaskReportList")
    @ApiOperation("分页查询巡视报告")
    public ResponseResult getTaskReportList(Page<Map<String, Object>> page, String stationCode, String areaId, String taskName,
                                            String type, String startDate, String endDate, String bayId, String patrolType, String mainDeviceId) {
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        Page<Map<String, Object>> mapPage = taskTodoService.getTaskReportList(page, stationCode, areaId, taskName,
                type, startFormat, endFormat, bayId, patrolType);
        //        List<Map<String, Object>> records = mapPage.getRecords();
        //        records.forEach(r -> {
        //            String taskTodoId = r.get("taskTodoId").toString();
        //            Map<String, Object> map = taskTodoService.getTaskTodoById(taskTodoId,areaId,bayId,mainDeviceId);
        //            r.put("result", map);
        //        });
        return ResponseResult.successData(mapPage);
    }

    @PostMapping("/deleteTaskTodo")
    @ApiOperation("删除任务执行情况")
    public ResponseResult deleteTaskTodo(String taskTodoId) {
        if (StrUtil.isBlank(taskTodoId)) {
            return ResponseResult.error("参数为空");
        }
        String[] split = taskTodoId.split(",");
        for (String id : split) {
            taskTodoService.removeById(id);
        }
        return ResponseResult.success();
    }

    @GetMapping("/getTaskTodoById")
    @ApiOperation("根据巡视任务执行情况ID查看详情")
    public ResponseResult getTaskTodoById(String taskTodoId) {
        Map<String, Object> map = taskTodoService.getTaskTodoById(taskTodoId, null, null, null);
        return ResponseResult.successData(map);
    }

    @GetMapping("/exportTaskTodoById")
    @ApiOperation("导出报告")
    public void exportTaskTodoById(String taskTodoId, String areaId, String bayId, String mainDeviceId, HttpServletResponse response) throws IOException {
        Map<String, Object> map = taskTodoService.getTaskTodoById(taskTodoId, areaId, bayId, mainDeviceId);
        if (map == null) {
            return;
        }
        String stationCode = map.get("stationCode").toString();
        List<Substation> list =
                substationService.list(new LambdaQueryWrapper<Substation>().eq(Substation::getDatastatus, "1").eq(Substation::getStationCode, stationCode));
        if (list == null || list.size() == 0) {
            return;
        }
        Substation substation = list.get(0);
        String stationId = substation.getStationId();
        // 获取环境信息
        Map<String, Object> weatherDevice = weatherLogService.getWeatherLogList(stationId);
        map.put("environment", weatherDevice.get("environment"));
        /* Map<String, Object> map = BeanUtil.beanToMap(taskTodo);*/
        map.put("stationName", substation.getStationName());
        map.put("stationType", substation.getStationType());
        map.put("voltLevel", substation.getVoltLevel());
        List<Map<String, Object>> taskList = taskTodoService.getTaskResultById(map.get("taskTodoId").toString(),
                areaId, bayId, mainDeviceId);
        // 临时加的逻辑导出报告使用
        taskList.forEach(r -> {
            if (ObjectUtil.isEmpty(r.get("valid1"))) {
                r.put("valid1", "2");
            }
        });
        List<Map<String, Object>> abnormalList =
                taskList.stream().filter(t -> !Objects.isNull(t.get("valid1")) && ("2").equals(t.get("valid1").toString())).collect(Collectors.toList());
        List<Map<String, Object>> deviceByType = sysDictionaryItemsService.getDeviceByType("data_type");
        List<Map<String, Object>> normalList =
                taskList.stream().filter(t -> !Objects.isNull(t.get("valid1")) && ("1").equals(t.get("valid1").toString())).collect(Collectors.toList());
        long allCount = abnormalList.size() + normalList.size();
        if (allCount > 1000) {
            throw new RuntimeException("文件内容过大无法预览或下载");
        }
        abnormalList.forEach(a -> {
            if (!Objects.isNull(a.get("dataType"))) {
                String meterType = a.get("dataType").toString();
                for (Map<String, Object> data : deviceByType) {
                    String itemcode = data.get("itemcode").toString();
                    if (meterType.equals(itemcode)) {
                        a.put("dataType", data.get("dictname"));
                        break;
                    }
                }
            }
            a.put("index", abnormalList.indexOf(a) + 1);
            a.put("status", "异常");
            // 图片流
            try {
                String filePath = ObjectUtil.isNotEmpty(a.get("defectFilePath")) ? a.get("defectFilePath").toString() : "";
                if (StrUtil.isBlank(filePath)) {
                    filePath = a.get("filePath").toString();
                }
                if (StrUtil.isNotBlank(filePath)) {
                    filePath = URLDecoder.decode(filePath, "utf-8");
                    filePath = filePath.replace("\\", "/");
                    /*a.put("img", Pictures.ofStream(FileUtil.getImageStream(filePath), FileUtil.getPictureType
                    (filePath))
                            .size(100, 120).create());*/
                    log.info("报告图片路径" + httpServerConfig.getSnapFilePath() + filePath);
                    a.put("img", Pictures.ofStream(new FileInputStream(new File(httpServerConfig.getSnapFilePath() + filePath)),
                            FileUtil.getPictureType(filePath))
                            .size(100, 120).create());
                }

            } catch (Exception e) {
                log.error(e.getMessage());;
            }
        });
        normalList.forEach(n -> {
            if (!Objects.isNull(n.get("dataType"))) {
                String meterType = n.get("dataType").toString();
                for (Map<String, Object> data : deviceByType) {
                    String itemcode = data.get("itemcode").toString();
                    if (meterType.equals(itemcode)) {
                        n.put("dataType", data.get("dictname"));
                        break;
                    }
                }
            }
            n.put("index", normalList.indexOf(n) + 1);
            n.put("status", "正常");
            try {
                String filePath = ObjectUtil.isNotEmpty(n.get("defectFilePath")) ? n.get("defectFilePath").toString() : "";
                if (StrUtil.isBlank(filePath)) {
                    filePath = n.get("filePath").toString();
                }
                if (StrUtil.isNotBlank(filePath)) {
                    filePath = URLDecoder.decode(filePath, "utf-8");
                    filePath = filePath.replace("\\", "/");
                    log.info("报告图片路径" + httpServerConfig.getSnapFilePath() + filePath);
                    n.put("img", Pictures.ofStream(new FileInputStream(new File(httpServerConfig.getSnapFilePath() + filePath)),
                            FileUtil.getPictureType(filePath))
                            .size(100, 120).create());
                }
            } catch (Exception e) {
                log.error(e.getMessage());;
            }
        });
        List<Map<String, Object>> demo = getMapData();
        //创建一个列表的规则
        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        //设置列表配置，如果有多个列表时需加.bind("list1", policy) 新列表配置即可
        Configure config = Configure.builder().bind("normalList", policy).bind("abnormalList", policy).build();
        if (abnormalList.size() > 0) {
            map.put("abnormalList", abnormalList);
        } else {
            map.put("abnormalList", demo);
        }
        if (normalList.size() > 0) {
            map.put("normalList", normalList);
        } else {
            map.put("normalList", demo);
        }

        // 加载模板渲染数据
        String path = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource(
                "")).getPath() + "templates" + File.separator + "巡视报告模板.docx";
        XWPFTemplate compile = XWPFTemplate.compile(path, config);
        XWPFTemplate template = compile.render(map);
        //template.write(new FileOutputStream("E:\\巡视报告模板.docx"));
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename='reportTemp.docx'");

        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        bos.flush();
        out.flush();
        PoitlIOUtils.closeQuietlyMulti(template, bos, out);
    }

    @GetMapping("/exportMeterDataByTaskTodoId")
    @ApiOperation("导出表计数据")
    public void exportMeterDataByTaskTodoId(String taskTodoId, HttpServletResponse response) throws IOException {
        taskTodoService.exportMeterDataByTaskTodoId(taskTodoId,response);
    }

    @GetMapping("/sendTaskResultById")
    @ApiOperation("发送任务结果")
    public void sendTaskResultById(String id) {
        taskTodoService.sendTaskResultById(id);
    }

    @GetMapping("/exportTaskToSystem")
    @ApiOperation("导出报告到服务器")
    public void exportTaskToSystem(String taskTodoId, String areaId, String bayId, String mainDeviceId) throws Exception {
        String filename = "task_result_report.docx";
        String filepath = httpServerConfig.getSnapFilePath() + filename;
        String filePath = this.exportTaskTodo(taskTodoId, areaId, bayId, mainDeviceId, filepath);
        JSONObject jsonObject = new JSONObject();
        try {
//            Thread.sleep(20000);
            List<PlatformParentSystem> list = platformParentSystemService.list(new LambdaQueryWrapper<PlatformParentSystem>().eq(PlatformParentSystem::getIsEnable, "1"));
            if (list.size() > 0) {
                PlatformParentSystem platformParentSystem = list.get(0);
                if (tlsftpUtils.isConnected()) {
                    tlsftpUtils.disconnect();
                }
                tlsftpUtils.connect(platformParentSystem.getFtpIp(), platformParentSystem.getFtpUser(), platformParentSystem.getFtpPassword(), NumberUtil.parseInt(platformParentSystem.getFtpPort()));
                String path = String.format("/%s/%s/%s/%s/%s/",
                        "7FE4BB37-F54A-4808-852B-6CAB43DD71B3-00001",
                        DateUtil.format(DateUtil.date(), "yyyy"),
                        DateUtil.format(DateUtil.date(), "MM"),
                        DateUtil.format(DateUtil.date(), "dd"),
                        "report"
                );
                jsonObject.putOnce("file_path", path + filePath);
                tlsftpUtils.upload(path, new File(httpServerConfig.getSnapFilePath() + filePath));
                tlsftpUtils.disconnect();
            }
        } catch (Exception e) {
            tlsftpUtils.disconnect();
        }
        platformParentSystemService.sendTaskReportCommand(jsonObject.toString());
    }

    private String exportTaskTodo(String taskTodoId, String areaId, String bayId, String mainDeviceId, String filepath) throws Exception {
        Map<String, Object> map = taskTodoService.getTaskTodoById(taskTodoId, areaId, bayId, mainDeviceId);
        if (map == null) {
            return "";
        }
        String stationCode = map.get("stationCode").toString();
        List<Substation> list =
                substationService.list(new LambdaQueryWrapper<Substation>().eq(Substation::getDatastatus, "1").eq(Substation::getStationCode, stationCode));
        if (list == null || list.size() == 0) {
            return "";
        }
        Substation substation = list.get(0);
        String stationId = substation.getStationId();
        // 获取环境信息
        Map<String, Object> weatherDevice = weatherLogService.getWeatherLogList(stationId);
        map.put("environment", weatherDevice.get("environment"));
        /* Map<String, Object> map = BeanUtil.beanToMap(taskTodo);*/
        map.put("stationName", substation.getStationName());
        map.put("stationType", substation.getStationType());
        map.put("voltLevel", substation.getVoltLevel());
        List<Map<String, Object>> taskList = taskTodoService.getTaskResultById(map.get("taskTodoId").toString(),
                areaId, bayId, mainDeviceId);
        // 临时加的逻辑导出报告使用
        taskList.forEach(r -> {
            if (ObjectUtil.isEmpty(r.get("valid1"))) {
                r.put("valid1", "2");
            }
        });
        List<Map<String, Object>> abnormalList =
                taskList.stream().filter(t -> !Objects.isNull(t.get("valid1")) && ("2").equals(t.get("valid1").toString())).collect(Collectors.toList());
        List<Map<String, Object>> deviceByType = sysDictionaryItemsService.getDeviceByType("data_type");
        abnormalList.forEach(a -> {
            if (!Objects.isNull(a.get("dataType"))) {
                String meterType = a.get("dataType").toString();
                for (Map<String, Object> data : deviceByType) {
                    String itemcode = data.get("itemcode").toString();
                    if (meterType.equals(itemcode)) {
                        a.put("dataType", data.get("dictname"));
                        break;
                    }
                }
            }
            a.put("index", abnormalList.indexOf(a) + 1);
            a.put("status", "异常");
            // 图片流
            try {
                String filePath = a.get("defectFilePath").toString();
                if (StrUtil.isNotBlank(filePath)) {
                    filePath = URLDecoder.decode(filePath, "utf-8");
                    filePath = filePath.replace("\\", "/");
                    a.put("img",
                            Pictures.ofStream(new FileInputStream(new File(httpServerConfig.getSnapFilePath() + filePath)),
                                    FileUtil.getPictureType(filePath))
                                    .size(100, 120).create());
                }

            } catch (Exception e) {
                log.error(e.getMessage());;
            }
        });
        List<Map<String, Object>> normalList =
                taskList.stream().filter(t -> !Objects.isNull(t.get("valid1")) && ("1").equals(t.get("valid1").toString())).collect(Collectors.toList());
        normalList.forEach(n -> {
            if (!Objects.isNull(n.get("dataType"))) {
                String meterType = n.get("dataType").toString();
                for (Map<String, Object> data : deviceByType) {
                    String itemcode = data.get("itemcode").toString();
                    if (meterType.equals(itemcode)) {
                        n.put("dataType", data.get("dictname"));
                        break;
                    }
                }
            }
            n.put("index", normalList.indexOf(n) + 1);
            n.put("status", "正常");
            try {
                String filePath = n.get("defectFilePath").toString();
                if (StrUtil.isNotBlank(filePath)) {
                    filePath = URLDecoder.decode(filePath, "utf-8");
                    filePath = filePath.replace("\\", "/");
                    log.info("报告图片路径" + httpServerConfig.getSnapFilePath() + filePath);
                    n.put("img",
                            Pictures.ofStream(new FileInputStream(new File(httpServerConfig.getSnapFilePath() + filePath)),
                                    FileUtil.getPictureType(filePath))
                                    .size(100, 120).create());
                }
            } catch (Exception e) {
                log.error(e.getMessage());;
            }
        });
        List<Map<String, Object>> demo = getMapData();

        //创建一个列表的规则
        HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
        //设置列表配置，如果有多个列表时需加.bind("list1", policy) 新列表配置即可
        Configure config = Configure.builder().bind("normalList", policy).bind("abnormalList", policy).build();
        if (abnormalList.size() > 0) {
            map.put("abnormalList", abnormalList);
        } else {
            map.put("abnormalList", demo);
        }
        if (normalList.size() > 0) {
            map.put("normalList", normalList);
        } else {
            map.put("normalList", demo);
        }
        String planStartTime = map.get("planStartTime").toString();
        DateTime parse = DateUtil.parse(planStartTime);
        String formatDate = DateUtil.format(parse, "yyyyMMddHHmmss");
        String filePath = map.get("taskName").toString() + formatDate + ".docx";
        filepath = filepath.replace("task_result_report.docx", filePath);
        // 加载模板渲染数据
        String path = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource(
                "")).getPath() + "templates" + File.separator + "巡视报告模板.docx";
        XWPFTemplate compile = XWPFTemplate.compile(path, config);
        XWPFTemplate template = compile.render(map);
        FileOutputStream fileOutputStream = new FileOutputStream(filepath);
        template.write(fileOutputStream);
        fileOutputStream.close();
        template.close();
        compile.close();
        return filePath;
    }

    private List<Map<String, Object>> getMapData() {
        List<Map<String, Object>> demo = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("index", "");
        map.put("areaName", "");
        map.put("bayName", "");
        map.put("patroldeviceName", "");
        map.put("componentName", "");
        map.put("deviceName", "");
        map.put("dataType", "");
        map.put("time", "");
        map.put("desc", "");
        map.put("status", "");
        map.put("img", null);
        demo.add(map);
        return demo;
    }

    @GetMapping("/getAbnormalDeviceList")
    @ApiOperation("异常点位查询")
    public ResponseResult getAbnormalDeviceList(Page<Map<String, Object>> page, String stationCode, String areaId,
                                                String bayId, String taskName, String deviceName,
                                                String patroldeviceName, String componentName, String recognitionType
            , String status, String startDate, String endDate) {
        Page<Map<String, Object>> mapPage = taskTodoService.getAbnormalDeviceList(page, stationCode, areaId, bayId,
                taskName, deviceName, patroldeviceName, componentName, recognitionType, status, startDate, endDate);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getTaskResultList")
    @ApiOperation("数据对比分析列表")
    public ResponseResult getTaskResultList(Page<Map<String, Object>> page, String deviceId, String startDate,
                                            String endDate) {
        if (StrUtil.isBlank(deviceId)) {
            return ResponseResult.error("参数为空");
        }
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        Page<Map<String, Object>> resultList = taskTodoService.getTaskResultList(page, deviceId, startFormat,
                endFormat);
        List<Map<String, Object>> records = resultList.getRecords();
        records.forEach(r -> {
            String flag = r.get("flag").toString();
            String valid = "";
            if (Objects.isNull(r.get("reviseValid"))) {
                if (!Objects.isNull(r.get("valid"))) {
                    valid = r.get("valid").toString();
                }
            } else {
                String reviseValid = r.get("reviseValid").toString();
                if ("0".equals(reviseValid)) {
                    valid = "1";
                } else {
                    valid = "2";
                }
            }
            if ("4".equals(flag)) {
                r.put("analysisResult", "识别失败");
            } else if ("6".equals(flag)) {
                r.put("analysisResult", "采集失败");
            } else if ("2".equals(valid)) {
                r.put("analysisResult", "异常");
            } else if ("1".equals(valid)) {
                r.put("analysisResult", "正常");
            }
            SubstationDevice substationDevice = substationDeviceService.getById(deviceId);
            if (substationDevice != null) {
                String deviceClass = substationDevice.getDeviceClass();
                r.put("deviceClass", deviceClass);
            }
        });
        resultList.setRecords(records);
        return ResponseResult.successData(resultList);
    }

    @GetMapping("/exportTaskResultList")
    @ApiOperation("导出数据对比分析列表")
    public void exportTaskResultList(String deviceId, String startDate, String endDate, String exportFields,
                                     HttpServletResponse response) throws IOException {
        if (StrUtil.isBlank(deviceId)) {
            return;
        }
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        List<Map<String, Object>> records = taskTodoService.getTaskResultAll(deviceId, startFormat, endFormat);
        records.forEach(r -> {
            String flag = "";
            if (!Objects.isNull(r.get("flag"))) {
                flag = r.get("flag").toString();
            }
            String valid = "";
            if (Objects.isNull(r.get("reviseValid"))) {
                if (!Objects.isNull(r.get("valid"))) {
                    valid = r.get("valid").toString();
                }
            } else {
                String reviseValid = r.get("reviseValid").toString();
                if ("0".equals(reviseValid)) {
                    valid = "1";
                } else {
                    valid = "2";
                }
            }
            if ("4".equals(flag)) {
                r.put("analysisResult", "识别失败");
            } else if ("6".equals(flag)) {
                r.put("analysisResult", "采集失败");
            } else if ("2".equals(valid)) {
                r.put("analysisResult", "异常");
            } else if ("1".equals(valid)) {
                r.put("analysisResult", "正常");
            }
            String deviceClass = "";
            SubstationDevice substationDevice = substationDeviceService.getById(deviceId);
            if (substationDevice != null) {
                deviceClass = substationDevice.getDeviceClass();
            }
            r.put("deviceClass", deviceClass);
            LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SubstationPatroldevice::getPatroldeviceCode, r.get("patroldeviceCode").toString());
            queryWrapper.select(SubstationPatroldevice::getType);
            Map<String, Object> map = substationPatroldeviceService.getMap(queryWrapper);
            if (map != null) {
                r.put("type", map.get("type"));

            }
        });
        taskTodoService.exportTaskResultList(records, exportFields, response);
    }

    @GetMapping("/previewTaskResultList")
    @ApiOperation("预览数据对比分析列表")
    public ResponseResult previewTaskResultList(String deviceId, String startDate, String endDate) {
        if (StrUtil.isBlank(deviceId)) {
            return ResponseResult.error("参数为空");
        }
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        List<Map<String, Object>> records = taskTodoService.getTaskResultAll(deviceId, startFormat, endFormat);
        records.forEach(r -> {
            String flag = "";
            if (!Objects.isNull(r.get("flag"))) {
                flag = r.get("flag").toString();
            }
            String valid = "";
            if (Objects.isNull(r.get("reviseValid"))) {
                if (!Objects.isNull(r.get("valid"))) {
                    valid = r.get("valid").toString();
                }
            } else {
                String reviseValid = r.get("reviseValid").toString();
                if ("0".equals(reviseValid)) {
                    valid = "1";
                } else {
                    valid = "2";
                }
            }
            if ("4".equals(flag)) {
                r.put("analysisResult", "识别失败");
            } else if ("6".equals(flag)) {
                r.put("analysisResult", "采集失败");
            } else if ("2".equals(valid)) {
                r.put("analysisResult", "异常");
            } else if ("1".equals(valid)) {
                r.put("analysisResult", "正常");
            }
            String deviceClass = "";
            SubstationDevice substationDevice = substationDeviceService.getById(deviceId);
            if (substationDevice != null) {
                deviceClass = substationDevice.getDeviceClass();
            }
            r.put("deviceClass", deviceClass);
        });
        return ResponseResult.successData(records);
    }

    @GetMapping("/getAnalysisCurve")
    @ApiOperation("数据对比分析曲线")
    public ResponseResult getAnalysisCurve(String deviceId, String startDate, String endDate) {
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        if (StrUtil.isBlank(deviceId)) {
            return ResponseResult.error("参数为空");
        }
        Map<String, Object> map = taskTodoService.getAnalysisCurve(deviceId, startFormat, endFormat);
        return ResponseResult.successData(map);
    }

    @GetMapping("/getTaskDeviceList")
    @ApiOperation("根据任务执行情况ID查询点位查询")
    public ResponseResult getTaskDeviceList(Page<Map<String, Object>> page, String taskTodoId, String deviceName,
                                            String valid) {
        Page<Map<String, Object>> mapPage = taskTodoService.getTaskDeviceList(page, taskTodoId, deviceName, valid);
        List<Map<String, Object>> records = mapPage.getRecords();
        records.forEach(m -> {
            String flag = m.get("flag").toString();
            String valid1 = Objects.isNull(m.get("valid1")) ? "" : m.get("valid1").toString();
            if ("4".equals(flag)) {
                m.put("analysisResult", "识别失败");
            } else if ("6".equals(flag)) {
                m.put("analysisResult", "采集失败");
            } else if (StrUtil.isNotBlank(valid1) && "1".equals(valid1)) {
                m.put("analysisResult", "正常");
            } else if (StrUtil.isNotBlank(valid1) && "2".equals(valid1)) {
                m.put("analysisResult", "异常");
            } else {
                m.put("analysisResult", "");
            }
        });
        mapPage.setRecords(records);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getTaskDeviceById")
    @ApiOperation("根据任务执行情况ID查询点位查询(所有)")
    public ResponseResult getTaskDeviceById(String taskTodoId, String deviceName, String valid) {
        List<Map<String, Object>> mapList = taskTodoService.getTaskDeviceById(taskTodoId, deviceName, valid);
        mapList.forEach(m -> {
            if (ObjUtil.isNotEmpty(m.get("patroldeviceJson"))) {
//                JSONObject jobj = JSONUtil.parseObj(m.get("patroldeviceJson").toString());
                m.put("channelCode", m.get("patroldeviceChannelcode"));
                m.put("channelPos", m.get("patroldevicePos"));
            }
            String flag = m.get("flag").toString();
            String valid1 = Objects.isNull(m.get("valid1")) ? "" : m.get("valid1").toString();
            if ("4".equals(flag)) {
                m.put("analysisResult", "识别失败");
            } else if ("6".equals(flag)) {
                m.put("analysisResult", "采集失败");
            } else if (StrUtil.isNotBlank(valid1) && "1".equals(valid1)) {
                m.put("analysisResult", "正常");
            } else if (StrUtil.isNotBlank(valid1) && "2".equals(valid1)) {
                m.put("analysisResult", "异常");
            } else {
                m.put("analysisResult", "");
            }
        });
        return ResponseResult.successData(mapList);
    }

    @GetMapping("/exportAbnormalDevice")
    @ApiOperation("导出异常点位(导出全部)")
    public void exportAbnormalDevice(String stationCode, String taskName,
                                     String deviceName, String patroldeviceName,
                                     String componentName, String recognitionType, String status,
                                     String startDate, String endDate, HttpServletResponse response) throws IOException {
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        // 获取任务执行id
        List<Map<String, Object>> records = taskTodoService.getAbnormalDevice(stationCode, taskName, deviceName,
                patroldeviceName, componentName, recognitionType, status, startFormat, endFormat);
        taskTodoService.exportAbnormalDevice(records, response);
    }

    @GetMapping("/getHistoricalCurve")
    @ApiOperation("查询点位历史曲线")
    public ResponseResult getHistoricalCurve(String deviceId) {
        List<Map<String, Object>> listMap = taskTodoService.getHistoricalCurve(deviceId);
        SubstationDevice substationDevice = substationDeviceService.getById(deviceId);
        String lowerValue = "";
        String upperValue = "";
        if (substationDevice != null) {
            lowerValue = substationDevice.getLowerValue();
            upperValue = substationDevice.getUpperValue();
        }
        listMap.forEach(m -> {
            String time = m.get("time").toString();
            DateTime dateTime = DateUtil.parse(time);
            String dateFormat = DateUtil.format(dateTime, "MM月dd日 HH时mm分");
            m.put("dateTime", dateFormat);
        });
        List<Object> dateTimeList = listMap.stream().map(m -> m.get("dateTime")).collect(Collectors.toList());
        Collections.reverse(dateTimeList);
        List<Object> valueList = listMap.stream().map(m -> m.get("value")).collect(Collectors.toList());
        Collections.reverse(valueList);
        Map<String, Object> map = new HashMap<>();
        //map.put("list", listMap);
        map.put("valueList", valueList);
        map.put("dateTimeList", dateTimeList);
        map.put("lowerValue", lowerValue);
        map.put("upperValue", upperValue);
        return ResponseResult.successData(map);
    }

    @GetMapping("/getDeviceByMainDevice")
    @ApiOperation("查询主设备所关联的点位")
    public ResponseResult getDeviceByMainDevice(String mainDeviceId, String meterType, String recognitionType,
                                                String startDate, String endDate) {
        if (StrUtil.isBlank(mainDeviceId)) {
            return ResponseResult.error("参数为空");
        }
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        List<Map<String, Object>> maps = taskTodoService.getDeviceByMainDevice(mainDeviceId, meterType, recognitionType,
                startFormat, endFormat);
        return ResponseResult.successData(maps);
    }

    @GetMapping("/test")
    @ApiOperation("测试视频截图")
    public void test() throws Exception {
        //34020000001320000002_34020000001320000002
        // httpUtil.getMonitorVideoSnap("34020000001320000002","34020000001320000002");
    }

    /**********************************
     * 用途说明: 修正巡视结果
     * 参数说明 taskResult 任务识别处理结果
     * 返回值说明: 当前任务信息
     ***********************************/
    @PostMapping("/updateTaskResultById")
    @ApiOperation("修正巡视结果")
    public ResponseResult updateTaskResultById(@RequestBody TaskResult taskResult) {
        taskResult.setLastmodifier(SecurityUtils.getCurrentUsername());
        taskResult.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        boolean ok = taskTodoService.updateTaskResultById(taskResult);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修正错误");
        }

    }

    /**********************************
     * 用途说明: 修正巡视结果
     * 参数说明 taskResult 任务识别处理结果
     * 返回值说明: 当前任务信息
     ***********************************/
    @PostMapping("/updateTaskTodoById")
    @ApiOperation("审核任务执行情况")
    public ResponseResult updateTaskTodoById(@RequestBody TaskTodo taskTodo) throws Exception {
        String currentUsername = SecurityUtils.getCurrentUsername();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
        taskTodo.setExamineDate(format);
        taskTodo.setCexamineUserName(currentUsername);
        taskTodo.setLastmodifier(currentUsername);
        taskTodo.setLastmodifydate(timestamp);
        boolean ok = taskTodoService.updateById(taskTodo);
        //        List<TaskResult> abnormalResult = taskTodoService.getAbnormalResult(taskTodo.getTaskTodoId());
        //        List<DefectDevice> defectDevices = BeanUtil.copyToList(abnormalResult, DefectDevice.class);
        //        defectDeviceService.saveOrUpdateBatch(defectDevices);
        if (ok) {
            //            String filename = "task_result_report.docx";
            //            String filepath = httpServerConfig.getSnapFilePath() + filename;
            //            String taskTodoId = taskTodo.getTaskTodoId();
            //            this.exportTaskTodo(taskTodoId, null, null, null, filepath);
            //            JSONObject jsonObject = new JSONObject();
            //            jsonObject.putOnce("task_patrolled_id", taskTodoId);
            //            jsonObject.putOnce("report_path", filename);
            //            platformParentSystemService.sendTaskReportCommand(jsonObject.toString());
            return ResponseResult.success();
        } else {
            return ResponseResult.error("审核错误");
        }

    }

    /**********************************
     * 用途说明: 查询联动控制巡视任务
     * 参数说明 stationCode 变电站编号
     * 返回值说明: com.yfd.platform.config.ResponseResult
     ***********************************/
    @GetMapping("/getLinkTaskTodo")
    @ApiOperation("查询联动控制巡视任务")
    public ResponseResult getLinkTaskTodo(String stationCode, String todoId, String linkageType) {
        List<Map<String, Object>> mapList = taskTodoService.getLinkTaskTodo(stationCode, todoId, linkageType);
        if (mapList == null || mapList.size() == 0) {
            return ResponseResult.successData(null);
        }
        Map<String, Object> map = mapList.get(0);
        if (ObjectUtil.isNotEmpty(map.get("taskTodoId"))) {
            String taskTodoId = map.get("taskTodoId").toString();
            List<Map<String, Object>> taskResultList = taskTodoService.getTaskResultById(taskTodoId, null, null, null);
//            device_id_list
            String deviceIdList = map.get("deviceIdList").toString();
            List<String> ids = StrUtil.split(deviceIdList, ",");
            List<Map<String, Object>> sortList = new ArrayList<>();
            for (int i = ids.size() - 1; i >= 0; i--) {
                String id = ids.get(i);
                for (Map<String, Object> t : taskResultList) {
                    String deviceId = t.get("deviceId").toString();
                    if (id.equals(deviceId)) {
                        if (ObjectUtil.isNotEmpty(t.get("patroldeviceCode")) && ObjectUtil.isNotEmpty(t.get(
                                "patroldeviceChannelcode"))) {
                            t.put("deviceId", t.get("patroldeviceCode").toString());
                            t.put("channelId", t.get("patroldeviceChannelcode").toString());

                        }
                        String flag = ObjectUtil.isEmpty(t.get("flag")) ? "" : t.get("flag").toString();
                        String valid1 = ObjectUtil.isEmpty(t.get("valid1")) ? "" : t.get("valid1").toString();
                        if ("4".equals(flag)) {
                            t.put("analysisResult", "识别失败");
                        } else if ("6".equals(flag)) {
                            t.put("analysisResult", "采集失败");
                        } else if (StrUtil.isNotBlank(valid1) && "1".equals(valid1)) {
                            t.put("analysisResult", "正常");
                        } else if (StrUtil.isNotBlank(valid1) && "2".equals(valid1)) {
                            t.put("analysisResult", "异常");
                        } else {
                            t.put("analysisResult", "");
                        }
                        sortList.add(t);
                        break;
                    }
                }
            }
            map.put("children", sortList);
        }
        return ResponseResult.successData(map);
    }

    @GetMapping("/getLinkTaskRecordLast")
    @ApiOperation("查询联动任务最近十条")
    public ResponseResult getLinkTaskRecordLast(String stationCode, String linkageType, String taskName) {
        List<Map<String, Object>> mapList = taskTodoService.getLinkTaskRecordLast(stationCode, linkageType, taskName);
        return ResponseResult.successData(mapList);
    }

    @GetMapping("/getLinkTaskTodoList")
    @ApiOperation("查询联动任务列表")
    public ResponseResult getLinkTaskTodoList(Page<Map<String, Object>> page, String stationCode,
                                              String linkageDeviceName, String taskName, String linkageType,
                                              String linkageDeviceType, String startDate, String endDate) {
        if (StrUtil.isBlank(stationCode)) {
            return ResponseResult.error("参数为空");
        }
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }

        Page<Map<String, Object>> mapPage = taskTodoService.getLinkTaskTodoList(page, stationCode, linkageDeviceName,
                taskName, linkageType, linkageDeviceType, startFormat, endFormat);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getTaskDurationStat")
    @ApiOperation("按照日、周、月统计巡视任务")
    public ResponseResult getTaskDurationStat(String startDate, String endDate, String type) {
        List<Map<String, Object>> mapList = taskTodoService.getTaskDurationStat(startDate, endDate, type);
        return ResponseResult.successData(mapList);
    }

    @GetMapping("/exportTaskDurationStat")
    @ApiOperation("按照日、周、月统计巡视任务导出")
    public void exportTaskDurationStat(String startDate, String endDate, String type, HttpServletResponse response) throws IOException {
        taskTodoService.exportTaskDurationStat(startDate, endDate, type, response);
    }

    @GetMapping("/getHistoryDevice")
    @ApiOperation("获取历史点位")
    public ResponseResult getHistoryDevice(Page<Map<String, Object>> page, String startDate, String endDate,
                                           String deviceId) {
        Page<Map<String, Object>> mapPage = taskTodoService.getHistoryDevice(page, startDate, endDate, deviceId);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/uploadTaskTodoById")
    @ApiOperation("上传巡视报告")
    public ResponseResult uploadTaskTodoById(String taskTodoId) throws Exception {
        String[] splitIds = taskTodoId.split(",");
        for (String splitId : splitIds) {
            Map<String, Object> map = taskTodoService.getTaskTodoById(splitId, null, null, null);
            if (map == null) {
                continue;
            }
            String stationCode = map.get("stationCode").toString();
            List<Substation> list =
                    substationService.list(new LambdaQueryWrapper<Substation>().eq(Substation::getDatastatus, "1").eq(Substation::getStationCode, stationCode));
            if (list == null || list.size() == 0) {
                continue;
            }
            Substation substation = list.get(0);
            String stationId = substation.getStationId();
            // 获取环境信息
            Map<String, Object> weatherDevice = weatherLogService.getWeatherLogList(stationId);
            map.put("environment", weatherDevice.get("environment"));
            /* Map<String, Object> map = BeanUtil.beanToMap(taskTodo);*/
            map.put("stationName", substation.getStationName());
            map.put("stationType", substation.getStationType());
            map.put("voltLevel", substation.getVoltLevel());
            List<Map<String, Object>> taskList = taskTodoService.getTaskResultById(map.get("taskTodoId").toString(), null, null, null);
            List<Map<String, Object>> abnormalList =
                    taskList.stream().filter(t -> !Objects.isNull(t.get("valid1")) && ("2").equals(t.get("valid1").toString())).collect(Collectors.toList());
            List<Map<String, Object>> deviceByType = sysDictionaryItemsService.getDeviceByType("data_type");
            abnormalList.forEach(a -> {
                if (!Objects.isNull(a.get("dataType"))) {
                    String meterType = a.get("dataType").toString();
                    for (Map<String, Object> data : deviceByType) {
                        String itemcode = data.get("itemcode").toString();
                        if (meterType.equals(itemcode)) {
                            a.put("dataType", data.get("dictname"));
                            break;
                        }
                    }
                }
                a.put("index", abnormalList.indexOf(a) + 1);
                a.put("status", "异常");
                // 图片流
                try {
                    String filePath = a.get("defectFilePath").toString();
                    if (StrUtil.isNotBlank(filePath)) {
                        filePath = URLDecoder.decode(filePath, "utf-8");
                        filePath = filePath.replace("\\", "/");
                        log.info("报告图片路径" + httpServerConfig.getSnapFilePath() + filePath);
                        a.put("img",
                                Pictures.ofStream(new FileInputStream(new File(httpServerConfig.getSnapFilePath() + filePath)),
                                        FileUtil.getPictureType(filePath))
                                        .size(100, 120).create());
                    }

                } catch (Exception e) {
                    log.error(e.getMessage());;
                }
            });
            List<Map<String, Object>> normalList =
                    taskList.stream().filter(t -> !Objects.isNull(t.get("valid1")) && ("1").equals(t.get("valid1").toString())).collect(Collectors.toList());
            normalList.forEach(n -> {
                if (!Objects.isNull(n.get("dataType"))) {
                    String meterType = n.get("dataType").toString();
                    for (Map<String, Object> data : deviceByType) {
                        String itemcode = data.get("itemcode").toString();
                        if (meterType.equals(itemcode)) {
                            n.put("dataType", data.get("dictname"));
                            break;
                        }
                    }
                }
                n.put("index", normalList.indexOf(n) + 1);
                n.put("status", "正常");
                try {
                    String filePath = n.get("defectFilePath").toString();
                    if (StrUtil.isNotBlank(filePath)) {
                        filePath = URLDecoder.decode(filePath, "utf-8");
                        filePath = filePath.replace("\\", "/");
                        log.info("报告图片路径" + httpServerConfig.getSnapFilePath() + filePath);
                        n.put("img",
                                Pictures.ofStream(new FileInputStream(new File(httpServerConfig.getSnapFilePath() + filePath)),
                                        FileUtil.getPictureType(filePath))
                                        .size(100, 120).create());
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());;
                }
            });
            List<Map<String, Object>> demo = getMapData();
            //创建一个列表的规则
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            //设置列表配置，如果有多个列表时需加.bind("list1", policy) 新列表配置即可
            Configure config = Configure.builder().bind("normalList", policy).bind("abnormalList", policy).build();
            if (abnormalList.size() > 0) {
                map.put("abnormalList", abnormalList);
            } else {
                map.put("abnormalList", demo);
            }
            if (normalList.size() > 0) {
                map.put("normalList", normalList);
            } else {
                map.put("normalList", demo);
            }

            String reportName = "巡视报告模板.docx";
            // 加载模板渲染数据
            String path = Objects.requireNonNull(Objects.requireNonNull(ClassUtils.getDefaultClassLoader()).getResource(
                    "")).getPath() + "templates" + File.separator + reportName;
            XWPFTemplate compile = XWPFTemplate.compile(path, config);
            XWPFTemplate template = compile.render(map);
            String taskName = map.get("taskName").toString();
            String replaceAll = taskName.replaceAll("[/.]", "");
            String startTime = map.get("startTime").toString();
            DateTime parse = DateUtil.parse(startTime);
            String dateStr = DateUtil.format(parse, "yyyyMMDDHHmmss");
            String fileName = replaceAll + dateStr + ".docx";
            String filePath = httpServerConfig.getModelPath() + fileName;
            template.write(new FileOutputStream(filePath));
            ftpClient.uploadFile(filePath, fileName);
        }

        return ResponseResult.success();
    }

    @GetMapping("/getNonHomologousAnalysis")
    @ApiOperation("查询非同源对比分析列表")
    public ResponseResult getNonHomologousAnalysis(String stationCode, String taskName, String mainDeviceName,
                                                   String componentName, String recognitionType, String startDate, String endDate) {
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        List<Map<String, Object>> mapList = taskTodoService.getNonHomologousAnalysis(stationCode, taskName,
                mainDeviceName, componentName, recognitionType, startFormat, endFormat);
        return ResponseResult.successData(mapList);
    }

    @GetMapping("/getNonCoherentAnalysis")
    @ApiOperation("查询非同相对比分析列表")
    public ResponseResult getNonCoherentAnalysis(String stationCode, String taskName, String mainDeviceName,
                                                 String componentName, String recognitionType, String startDate,
                                                 String endDate) {
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        List<Map<String, Object>> mapList = taskTodoService.getNonCoherentAnalysis(stationCode, taskName,
                mainDeviceName, componentName, recognitionType, startFormat, endFormat);
        return ResponseResult.successData(mapList);
    }

    @GetMapping("/getTrendChangeDeviceList")
    @ApiOperation("查询趋势变化点位列表")
    public ResponseResult getTrendChangeDeviceList(Page<Map<String, Object>> page, String stationCode,
                                                   String mainDeviceName, String componentName,
                                                   String recognitionType, String deviceName, String startDate,
                                                   String endDate) {
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        Page<Map<String, Object>> mapPage = taskTodoService.getTrendChangeDeviceList(page, stationCode, mainDeviceName, componentName, recognitionType, deviceName, startFormat, endFormat);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getTrendChangeAnalysisList")
    @ApiOperation("查询趋势变化分析列表")
    public ResponseResult getTrendChangeAnalysisList(String deviceId, String startDate, String endDate) {
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        Map<String, Object> mapList = taskTodoService.getTrendChangeAnalysisList(deviceId, startFormat,
                endFormat);
        return ResponseResult.successData(mapList);
    }

    @GetMapping("/getThreadTask")
    @ApiOperation("测试查询多线程任务分配")
    public ResponseResult getThreadTask(String taskTodoId) {
        return taskTodoService.getThreadTask(taskTodoId);
    }

    @PostMapping("/onceAnalyse")
    @ApiOperation("单点识别")
    public ResponseResult onceAnalyse(@RequestBody String param) throws Exception {
        JSONObject jsonObject = JSONUtil.parseObj(param);
        boolean isOk = taskTodoService.onceAnalyse(jsonObject.getStr("id"));
        return ResponseResult.success();
    }

    @GetMapping("/getResultByPatroldevice")
    @ApiOperation("根据设备id获取点位信息")
    public ResponseResult getResultByPatroldevice(Page<Map<String, Object>> page, String patroldeviceId,
                                                  String mainDeviceId, String taskName, String recognitionType,
                                                  String valid, String isReport, String startDate, String endDate) {
        //        SubstationPatroldevice substationPatroldevice = substationPatroldeviceService.getById(patroldeviceId);
        String startFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseStart = DateUtil.parse(startDate);
            //一天的开始
            Date beginOfDay = DateUtil.beginOfDay(parseStart);
            startFormat = DateUtil.format(beginOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        String endFormat = "";
        if (StrUtil.isNotBlank(startDate)) {
            Date parseEnd = DateUtil.parse(endDate);
            //一天的结束
            Date endOfDay = DateUtil.endOfDay(parseEnd);
            endFormat = DateUtil.format(endOfDay, "yyyy-MM-dd HH:mm:ss");
        }
        Page<Map<String, Object>> mapPage = taskTodoService.getResultByPatroldevice(page, null, mainDeviceId,
                taskName, recognitionType, valid, isReport, startFormat, endFormat);
        List<Map<String, Object>> records = mapPage.getRecords();
        records.forEach(m -> {
            String flag = m.get("flag").toString();
            String valid1 = Objects.isNull(m.get("valid1")) ? "" : m.get("valid1").toString();
            if ("4".equals(flag)) {
                m.put("analysisResult", "识别失败");
            } else if ("6".equals(flag)) {
                m.put("analysisResult", "采集失败");
            } else if (StrUtil.isNotBlank(valid1) && "1".equals(valid1)) {
                m.put("analysisResult", "正常");
            } else if (StrUtil.isNotBlank(valid1) && "2".equals(valid1)) {
                m.put("analysisResult", "异常");
            } else {
                m.put("analysisResult", "");
            }
        });
        mapPage.setRecords(records);
        return ResponseResult.successData(mapPage);
    }
}
