package cn.iocoder.yudao.module.pms.controller.admin.iotprojecttask;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.datapermission.core.util.DataPermissionUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotattachment.vo.IotAttachmentPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotattachment.vo.IotAttachmentRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotprojectinfo.vo.IotProjectInfoPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotprojecttask.vo.*;
import cn.iocoder.yudao.module.pms.controller.admin.iotrddailyreport.vo.IotRdDailyReportPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotrddailyreport.vo.IotRdDailyReportStatisticsItemVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotattachment.IotAttachmentDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotprojectinfo.IotProjectInfoDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotprojecttask.IotProjectTaskDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotprojecttaskattrs.IotTaskAttrModelProperty;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotrddailyreport.IotRdDailyReportDO;
import cn.iocoder.yudao.module.pms.dal.mysql.iotattachment.IotAttachmentMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.iotprojectinfo.IotProjectInfoMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.iotrddailyreport.IotRdDailyReportMapper;
import cn.iocoder.yudao.module.pms.enums.AttachmentCategoryEnum;
import cn.iocoder.yudao.module.pms.enums.AttachmentTypeEnum;
import cn.iocoder.yudao.module.pms.service.iotprojectinfo.IotProjectInfoService;
import cn.iocoder.yudao.module.pms.service.iotprojecttask.IotProjectTaskService;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.dict.DictDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.MapUtils.findAndThen;


@Tag(name = "管理后台 - 项目信息任务拆分")
@RestController
@RequestMapping("/rq/iot-project-task")
@Validated
public class IotProjectTaskController {

    @Resource
    private IotProjectTaskService iotProjectTaskService;
    @Resource
    private DeptService deptService;

    @Resource
    private IotProjectInfoService iotProjectInfoService;
    @Resource
    private IotRdDailyReportMapper iotRdDailyReportMapper;
    @Resource
    private IotProjectInfoMapper iotProjectInfoMapper;
    @Resource
    private DictDataService dictDataService;
    @Resource
    private IotAttachmentMapper iotAttachmentMapper;

    @PostMapping("/create")
    @Operation(summary = "创建项目信息任务拆分")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:create')")
    public CommonResult<Boolean> createIotProjectTask(@RequestBody IotTaskSaveVO createReqVO) {
        return success(iotProjectTaskService.createIotProjectTaskList(createReqVO.getTaskList()));
    }

    @PutMapping("/update")
    @Operation(summary = "更新项目信息任务拆分")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:update')")
    public CommonResult<Boolean> updateIotProjectTask(@RequestBody IotTaskSaveVO updateReqVO) {
        iotProjectTaskService.updateIotProjectTaskList(updateReqVO.getTaskList());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除项目信息任务拆分")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:delete')")
    public CommonResult<Boolean> deleteIotProjectTask(@RequestParam("id") Long id) {
        iotProjectTaskService.deleteIotProjectTask(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得项目信息任务拆分")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:query')")
    public CommonResult<IotProjectTaskRespVO> getIotProjectTask(@RequestParam("id") Long id) {
        IotProjectTaskDO iotProjectTask = iotProjectTaskService.getIotProjectTask(id);
        return success(BeanUtils.toBean(iotProjectTask, IotProjectTaskRespVO.class));
    }

    @PostMapping("/generateReport")
    @Operation(summary = "基于新建的任务井号 生成指定日期的日报 (默认生成当天的日报)")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:query')")
    public CommonResult<Long> generateReport(@RequestBody IotProjectTaskPageReqVO reqVO) {
        Long newTaskId = iotProjectTaskService.generateReport(reqVO);
        return success(newTaskId);
    }

    @GetMapping("/page")
    @Operation(summary = "获得项目信息任务拆分分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:query')")
    public CommonResult<PageResult<IotProjectTaskRespVO>> getIotProjectTaskPage(@Valid IotProjectTaskPageReqVO pageReqVO) {
        Set<Long> idList = new HashSet<>();
        /* if(Objects.nonNull(pageReqVO.getDeptId())){
            idList =  deptService.getChildDeptIdListFromCache(pageReqVO.getDeptId());
            idList.add(pageReqVO.getDeptId());
        } */
        PageResult<IotProjectTaskDO> pageResult = iotProjectTaskService.getIotProjectTaskPage1(pageReqVO, idList);

        return success(new PageResult<>(buildTasks(pageResult.getList()), pageResult.getTotal()));
    }

    /**
     * 组装 设备-bom 关联关系对象
     * @param pagedTasks
     * @return
     */
    private List<IotProjectTaskRespVO> buildTasks(List<IotProjectTaskDO> pagedTasks) {
        if (CollUtil.isEmpty(pagedTasks)) {
            return Collections.emptyList();
        }
        Map<Long, List<IotProjectTaskPlatformVO>> platformWellPair = new HashMap<>();
        // 查询每口井的已完成工作量
        IotRdDailyReportPageReqVO reportReqVO = new IotRdDailyReportPageReqVO();
        reportReqVO.setTaskIds(convertList(pagedTasks, IotProjectTaskDO::getId));
        List<IotRdDailyReportDO> dailyReports = iotRdDailyReportMapper.dailyReports(reportReqVO);
        // key任务井id      value队伍工作量数据
        Map<Long, BigDecimal> bridgePlugPair = new HashMap<>();
        Map<Long, BigDecimal> runCountPair = new HashMap<>();
        Map<Long, BigDecimal> cumulativeWorkingWellPair = new HashMap<>();
        Map<Long, BigDecimal> hourCountPair = new HashMap<>();
        Map<Long, BigDecimal> waterVolumePair = new HashMap<>();
        Map<Long, BigDecimal> pumpTripsPair = new HashMap<>();
        Map<Long, BigDecimal> cumulativeWorkingLayersPair = new HashMap<>();
        Map<Long, BigDecimal> mixSandPair = new HashMap<>();
        if (CollUtil.isNotEmpty(dailyReports)) {
            dailyReports.forEach(report -> {
                // 设置每个任务的工作量数据  单位相同的工作量值作合并处理
                List<IotTaskAttrModelProperty> taskAttrs = report.getExtProperty();
                // 暂存不同单位的工作量属性值
                BigDecimal tempTotalBridgePlug = BigDecimal.ZERO;               // 桥塞(个数)
                BigDecimal tempTotalRunCount = BigDecimal.ZERO;                 // 趟数
                BigDecimal tempTotalCumulativeWorkingWell = BigDecimal.ZERO;    // 井数
                BigDecimal tempTotalHourCount = BigDecimal.ZERO;                // 小时H
                BigDecimal tempTotalWaterVolume = BigDecimal.ZERO;              // 水方量(方)
                BigDecimal tempTotalPumpTrips = BigDecimal.ZERO;
                BigDecimal tempTotalCumulativeWorkingLayers = BigDecimal.ZERO;  // 段数  累计施工-层
                BigDecimal tempTotalMixSand = BigDecimal.ZERO;                  // 台次 当日泵车台次 当日仪表/混砂
                if (CollUtil.isNotEmpty(taskAttrs)) {
                    for (IotTaskAttrModelProperty attr : taskAttrs) {
                        String unit = attr.getUnit();   // 工作量单位
                        String actualValueStr = attr.getActualValue();  // 工作量属性的实际值
                        // 处理实际值：避免null或非数字字符串导致的异常
                        BigDecimal actualValue = BigDecimal.ZERO;
                        if (StrUtil.isNotBlank(actualValueStr)) {  // 假设使用Hutool的StrUtil，或自行判断null/空
                            try {
                                actualValue = new BigDecimal(actualValueStr);
                            } catch (NumberFormatException e) {
                                // 若字符串格式错误，默认按0处理（可根据业务调整）
                                actualValue = BigDecimal.ZERO;
                            }
                        }
                        if ("个数".equals(unit)) {
                            // 钻可溶桥塞  钻复合桥塞
                            tempTotalBridgePlug = tempTotalBridgePlug.add(actualValue);
                            if (bridgePlugPair.containsKey(report.getTaskId())) {
                                BigDecimal tempBridgePlug = bridgePlugPair.get(report.getTaskId());
                                bridgePlugPair.put(report.getTaskId(), tempTotalBridgePlug.add(tempBridgePlug));
                            } else {
                                bridgePlugPair.put(report.getTaskId(), tempTotalBridgePlug);
                            }
                        }
                        if ("趟数".equals(unit)) {
                            tempTotalRunCount = tempTotalRunCount.add(actualValue);
                            if (runCountPair.containsKey(report.getTaskId())) {
                                BigDecimal tempRunCount = runCountPair.get(report.getTaskId());
                                runCountPair.put(report.getTaskId(), tempTotalRunCount.add(tempRunCount));
                            } else {
                                runCountPair.put(report.getTaskId(), tempTotalRunCount);
                            }
                        }
                        if ("小时".equals(unit)) {
                            tempTotalHourCount = tempTotalHourCount.add(actualValue);
                            if (hourCountPair.containsKey(report.getTaskId())) {
                                BigDecimal tempHourCount = hourCountPair.get(report.getTaskId());
                                hourCountPair.put(report.getTaskId(), tempTotalHourCount.add(tempHourCount));
                            } else {
                                hourCountPair.put(report.getTaskId(), tempTotalHourCount);
                            }
                        }
                        if ("天数".equals(unit)) {
                            // 将 actualValue 换算成 H
                            BigDecimal hours = actualValue.multiply(new BigDecimal("24"));
                            tempTotalHourCount = tempTotalHourCount.add(hours);
                            if (hourCountPair.containsKey(report.getTaskId())) {
                                BigDecimal tempHourCount = hourCountPair.get(report.getTaskId());
                                hourCountPair.put(report.getTaskId(), tempTotalHourCount.add(tempHourCount));
                            } else {
                                hourCountPair.put(report.getTaskId(), tempTotalHourCount);
                            }
                        }
                        if ("方".equals(unit)) {
                            tempTotalWaterVolume = tempTotalWaterVolume.add(actualValue);
                            if (waterVolumePair.containsKey(report.getTaskId())) {
                                BigDecimal tempWaterVolume = waterVolumePair.get(report.getTaskId());
                                waterVolumePair.put(report.getTaskId(), tempTotalWaterVolume.add(tempWaterVolume));
                            } else {
                                waterVolumePair.put(report.getTaskId(), tempTotalWaterVolume);
                            }
                        }
                        if ("井数".equals(unit)) {
                            tempTotalCumulativeWorkingWell = tempTotalCumulativeWorkingWell.add(actualValue);
                            if (cumulativeWorkingWellPair.containsKey(report.getTaskId())) {
                                BigDecimal tempWorkingWell = cumulativeWorkingWellPair.get(report.getTaskId());
                                cumulativeWorkingWellPair.put(report.getTaskId(), tempTotalCumulativeWorkingWell.add(tempWorkingWell));
                            } else {
                                cumulativeWorkingWellPair.put(report.getTaskId(), tempTotalCumulativeWorkingWell);
                            }
                        }
                        if ("段数".equals(unit)) {
                            // 累计施工层
                            tempTotalCumulativeWorkingLayers = tempTotalCumulativeWorkingLayers.add(actualValue);
                            if (cumulativeWorkingLayersPair.containsKey(report.getTaskId())) {
                                BigDecimal tempWorkingLayer = cumulativeWorkingLayersPair.get(report.getTaskId());
                                cumulativeWorkingLayersPair.put(report.getTaskId(), tempTotalCumulativeWorkingLayers.add(tempWorkingLayer));
                            } else {
                                cumulativeWorkingLayersPair.put(report.getTaskId(), tempTotalCumulativeWorkingLayers);
                            }
                        }
                        if ("台次".equals(unit) && "当日泵车台次".equals(attr.getName())) {
                            tempTotalPumpTrips = tempTotalPumpTrips.add(actualValue);
                            if (pumpTripsPair.containsKey(report.getTaskId())) {
                                BigDecimal tempPumpTrips = pumpTripsPair.get(report.getTaskId());
                                pumpTripsPair.put(report.getTaskId(), tempTotalPumpTrips.add(tempPumpTrips));
                            } else {
                                pumpTripsPair.put(report.getTaskId(), tempTotalPumpTrips);
                            }
                        }
                        if ("台次".equals(unit) && ("当日仪表/混砂".equals(attr.getName())
                                || "当日混砂".equals(attr.getName()) || "当日仪表".equals(attr.getName()))) {
                            tempTotalMixSand = tempTotalMixSand.add(actualValue);
                            if (mixSandPair.containsKey(report.getTaskId())) {
                                BigDecimal tempMixSand = mixSandPair.get(report.getTaskId());
                                mixSandPair.put(report.getTaskId(), tempTotalMixSand.add(tempMixSand));
                            } else {
                                mixSandPair.put(report.getTaskId(), tempTotalMixSand);
                            }
                        }
                    }
                }
            });
        }
        // key任务id   value任务已经完成的工作量集合
        Map<Long, List<IotRdDailyReportStatisticsItemVO>> taskFinishedWorkloadPair = new HashMap<>();
        // 循环每个任务 找到任务 关联的平台井
        if (CollUtil.isNotEmpty(pagedTasks)) {
            pagedTasks.forEach(task -> {
                // 查询任务主井及关联井的扩展属性 组装 工作量集合 extProperty dropdownList
                String platformGroup = task.getPlatformGroup();
                if (StrUtil.isNotBlank(platformGroup)) {
                    // 根据 platformGroup 查询关联的平台井
                    IotProjectTaskPageReqVO reqVO = new IotProjectTaskPageReqVO();
                    reqVO.setPlatformGroup(platformGroup);
                    List<IotProjectTaskDO> tasks = iotProjectTaskService.projectTasks(reqVO);
                    List<IotProjectTaskPlatformVO> platforms = new ArrayList<>();
                    tasks.forEach(groupTask -> {
                        IotProjectTaskPlatformVO tempPlatform = new IotProjectTaskPlatformVO();
                        tempPlatform.setId(groupTask.getId());
                        tempPlatform.setWellName(groupTask.getWellName());
                        tempPlatform.setWorkloadDesign(groupTask.getWorkloadDesign());
                        tempPlatform.setExtProperty(groupTask.getExtProperty());
                        platforms.add(tempPlatform);
                    });
                    platformWellPair.put(task.getId(), platforms);
                }
                // 设置每个任务的已完成工作量信息
                List<IotRdDailyReportStatisticsItemVO> items = new ArrayList<>();
                // 以队伍为维度 设置每种施工工艺的工作量 总和
                if (bridgePlugPair.containsKey(task.getId())) {
                    // 钻可溶桥塞  钻复合桥塞
                    IotRdDailyReportStatisticsItemVO item = new IotRdDailyReportStatisticsItemVO();
                    item.setUnit("个数");
                    item.setWorkload(bridgePlugPair.get(task.getId()));
                    items.add(item);
                }
                if (runCountPair.containsKey(task.getId())) {
                    // 通刮洗  冲砂
                    IotRdDailyReportStatisticsItemVO item = new IotRdDailyReportStatisticsItemVO();
                    item.setUnit("趟数");
                    item.setWorkload(runCountPair.get(task.getId()));
                    items.add(item);
                }
                if (hourCountPair.containsKey(task.getId())) {
                    // 液氮泵车(时间D)  千型泵车(时间H)
                    IotRdDailyReportStatisticsItemVO item = new IotRdDailyReportStatisticsItemVO();
                    item.setUnit("小时");
                    item.setWorkload(hourCountPair.get(task.getId()));
                    items.add(item);
                }
                if (waterVolumePair.containsKey(task.getId())) {
                    // 注水
                    IotRdDailyReportStatisticsItemVO item = new IotRdDailyReportStatisticsItemVO();
                    item.setUnit("方");
                    item.setWorkload(waterVolumePair.get(task.getId()));
                    items.add(item);
                }
                if (cumulativeWorkingWellPair.containsKey(task.getId())) {
                    // 连续油管常规作业
                    IotRdDailyReportStatisticsItemVO item = new IotRdDailyReportStatisticsItemVO();
                    item.setUnit("井数");
                    item.setWorkload(cumulativeWorkingWellPair.get(task.getId()));
                    items.add(item);
                }
                if (cumulativeWorkingLayersPair.containsKey(task.getId())) {
                    // 压裂大包 压裂总包
                    IotRdDailyReportStatisticsItemVO item = new IotRdDailyReportStatisticsItemVO();
                    item.setUnit("段数");
                    item.setWorkload(cumulativeWorkingLayersPair.get(task.getId()));
                    items.add(item);
                }
                if (pumpTripsPair.containsKey(task.getId())) {
                    // 主压裂车 当日泵车台次
                    IotRdDailyReportStatisticsItemVO item = new IotRdDailyReportStatisticsItemVO();
                    item.setUnit("台次");
                    item.setWorkload(pumpTripsPair.get(task.getId()));
                    items.add(item);
                }
                if (mixSandPair.containsKey(task.getId())) {
                    // 当日仪表/混砂 台次
                    IotRdDailyReportStatisticsItemVO item = new IotRdDailyReportStatisticsItemVO();
                    item.setUnit("台次");
                    item.setWorkload(mixSandPair.get(task.getId()));
                    items.add(item);
                }
                taskFinishedWorkloadPair.put(task.getId(), items);
            });
        }
        // 查询当前任务关联的 附件列表
        Map<Long, List<IotAttachmentRespVO>> attachmentsPair = new HashMap<>();
        IotAttachmentPageReqVO attReqVO = new IotAttachmentPageReqVO();
        attReqVO.setCategory(AttachmentCategoryEnum.DAILY_REPORT.getCode());
        attReqVO.setTypes(Arrays.asList(AttachmentTypeEnum.CONSTRUCTION_DESIGN.getCode(),
                AttachmentTypeEnum.GEOLOGICAL_DESIGN.getCode(), AttachmentTypeEnum.COMPLETION_REPORT.getCode()));
        attReqVO.setBizIds(convertList(pagedTasks, IotProjectTaskDO::getId));
        List<IotAttachmentDO> attachments = iotAttachmentMapper.attachments(attReqVO);
        if (CollUtil.isNotEmpty(attachments)) {
            attachments.forEach(att -> {
                IotAttachmentRespVO attResp = BeanUtils.toBean(att, IotAttachmentRespVO.class);
                if (attachmentsPair.containsKey(att.getBizId())) {
                    List<IotAttachmentRespVO> tempAttachments = attachmentsPair.get(att.getBizId());
                    tempAttachments.add(attResp);
                    attachmentsPair.put(att.getBizId(), tempAttachments);
                } else {
                    List<IotAttachmentRespVO> tempAttachments = new ArrayList<>();
                    tempAttachments.add(attResp);
                    attachmentsPair.put(att.getBizId(), tempAttachments);
                }
            });
        }
        // 找到任务对应的合同信息
        Map<Long, String> projectPair = new HashMap<>();
        List<Long> projectIds = convertList(pagedTasks, IotProjectTaskDO::getProjectId);
        // 查询所有 项目信息
        IotProjectInfoPageReqVO reqVO = new IotProjectInfoPageReqVO();
        reqVO.setProjectIds(projectIds);
        List<IotProjectInfoDO> projects = iotProjectInfoMapper.selectList(reqVO);
        if (CollUtil.isNotEmpty(projects)) {
            projects.forEach(project -> {
                projectPair.put(project.getId(), project.getContractName());
            });
        }
        // 2. 拼接数据
        return BeanUtils.toBean(pagedTasks, IotProjectTaskRespVO.class, (taskVO) -> {
            // 拼接平台井信息
            findAndThen(platformWellPair, taskVO.getId(), tasks -> taskVO.setPlatformWells(tasks));
            // 附件
            findAndThen(attachmentsPair, taskVO.getId(), attachmentRespS -> taskVO.setAttachments(attachmentRespS));
            // 任务已经完成的工作量
            findAndThen(taskFinishedWorkloadPair, taskVO.getId(), workloads -> taskVO.setItems(workloads));
            // 设置任务的 合同信息
            findAndThen(projectPair, taskVO.getProjectId(), projectName -> taskVO.setContractName(projectName));
        });
    }

    @GetMapping("/list")
    @Operation(summary = "获得项目信息任务拆分全部数据")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:query')")
    public CommonResult<PageResult<IotProjectTaskRespVO>> getTaskList(IotProjectTaskPageReqVO pageReqVO) {
        Set<Long> idList = new HashSet<>();
        if (StrUtil.isNotBlank(pageReqVO.getSearchKey())) {
            // app 端搜索
            PageResult<IotProjectTaskDO> taskList = iotProjectTaskService.appTaskList(pageReqVO, idList);
            return success(new PageResult<>(buildProjectTaskList(taskList.getList()), taskList.getTotal()));
        } else {
            PageResult<IotProjectTaskDO> taskList = iotProjectTaskService.taskList(pageReqVO, idList);
            return success(new PageResult<>(buildProjectTaskList(taskList.getList()), taskList.getTotal()));
        }
    }

    @GetMapping("/taskWellNames")
    @Operation(summary = "查看某个专业公司下去重后的所有任务列表")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:query')")
    public CommonResult<List<IotProjectTaskRespVO>> taskWellNames( IotProjectTaskPageReqVO pageReqVO) {
        List<IotProjectTaskDO> wellNames = iotProjectTaskService.taskWellNames(pageReqVO);
        return success(BeanUtils.toBean(wellNames, IotProjectTaskRespVO.class));
    }

    @GetMapping("/taskTreeWellNames")
    @Operation(summary = "查看某个专业公司下去重后的所有任务列表 构建树层级关系")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:query')")
    public CommonResult<List<IotProjectTaskTreeRespVO>> taskTreeWellNames(IotProjectTaskPageReqVO pageReqVO) {
        IotProjectInfoPageReqVO projectReqVO = new IotProjectInfoPageReqVO();
        projectReqVO.setDeptId(pageReqVO.getCompanyId());
        projectReqVO.setContractName(pageReqVO.getSearchKey());
        List<IotProjectInfoDO> projects = iotProjectInfoMapper.sortedProjects(projectReqVO);
        List<IotProjectTaskTreeRespVO> results = new ArrayList<>();

        if (CollUtil.isNotEmpty(projects)) {
            projects.forEach(project -> {
                IotProjectTaskTreeRespVO tempProject = new IotProjectTaskTreeRespVO();
                tempProject.setType("1");
                tempProject.setProjectId(project.getId());
                tempProject.setProjectName(project.getContractName());
                tempProject.setProjectCreateTime(project.getCreateTime());
                results.add(tempProject);
            });
        }
        List<IotProjectTaskDO> wellNames = iotProjectTaskService.taskWellNames(pageReqVO);
        if (CollUtil.isNotEmpty(wellNames)) {
            wellNames.forEach(wellName -> {
                IotProjectTaskTreeRespVO tempTask = new IotProjectTaskTreeRespVO();
                tempTask.setType("2");
                tempTask.setProjectId(wellName.getProjectId());
                tempTask.setTaskId(wellName.getId());
                tempTask.setWellName(wellName.getWellName());
                tempTask.setTaskCreateTime(wellName.getCreateTime());
                results.add(tempTask);
            });
        }
        return success(results);
    }

    private List<IotProjectTaskRespVO> buildProjectTaskList(List<IotProjectTaskDO> tasks) {
        if (CollUtil.isEmpty(tasks)) {
            return Collections.emptyList();
        }
        // 设置任务状态(区分 瑞恒 瑞都 瑞鹰)
        // 施工状态 字典数据
        List<DictDataDO> rdStatusData = dictDataService.getDictDataListByDictType("rdStatus");
        List<DictDataDO> repairStatusData = dictDataService.getDictDataListByDictType("repairStatus");
        List<DictDataDO> rigStatus = dictDataService.getDictDataListByDictType("rigStatus");
        List<DictDataDO> constructionStatus = dictDataService.getDictDataListByDictType("constructionStatus");
        // key施工状态数据字典value   value施工状态数据字典label  瑞恒
        Map<String, String> constructStatusPair = new HashMap<>();
        // key施工状态数据字典value   value施工状态数据字典label 瑞都
        Map<String, String> rdStatusPair = new HashMap<>();
        // key施工状态数据字典value   value施工状态数据字典label 瑞鹰钻井
        Map<String, String> rigStatusPair = new HashMap<>();
        // key施工状态数据字典value   value施工状态数据字典label 瑞鹰修井
        Map<String, String> repairStatusPair = new HashMap<>();
        if (CollUtil.isNotEmpty(rdStatusData)) {
            rdStatusData.forEach(data -> {
                rdStatusPair.put(data.getValue(), data.getLabel());
            });
        }
        if (CollUtil.isNotEmpty(repairStatusData)) {
            repairStatusData.forEach(data -> {
                repairStatusPair.put(data.getValue(), data.getLabel());
            });
        }
        if (CollUtil.isNotEmpty(rigStatus)) {
            rigStatus.forEach(data -> {
                rigStatusPair.put(data.getValue(), data.getLabel());
            });
        }
        if (CollUtil.isNotEmpty(constructionStatus)) {
            constructionStatus.forEach(data -> {
                constructStatusPair.put(data.getValue(), data.getLabel());
            });
        }

        // 设备部门信息
        List<Long> projectIds = convertList(tasks, IotProjectTaskDO::getProjectId);
        // 查询当前分页任务的关联 施工队伍信息
        Set<Long> deptIds = new HashSet<>();
        // key任务id  value任务施工状态标签值
        Map<Long, String> taskStatusPair = new HashMap<>();
        tasks.forEach(task -> {
            if (CollUtil.isNotEmpty(task.getDeptIds())) {
                deptIds.addAll(task.getDeptIds());
            }
            if (StrUtil.isNotBlank(task.getStatus())) {

            }
            // 瑞都施工状态
            if (StrUtil.isNotBlank(task.getRdStatus())) {
                if (rdStatusPair.containsKey(task.getRdStatus())) {
                    taskStatusPair.put(task.getId(), rdStatusPair.get(task.getRdStatus()));
                }
            }
            // 瑞鹰钻井施工状态
            if (StrUtil.isNotBlank(task.getRigStatus())) {
                if (rigStatusPair.containsKey(task.getRigStatus())) {
                    taskStatusPair.put(task.getId(), rigStatusPair.get(task.getRigStatus()));
                }
            }
            // 瑞鹰修井施工状态
            if (StrUtil.isNotBlank(task.getRepairStatus())) {
                if (repairStatusPair.containsKey(task.getRepairStatus())) {
                    taskStatusPair.put(task.getId(), repairStatusPair.get(task.getRepairStatus()));
                }
            }
            // 瑞恒施工状态
            if (StrUtil.isNotBlank(task.getStatus()) && StrUtil.isBlank(task.getRdStatus()) && StrUtil.isBlank(task.getRigStatus()) && StrUtil.isBlank(task.getRepairStatus())) {
                if (constructStatusPair.containsKey(task.getStatus())) {
                    taskStatusPair.put(task.getId(), constructStatusPair.get(task.getStatus()));
                }
            }
        });
        Map<Long, DeptDO> deptMap = new HashMap<>();
        // 查询当前分布任务关联的施工队伍信息
        DataPermissionUtils.executeIgnore(() -> {
            Map<Long, DeptDO> tempDeptMap = deptService.getDeptMap(deptIds);
            deptMap.putAll(tempDeptMap);
        });
        Map<Long, Long> projectDeptPair = new HashMap<>();
        if (CollUtil.isNotEmpty(projectIds)) {
            // 查询 任务 关联的项目信息
            IotProjectInfoPageReqVO pageReqVO = new IotProjectInfoPageReqVO();
            pageReqVO.setProjectIds(projectIds);
            DataPermissionUtils.executeIgnore(() -> {
                List<IotProjectInfoDO> projectInfos = iotProjectInfoService.getIotProjectInfos(pageReqVO);
                if (CollUtil.isNotEmpty(projectInfos)) {
                    projectInfos.forEach(info -> {
                        projectDeptPair.put(info.getId(), info.getDeptId());
                    });
                }
            });
        }
        // 2. 拼接数据
        return BeanUtils.toBean(tasks, IotProjectTaskRespVO.class, (taskVO) -> {
            if (projectDeptPair.containsKey(taskVO.getProjectId())) {
                taskVO.setProjectDeptId(projectDeptPair.get(taskVO.getProjectId()));
            }
            // 任务施工状态
            findAndThen(taskStatusPair, taskVO.getId(), statusLabel -> taskVO.setStatusLabel(statusLabel));
            // 设置施工队伍名称
            if (CollUtil.isNotEmpty(taskVO.getDeptIds())) {
                Set<String> deptNames = new HashSet<>();
                taskVO.getDeptIds().forEach(deptId -> {
                    if (deptMap.containsKey(deptId)) {
                        deptNames.add(deptMap.get(deptId).getName());
                    }
                });
                taskVO.setDeptNames(StrUtil.join(StrUtil.COMMA, deptNames));
            }
        });
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出项目信息任务列表 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-project-task:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotProjectTaskExcel(@Valid IotProjectTaskPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        Set<Long> idList = new HashSet<>();
        List<IotProjectTaskDO> taskList = iotProjectTaskService.taskList(pageReqVO, idList).getList();
        List<IotProjectTaskRespVO> tasks = buildProjectTaskList(taskList);
        // 导出 Excel
        ExcelUtils.write(response, "任务查看列表.xls", "任务查看列表", IotProjectTaskRespVO.class,
                tasks);
    }

}