package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.net.HttpHeaders;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;

import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;

import com.yeejoin.amos.boot.module.hygf.api.Enum.CommonEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;

import com.yeejoin.amos.boot.module.hygf.api.util.JsonUtils;
import com.yeejoin.amos.boot.module.hygf.biz.feign.WorkflowFeignClient;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.component.robot.BadRequest;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.util.MapHelper;
import org.apache.commons.io.FileUtils;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.Bean;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.io.IOException;
import java.lang.reflect.Field;

import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 公共服务实现类
 *
 * @author hzz
 * @date 2024-06-20
 */
@Service
@Slf4j
public class CommonServiceImpl {
    //    @Autowired
//    private TaskV2FeignService taskV2FeignService;
    @Autowired
    private RedisUtils redisUtils;
    @Value("classpath:/json/hygfRouth.json")
    private Resource urlInfo;
    @Autowired
    SurveyInformationServiceImpl surveyInformationServiceImpl;
    @Autowired
    DocumentStationMapper documentStationMapper;
    private static final String regionRedis = "app_region_redis";
    @Autowired
    RedisUtils redisUtil;
    @Autowired
    private AmosRequestContext amosRequestContext;
    @Value("${urlHttp}")
    private String urlPath;
    @Autowired
    WorkflowFeignClient workflowFeignClient;
    @Autowired
    PowerStationMapper powerStationMapper;
    @Autowired
    HygfWorkOrderStationAuditingMapper workOrderStationAuditingMapper;
    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
    @Autowired
    BasicGridAuditingMapper basicGridAuditingMapper;
    @Autowired
    ConstructionRecordsMapper constructionRecordsMapper;
    @Autowired
    PreparationMoneyServiceImpl preparationMoneyService;
    @Autowired
    PreparationMoneyMapper preparationMoneyMapper;
    @Autowired
    private HygfReplenishmentMapper hygfReplenishmentMapper;
    @Autowired
    PreparationMoneyLogMapper preparationMoneyLogMapper;
    @Autowired
    DesignInformationMapper designInformationMapper;
    @Autowired
    HygfPreparationMoneyAuditingMapper preparationMoneyAuditingMapper;
    @Autowired
    ConstructionGirdRecordsMapper constructionGirdRecordsMapper;
    @Autowired
    ConstructionAcceptanceRecordsMapper constructionAcceptanceRecordsMapper;
    @Autowired
    FinancingAuditingMapper financingAuditingMapper;
    private static final String TEMP_DIR_NAME = "temp";
    private static final String TEMPLATE_FILE_PATH = "templates/informationTemp.xlsx"; // 模版文件路径

    private ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    private ExecutorService executorService = Executors.newFixedThreadPool(50); // 创建固定大小的线程池
    public String getRouthPath(String type,Object model) {
        List<Map> urlList = JsonUtils.getResourceList(urlInfo);
        String routhPath="";
        String urlParams = "";
        try {
            urlParams = "&" + toQueryParams(model);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (Map map : urlList) {
            if (map.get("type").equals(type)) {
                routhPath = (map.get("url").toString() + urlParams);
                break;
            }
        }
        return routhPath;
    }
//    private static String toQueryParams2(JSONObject jsonObject) {
//        StringBuilder sb = new StringBuilder();
//        Set<String> keys = jsonObject.keySet();
//        keys.forEach(key -> {
//            Object value = jsonObject.get(key);
//            if (sb.length() > 0) {
//                sb.append('&');
//            }
//            try {
//                if (value != null && !"".equals(value)) {
//                    sb.append(URLEncoder.encode(key, "UTF-8")).append('=').append(URLEncoder.encode(value.toString(), "UTF-8"));
//                }
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        });
//        return sb.toString();
//    }

//    public List<TaskModelDto> buildTaskModelDto(Object model, WorkflowResultDto workflowResultDto, BusinessTypeEnum businessType) {
//        List<TaskModelDto> taskModelDtoList = new ArrayList<>();
//        TaskModelDto taskModelDto = new TaskModelDto();
//        FlowKeyTodoEnum flowKeyTodoEnum = FlowKeyTodoEnum.getEumByFlowNodeKey(workflowResultDto.getNextNodeKey());
//        if (!Objects.isNull(flowKeyTodoEnum)) {
//            taskModelDto.setFlowStatus(flowKeyTodoEnum.getCode());
//            taskModelDto.setFlowStatusLabel(flowKeyTodoEnum.getDealName());
//        }
//        taskModelDto.setRoutePath(null);
//        taskModelDto.setFlowCode(workflowResultDto.getNextTaskId());
//        taskModelDto.setFlowCreateDate(new Date());
//        taskModelDto.setPageType(null);
//        taskModelDto.setExecuteUserIds(workflowResultDto.getNextExecuteUserIds());
//        taskModelDto.setModel(model);
//        taskModelDto.setRelationId(workflowResultDto.getInstanceId());
//        taskModelDto.setStartUserId(workflowResultDto.getStartUserId());
//        taskModelDto.setStartUser(workflowResultDto.getStartUser());
//        taskModelDto.setStartDate(workflowResultDto.getStartDate());
//        taskModelDto.setStartUserCompanyName(workflowResultDto.getStartUserCompanyName());
//        taskModelDto.setTaskName(workflowResultDto.getNextNodeName());
//        taskModelDto.setTaskCode(workflowResultDto.getNextNodeKey());
//        taskModelDto.setTaskType(businessType.getCode());
//        taskModelDto.setTaskTypeLabel(businessType.getName());
//        taskModelDto.setTaskStatus(FlowStatusEnum.TO_BE_PROCESSED.getCode());
//        taskModelDto.setTaskStatusLabel(FlowStatusEnum.TO_BE_PROCESSED.getName());
////        taskModelDto.setTaskDesc();
////        taskModelDto.setTaskContent();
//        taskModelDto.setNextExecuteUser(workflowResultDto.getNextExecutorIds());
//        taskModelDtoList.add(taskModelDto);
//        return taskModelDtoList;
//    }

//    public void deleteTaskModel(String id) {
//        try {
//            List<TaskV2Model> result = taskV2FeignService.selectListByRelationId(id).getResult();
//            if (!result.isEmpty()) {
//                List<Long> idList = result.stream().map(TaskV2Model::getSequenceNbr).collect(Collectors.toList());
//                String ids = idList.stream().map(Object::toString).collect(Collectors.joining(","));
//                taskV2FeignService.delete(ids);
//            }
//        }catch (Exception e){
//            log.error(e.getMessage(),e);
//        }
//    }

//    /**
//     * 待办新增接口
//     **/
//    public void buildTaskModel(List<TaskModelDto> list) {
//        try {
//            //执行人为空使用系统机器人账号
//            if (StrUtil.isEmpty(RequestContext.getExeUserId())) {
//                RequestContext.setExeUserId(amosRequestContext.getUserId());
//                RequestContext.setToken(amosRequestContext.getToken());
//                RequestContext.setAgencyCode("JXIOP");
//            }
//            List<TaskV2Model> taskV2Models = new ArrayList<>();
//            for (TaskModelDto obj : list) {
//                // 判断是否是暂存 新增若无下一节点执行人即为暂存
//                boolean flag = StringUtils.isEmpty(obj.getNextExecuteUser());
//                if (flag) {
//                    List<TaskV2Model> result = taskV2FeignService.selectListByRelationId(obj.getRelationId()).getResult();
//                    if (CollectionUtil.isNotEmpty(result)) {
//                        break;
//                    }
//                }
//                //处理开始流程人员为空的问题
//                dealStartUser(obj);
//                TaskV2Model model = new TaskV2Model();
//                BeanUtil.copyProperties(obj, model);
//                String urlParams = "&formType=edit";
//                try {
//                    urlParams = "&" + toQueryParams(obj.getModel());
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                List<Map> urlList = JsonUtils.getResourceList(urlInfo);
//                for (Map map : urlList) {
//                    if (map.get("type").equals(obj.getTaskCode())) {
//                        model.setRoutePath(map.get("url").toString() + urlParams);
//                        break;
//                    }
//                }
//                // 是true则为暂存 除公共部分统一处理
//                if (flag) {
//                    Object redisUserInfo = redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken()));
//                    if (Objects.isNull(redisUserInfo)) {
//                        break;
//                    }
//                    ReginParams reginParams = JSONObject.parseObject(redisUserInfo.toString(), ReginParams.class);
//                    model.setFlowStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode());
//                    model.setFlowStatusLabel(FlowStatusEnum.TO_BE_SUBMITTED.getName());
//                    model.setStartUserId(RequestContext.getExeUserId());
//                    model.setStartUser(reginParams.getUserModel().getRealName());
//                    model.setStartUserCompanyName(reginParams.getCompany().getCompanyName());
//                    model.setStartDate(new Date());
//                    model.setExecuteUserIds(RequestContext.getExeUserId());
//                    model.setFlowCreateDate(new Date());
//                    model.setTaskStatus(FlowStatusEnum.TO_BE_SUBMITTED.getCode());
//                    model.setTaskTitle("有一条待提交的草稿");
//                    model.setTaskName(BusinessTypeEnum.getNameByType(obj.getTaskType()));
//                    model.setTaskTypeLabel(BusinessTypeEnum.getNameByType(obj.getTaskType()));
//                    //     model.setTaskContent("【申请单号:"+obj.getTaskCode()+"】待提交");
//                } else {
//                    model.setTaskStatus(0);
//                    model.setTaskTitle(obj.getStartUser() + "发起了" + obj.getTaskName());
//                }
//                model.setFlowInstanceId(model.getRelationId());
//                model.setTaskSource("workFlow");
//                model.setExtras(JSON.toJSONString(obj.getModel()));
//                // model.setTerminal(params.getOrDefault("terminal","WEB").toString());
//                model.setCreateDate(new Date());
//                model.setRecUserId(RequestContext.getExeUserId());
//                model.setAgencyCode(RequestContext.getAgencyCode());
//                taskV2Models.add(model);
//
//            }
//            //如果使用的是机器人则使用机器人的token、appkey、product进行调用
//            if (amosRequestContext.getUserId().equals(RequestContext.getExeUserId())) {
//                taskV2FeignService.batchAddStringNew(amosRequestContext.getAppKey(), amosRequestContext.getProduct(), amosRequestContext.getToken(), JSONArray.toJSONString(taskV2Models));
//            } else {
//                taskV2FeignService.batchAddString(JSONArray.toJSONString(taskV2Models));
//            }
//        }catch (Exception e){
//            log.error(e.getMessage(),e);
//        }
//    }

//    private void dealStartUser(TaskModelDto obj) {
//        if (StrUtil.isEmpty(obj.getStartUser())) {
//            List<TaskV2Model> result = taskV2FeignService.selectListByRelationId(obj.getRelationId()).getResult();
//            if (CollectionUtil.isNotEmpty(result)) {
//                List<TaskV2Model> collect = result.stream().filter(item -> item.getStartUser() != null).collect(Collectors.toList());
//                if (CollectionUtil.isNotEmpty(collect)) {
//                    TaskV2Model taskV2Model = collect.get(0);
//                    obj.setStartUserId(taskV2Model.getStartUserId());
//                    obj.setStartUser(taskV2Model.getStartUser());
//                    obj.setStartDate(taskV2Model.getStartDate());
//                    obj.setStartUserCompanyName(taskV2Model.getStartUserCompanyName());
//                }
//            }
//        }
//    }

//    /**
//     * 待办编辑接口
//     * 参数
//     * taskStatus
//     * taskStatusLabel 操作名称  6614驳回 6616已完成 6612待受理
//     * flowStatusLabel  任务状态枚举code
//     * 流程实例id  instanceId
//     * flowCode 任务id
//     **/
//    public TaskV2Model updateTaskModel(Map<String, Object> params) {
//        try {
//            String exeUserId = RequestContext.getExeUserId();
//            List<TaskV2Model> result = taskV2FeignService.selectListByRelationId(params.get("relationId").toString()).getResult();
//            List<TaskV2Model> collect = result.stream().sorted((r1, r2) -> r2.getSequenceNbr().compareTo(r1.getSequenceNbr())).collect(Collectors.toList());
//
//            if (collect.isEmpty()) {
//                return null;
//            }
//            collect.get(0).setFlowStatus(Integer.valueOf(params.get("flowStatus").toString()));
//            collect.get(0).setFlowStatusLabel(params.get("flowStatusLabel").toString());
//            collect.get(0).setTaskStatus(Integer.valueOf(params.get("taskStatus").toString()));
//            collect.get(0).setTaskStatusLabel(params.get("taskStatusLabel").toString());
//            collect.get(0).setEndUserId(exeUserId);
//            collect.get(0).setEndDate(new Date());
//            // 当流程完成时将所有待办状态统一修改为已完成
//            String urlParams = "&formType=detail";
//            if (collect.get(0).getFlowStatusLabel().equals(FlowStatusEnum.TO_BE_FINISHED.getName())) {
//                try {
//                    urlParams = "&" + toQueryParams(params.get("model"));
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//                List<Map> urlList = JsonUtils.getResourceList(urlInfo);
//                for (Map map : urlList) {
//                    //此处单独处理经销商审核 审核完成后跳转列表页面
//                    if("jxs_03".equals(collect.get(0).getTaskCode())){
//                        urlParams = "/mixuap?appId=1678340647909617665&id=1678365817248444417"+ urlParams;
//                        break;
//                    }
//                    if (map.get("type").equals(collect.get(0).getTaskCode())) {
//                        urlParams = map.get("url").toString() + urlParams;
//                        break;
//                    }
//                }
//                collect.get(0).setRoutePath(urlParams);
//                for (TaskV2Model taskV2Model : collect) {
//                    taskV2Model.setTaskStatusLabel((FlowStatusEnum.TO_BE_FINISHED.getName()));
//                    taskV2Model.setTaskStatus(FlowStatusEnum.TO_BE_FINISHED.getCode());
//                    taskV2Model.setFlowStatusLabel((FlowStatusEnum.TO_BE_FINISHED.getName()));
//                    taskV2Model.setFlowStatus(FlowStatusEnum.TO_BE_FINISHED.getCode());
//                }
//                taskV2FeignService.batchUpdateString(JSONArray.toJSONString(collect));
//            } else {
//                collect.get(0).setRoutePath(collect.get(0).getRoutePath().replace("roleIds=", "roleIds=55555&fq="));
//                taskV2FeignService.update(collect.get(0), collect.get(0).getSequenceNbr());
//            }
//            // 修改model并返回 用于组装新待办
//            collect.get(0).setEndUserId(null);
//            collect.get(0).setTaskStatus(null);
//            collect.get(0).setEndDate(null);
//            collect.get(0).setSequenceNbr(null);
//            collect.get(0).setCreateDate(new Date());
//            collect.get(0).setStartDate(new Date());
//            return collect.get(0);
//        }catch (Exception e){
//            log.error(e.getMessage(),e);
//        }
//        return null;
//    }


//    /**
//     * 待办 撤回
//     *
//     * @param id  工作流实例id
//     * @param obj 自己的实体：taskType为BusinessTypeEnum code；nextExecuteUser
//     */
//    public void rollbackTask(String id, JSONObject obj) {
//
//        List<TaskV2Model> result = taskV2FeignService.selectListByRelationId(id).getResult();
//        List<TaskV2Model> list = result.stream().sorted((r1, r2) -> r2.getSequenceNbr().compareTo(r1.getSequenceNbr())).collect(Collectors.toList());
//        TaskV2Model model = list.get(0);
//        taskV2FeignService.delete(String.valueOf(model.getSequenceNbr()));
//
//        String urlParams = "";
//        urlParams = "&" + toQueryParams2(obj);
//        List<Map> urlList = JsonUtils.getResourceList(urlInfo);
//
//        if (list.size() > 1) {
//            TaskV2Model lastTaskModel = list.get(1);
//            lastTaskModel.setEndUserId(null);
//            lastTaskModel.setEndDate(null);
//            lastTaskModel.setTaskStatus(FlowStatusEnum.TO_SUBMITTED.getCode());
//            lastTaskModel.setTaskStatusLabel("重新提交");
//            lastTaskModel.setFlowCode(obj.get("nextTaskId").toString());
//            if (obj.get("flowStatus") != null) {
//                lastTaskModel.setFlowStatus(Integer.valueOf(obj.get("flowStatus").toString()));
//            }
//            if (obj.get("flowStatusLabel") != null) {
//                lastTaskModel.setFlowStatusLabel(obj.get("flowStatusLabel").toString());
//            }
//
//            for (Map map : urlList) {
//                if (map.get("type").equals(obj.get("taskType")) && map.get("pageType").equals(obj.getOrDefault("pageType", "edit"))) {
//                    lastTaskModel.setRoutePath(map.get("url").toString().replace("{roleIds}", obj.get("nextExecuteUser").toString()) + urlParams);
//                    break;
//                }
//            }
//            taskV2FeignService.update(lastTaskModel, lastTaskModel.getSequenceNbr());
//        } else if (list.size() == 1) {
//            model.setExecuteUserIds(model.getStartUserId());
//            model.setTaskStatusLabel("重新提交");
//            model.setTaskStatus(FlowStatusEnum.TO_SUBMITTED.getCode());
//            model.setSequenceNbr(null);
//            if (obj.get("flowStatus") != null) {
//                model.setFlowStatus(Integer.valueOf(obj.get("flowStatus").toString()));
//            }
//            if (obj.get("flowStatusLabel") != null) {
//                model.setFlowStatusLabel(obj.get("flowStatusLabel").toString());
//            }
//            for (Map map : urlList) {
//                if (map.get("type").equals(obj.get("taskType")) && map.get("pageType").equals("edit")) {
//                    model.setRoutePath(map.get("url").toString().replace("{roleIds}", obj.get("nextExecuteUser").toString()) + urlParams);
//                    break;
//                }
//            }
//            taskV2FeignService.create(model);
//        }
//    }

    private  <T> String toQueryParams(T obj) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();

        for (Class<?> clazz = obj.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                if (!Modifier.isStatic(field.getModifiers())) {
                    field.setAccessible(true);

                    try {
                        Object value = field.get(obj);

                        if (value != null && !"".equals(value)) {
                            String encodedValue = URLEncoder.encode(value.toString(), "UTF-8");
                            sb.append(field.getName()).append('=').append(encodedValue).append('&');
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
    }

//    /**
//     * 更新并完成
//     * @param object
//     * @param workflowResultDto
//     * @param businessTypeEnum
//     */
//    public void updateTaskModelAndAddTask(Object object, WorkflowResultDto workflowResultDto, BusinessTypeEnum businessTypeEnum) {
//       try {
//           Map<String, Object> updateTaskParam = new HashMap<>();
//           updateTaskParam.put("flowStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
//           updateTaskParam.put("flowStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
//           updateTaskParam.put("taskStatus", FlowStatusEnum.TO_BE_FINISHED.getCode());
//           updateTaskParam.put("taskStatusLabel", FlowStatusEnum.TO_BE_FINISHED.getName());
//           updateTaskParam.put("model", object);
//           updateTaskParam.put("relationId", workflowResultDto.getInstanceId());
//           updateTaskModel(updateTaskParam);
//           buildTaskModel((buildTaskModelDto(object, workflowResultDto, businessTypeEnum)));
//       }catch (Exception e){
//           log.error(e.getMessage(),e);
//       }
//
//    }

    public JSONArray getRegionName() {
        JSONArray jsonArray = new JSONArray();
        if (redisUtil.hasKey(regionRedis)) {
            jsonArray = JSONArray.parseArray(redisUtil.get(regionRedis).toString());
        } else {
            Collection<RegionModel> regionChild = new ArrayList<>();
            RegionModel regionModel1 = new RegionModel();
            regionChild.add(regionModel1);
            FeignClientResult<Collection<RegionModel>> collectionFeignClientResult = Systemctl.regionClient.queryForTreeParent(null);
            Collection<RegionModel> result = collectionFeignClientResult.getResult();
            for (RegionModel regionModel : result) {
                if (null != regionModel && null != regionModel.getChildren()) {
                    for (RegionModel child : regionModel.getChildren()) {
                        if (null != child && null != child.getChildren()) {
                            for (RegionModel childChild : child.getChildren()) {
                                jsonArray.add(childChild);
                            }
                            child.setChildren(regionChild);
                            jsonArray.add(child);
                        }
                    }
                    regionModel.setChildren(regionChild);
                    jsonArray.add(regionModel);
                }else {
                    jsonArray.add(regionModel);
                }
            }

            redisUtil.set(regionRedis, jsonArray);
        }
        return jsonArray;
    }


    public static Path createUniqueDirectory(Path baseDir, String baseName) {
        Path dirPath = baseDir.resolve(baseName);

        // 检查目录是否存在
        if (Files.exists(dirPath)) {
            // 如果目录存在，则尝试创建带有数字后缀的目录
            int counter = 1;
            while (true) {
                String newName = baseName + "_" + counter;
                dirPath = baseDir.resolve(newName);
                if (!Files.exists(dirPath)) {
                    break; // 找到了一个新的名称，退出循环
                }
                counter++;
            }
        }

        // 创建目录
        try {
            Files.createDirectories(dirPath);
            return dirPath;
        } catch (IOException e) {
            System.err.println("Failed to create directory: " + dirPath);
            e.printStackTrace();
            return null;
        }
    }

    public void downZiliao(String surveyInformationId, List<String> peasantHouseholdIds, String processInstanceId, HttpServletResponse response) throws IOException {
        String fileName = "";
        String redisKey = "";
        if (peasantHouseholdIds.size()>1){
            redisKey = String.join(",", peasantHouseholdIds);
        }else {
            redisKey = peasantHouseholdIds.get(0);
        }
        int baifenbi = 100 / peasantHouseholdIds.size();
        int currentBili = 0;
        Path currentWorkingDir = Paths.get("");
        // 获取当前工作目录
        Path rootDir = currentWorkingDir;
        Path ziLiaoDir =rootDir.resolve("批量资料");
        for (String peasantHouseholdId : peasantHouseholdIds) {
            SurveyInfoAllDto returnDto = surveyInformationServiceImpl.querySurveyInfo(surveyInformationId, peasantHouseholdId, processInstanceId, null);
            fileName = returnDto.getSurveyInformation().getOwnersName();
            //客户优化项 补充发货信息
            PreparationMoney preparationMoneyDto = preparationMoneyMapper.selectPreparationMoneyInfo(peasantHouseholdId);

           String preparationMoneyInstanceId = null;
            if (null != preparationMoneyDto){
                preparationMoneyDto.setDeliveryFile(null != preparationMoneyDto.getDelFile()?JSONArray.parseArray(preparationMoneyDto.getDelFile()):null);
                preparationMoneyDto.setArrivalFile(null != preparationMoneyDto.getArrFile()?JSONArray.parseArray(preparationMoneyDto.getArrFile()):null);
                LambdaUpdateWrapper<PreparationMoneyLog> q1 = new LambdaUpdateWrapper<>();
                q1.eq(PreparationMoneyLog::getPreparationMoneyId, preparationMoneyDto.getSequenceNbr());
                q1.orderByAsc(PreparationMoneyLog::getExecutionTime);
                List<PreparationMoneyLog> preparationMoneyLogs = preparationMoneyLogMapper.selectList(q1);

                if (!Objects.isNull(preparationMoneyLogs)){
                    preparationMoneyDto.setPreparationMoneyLog(preparationMoneyLogs);
                }

                LambdaUpdateWrapper<HygfPreparationMoneyAuditing> q2 = new LambdaUpdateWrapper<>();
                q2.eq(HygfPreparationMoneyAuditing::getPreparationMoneyId, preparationMoneyDto.getSequenceNbr());
                q2.orderByAsc(HygfPreparationMoneyAuditing::getRecDate);
                q2.last("limit 1");
                HygfPreparationMoneyAuditing hygfPreparationMoneyAuditing = preparationMoneyAuditingMapper.selectOne(q2);

                if (null != hygfPreparationMoneyAuditing){
                    preparationMoneyInstanceId = hygfPreparationMoneyAuditing.getInstanceId();
                }
                //查询补货单
                LambdaQueryWrapper<HygfReplenishment> files = new LambdaQueryWrapper<>();
                files.eq(HygfReplenishment::getPreparationMoneyId,preparationMoneyDto.getSequenceNbr());
                files.orderByDesc(BaseEntity::getRecDate);
                List<HygfReplenishment> hygfReplenishments = hygfReplenishmentMapper.selectList(files);

                List<Map> hygfReplenishmentFiles = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(hygfReplenishments)){
                    preparationMoneyDto.setHygfReplenishments(hygfReplenishments);
                    for (HygfReplenishment hygfReplenishment : hygfReplenishments) {
                        hygfReplenishmentFiles.addAll(hygfReplenishment.getFile());
                    }
                    preparationMoneyDto.setReplenishmentFile(hygfReplenishmentFiles);
                }
            }


            if (!redisKey.contains(",")){
                redisUtils.set(redisKey, MapBuilder.<String, Object>create()
                        .put("value", currentBili).build());
            }

            String powerStationInstanceId = powerStationMapper.getInstanceIdByhouseId(peasantHouseholdId);
            String financingInstanceId  = financingAuditingMapper.getInstanceIdByhouseId(peasantHouseholdId);
            List<LinkedHashMap> powerStationWorkLog = new ArrayList<>();
            List<ConstructionRecords> workOrderStationWorkLog = new ArrayList<>();
            List<ConstructionGirdRecords> basicGridWorkLog = new ArrayList<>();
            List<LinkedHashMap> financingWorkLog = new ArrayList<>();
            List<LinkedHashMap> preparationMoneyLog = new ArrayList<>();
            List<ConstructionAcceptanceRecords> accptWorkLog = new ArrayList<>();
            workOrderStationWorkLog = this.getConstructionRecords(returnDto.getPowerStationEngineeringInfo().getWorkOrderPowerStationId(),returnDto.getPowerStationEngineeringInfo().getWorkOrderId());
            accptWorkLog = this.getConstructionRecordsAcc(peasantHouseholdId);
            basicGridWorkLog = this.getConstructionRecordsBasic(peasantHouseholdId);

            try {
                powerStationWorkLog = this.getWorkLog(powerStationInstanceId);
                financingWorkLog = this.getWorkLog(financingInstanceId);
                preparationMoneyLog = this.getWorkLog(preparationMoneyInstanceId);

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


            Path templateDir = Paths.get(TEMPLATE_FILE_PATH).getParent();
            System.out.println("模版文件所在目录是: " + templateDir);


            Path tempDir = createUniqueDirectory(ziLiaoDir, returnDto.getSurveyInformation().getOwnersName());
            String wenjianjia = tempDir.toString().replace("\\","/");
            try {
                Files.createDirectories(tempDir); // 创建临时目录
                System.out.println("Temporary directory created at: " + tempDir);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }

            String templatePath = "templates/informationTemp.xlsx";
            //String templatePath = "F:\\work\\amos-boot-zx-biz\\amos-boot-system-jxiop\\amos-boot-module-hygf-biz\\src\\main\\resources\\templates\\informationTemp.xlsx";
            //  String outputPath = "F:\\work\\amos-boot-zx-biz\\amos-boot-system-jxiop\\amos-boot-module-hygf-biz\\src\\main\\resources\\templates\\temp\\"+returnDto.getSurveyInformation().getOwnersName()+".xlsx";
            String outputPath =wenjianjia+"/"+returnDto.getSurveyInformation().getOwnersName()+".xlsx";

            Workbook workbook = null;
            try (  InputStream fis = new ClassPathResource(templatePath).getInputStream()){
                workbook = new XSSFWorkbook(fis);

                Sheet firstSheet = workbook.getSheetAt(0);
                fillSheet(firstSheet, returnDto.getSurveyInformation());

                Sheet secondSheet = workbook.getSheetAt(1);
                fillSheet(secondSheet, returnDto.getSurveyDetails());

                Sheet secondSheet2 = workbook.getSheetAt(2);
                fillSheet(secondSheet2, returnDto.getDesignInformation());

                Sheet secondSheet3 = workbook.getSheetAt(3);
                fillSheet(secondSheet3, returnDto.getCommercial());

                Sheet secondSheet4 = workbook.getSheetAt(4);
                fillSheet(secondSheet4, returnDto.getExtendedInformation());

                Sheet secondSheet5 = workbook.getSheetAt(5);
                fillSheet(secondSheet5, returnDto.getInformation());

                Sheet secondSheet6 = workbook.getSheetAt(6);
                fillSheet(secondSheet6, returnDto.getPowerStationEngineeringInfo());

                Sheet secondSheet7 = workbook.getSheetAt(7);
                fillSheet(secondSheet7, preparationMoneyDto);
                fillSheetFH(secondSheet7, preparationMoneyDto);

                Sheet secondSheet8 = workbook.getSheetAt(8);
                fillSheet(secondSheet8, returnDto.getPowerStationConstructionData());

                Sheet secondSheet9 = workbook.getSheetAt(9);
                fillSheet(secondSheet9, returnDto.getHygfOnGrid());

                Sheet secondSheet10 = workbook.getSheetAt(10);
                fillSheet(secondSheet10, returnDto.getWorkOrder());

                Sheet secondSheet11 = workbook.getSheetAt(11);
                fillSheet(secondSheet11, returnDto.getAcceptanceCheck());

                Sheet secondSheet12 = workbook.getSheetAt(12);
                fillSheet(secondSheet12, powerStationWorkLog);

                Sheet secondSheet13 = workbook.getSheetAt(13);
                if (CollectionUtil.isNotEmpty(preparationMoneyLog)){
                    fillSheet(secondSheet13, preparationMoneyLog);
                }else if (CollectionUtil.isNotEmpty(preparationMoneyLog)){
                    fillSheet(secondSheet13, preparationMoneyDto != null?preparationMoneyDto.getPreparationMoneyLog():null);
                }
                Sheet secondSheet14 = workbook.getSheetAt(14);
                fillSheet(secondSheet14, workOrderStationWorkLog);

                Sheet secondSheet15 = workbook.getSheetAt(15);
                fillSheet(secondSheet15, basicGridWorkLog);

                Sheet secondSheet16 = workbook.getSheetAt(16);
                fillSheet(secondSheet16, accptWorkLog);

                Sheet secondSheet17 = workbook.getSheetAt(17);
                fillSheet(secondSheet17, financingWorkLog);
                // 写入到新的Excel文件中
                try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                    workbook.write(fos);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (!redisKey.contains(",")){
                currentBili = currentBili + 15 ;
                redisUtils.set(redisKey, MapBuilder.<String, Object>create()
                        .put("value", currentBili).build());
            }
            List<HygfRectificationOrder> areaOrdersCon =new ArrayList<>();
            if (ObjectUtils.isNotEmpty(returnDto.getHygfOnGrid())) {
                areaOrdersCon = Optional.ofNullable(returnDto.getPowerStationConstructionData().getAreaOrders())
                        .orElse(new ArrayList<>());
                addNonNullList(areaOrdersCon, returnDto.getPowerStationConstructionData().getDesignOrders());
                addNonNullList(areaOrdersCon, returnDto.getPowerStationConstructionData().getEngineeringOrders());
            }
            // 主方法或代码块
            List<HygfRectificationOrder> areaOrders =new ArrayList<>();
            if (ObjectUtils.isNotEmpty(returnDto.getHygfOnGrid())) {
                areaOrders = Optional.ofNullable(returnDto.getHygfOnGrid().getAreaOrders())
                        .orElse(new ArrayList<>());
                addNonNullList(areaOrders, returnDto.getHygfOnGrid().getDesignOrders());
                addNonNullList(areaOrders, returnDto.getHygfOnGrid().getEngineeringOrders());
            }
            List<HygfRectificationOrder> areaOrdersAcc = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(returnDto.getAcceptanceCheck())){
                areaOrdersAcc = Optional.ofNullable(returnDto.getAcceptanceCheck().getAreaOrders())
                        .orElse(new ArrayList<>());
                addNonNullList(areaOrdersAcc, returnDto.getAcceptanceCheck().getLegalOrders());
                addNonNullList(areaOrdersAcc, returnDto.getAcceptanceCheck().getFinanceOrders());
                addNonNullList(areaOrdersAcc, returnDto.getAcceptanceCheck().getPropertyOrders());
            }

            List<Future<?>> futures = new ArrayList<>();
            String finalRedisKey = redisKey;
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(returnDto.getSurveyInformation(),"基本信息附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(returnDto.getSurveyDetails(),"勘察信息附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(preparationMoneyDto,"发货信息附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(returnDto.getDesignInformation(),"设计信息附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(returnDto.getCommercial(),"商务信息附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(returnDto.getInformation(),"资料归档附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(returnDto.getPowerStationConstructionData(),"施工信息附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            List<HygfRectificationOrder> finalAreaOrdersCon = areaOrdersCon;
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(finalAreaOrdersCon,"施工信息整改单附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(returnDto.getHygfOnGrid(),"并网信息附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            List<HygfRectificationOrder> finalAreaOrders = areaOrders;
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(finalAreaOrders,"并网信息整改单附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(returnDto.getWorkOrder(),"派工单信息附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            List<HygfRectificationOrder> finalAreaOrdersAcc = areaOrdersAcc;
            futures.add(executorService.submit(() -> {
                try {
                    downloadAndZipImages(finalAreaOrdersAcc,"验收信息整改单附件",tempDir,urlPath);
                    if (!finalRedisKey.contains(",")){
                        Map<String, Object> map = (Map<String, Object>) redisUtils.get(finalRedisKey);
                        Integer currentNum = (Integer) map.get("value")+7;
                        redisUtils.set(finalRedisKey, MapBuilder.<String, Object>create()
                                .put("value", currentNum).build());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }));
            // 等待所有任务完成
            for (Future<?> future : futures) {
                try {
                    future.get();
                } catch (InterruptedException | ExecutionException e) {
                    Throwable cause = e.getCause();
                    if (cause instanceof IOException) {
                        ((IOException) cause).printStackTrace();
                        // 可以在这里记录日志或者采取其他补救措施
                    } else {
                        e.printStackTrace();
                    }
                    // 根据具体情况，可以在这里选择终止程序或进行其他处理
                    return;
                }
            }

            //  response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+returnDto.getSurveyInformation().getOwnersName()+".zip");
            if (redisKey.contains(",")){
                currentBili = currentBili + baifenbi;
                redisUtils.set(redisKey,MapBuilder.<String, Object>create()
                        .put("value", currentBili).build());
            }
        }

        String encodedFilename = "";
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        if (peasantHouseholdIds.size() > 1){
            fileName = "批量资料";

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName+".zip", "UTF-8"));
            createZipFile(ziLiaoDir, fileName,response);
        }else {

            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName+".zip", "UTF-8"));
            createZipFile(ziLiaoDir, "批量资料/"+fileName,response);
        }
        redisUtils.set(redisKey, MapBuilder.<String, Object>create()
                .put("value", 100).build());


        cleanup(ziLiaoDir);
    }

    public void   test (HttpServletResponse response) throws UnsupportedEncodingException {
        String fileName = "批量资料";
        Path currentWorkingDir = Paths.get("");
        // 获取当前工作目录
        Path rootDir = currentWorkingDir;
        Path ziLiaoDir =rootDir.resolve("批量资料");
        String encodedFilename = URLEncoder.encode( fileName+".zip", StandardCharsets.UTF_8.name());
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName+".zip", "UTF-8"));
        createZipFile(ziLiaoDir, "批量资料",response);
    }
    private void autoSizeColumns(Sheet sheet) {
        if (null != sheet.getRow(0) ){
            for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
                sheet.autoSizeColumn(i);
            }
        }
    }


    private void fillSheetFH(Sheet sheet, PreparationMoney preparationMoney){
        if (Objects.isNull(preparationMoney)){
            return;
        }

        LambdaQueryWrapper<DocumentStation> q = new LambdaQueryWrapper<>();
        q.eq(DocumentStation::getPreparationMoneyId, preparationMoney.getSequenceNbr());
        List<DocumentStation> lih = documentStationMapper.selectList(q);

        if(lih != null && lih.size() > 0) {
            lih.forEach(e -> {
                if(e.getPeasantHouseholdNo() != null) {
                    e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
                    e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
                }
            });

        }

        List<Long> ids = new ArrayList<>();
        for (DocumentStation documentStation : lih) {
            ids.add(documentStation.getStationId());
        }
        //获取所有电站Bom，分组合并，暂时不相加

        QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
        designInformationQueryWrapper.in("peasant_household_id", ids);
        List<DesignInformation> li = designInformationMapper.selectList(designInformationQueryWrapper);
        DesignInformation designInformation = new DesignInformation();
        //组件
        List<Object> assembly = new ArrayList<>();
        //逆变器
        List<Object> inverter = new ArrayList<>();
        //电表箱
        List<Object> electricityMeter = new ArrayList<>();
        //电缆
        List<Object> cable = new ArrayList<>();
        for (DesignInformation des : li) {
            if (des.getAssembly() != null && !des.getAssembly().isEmpty()) {
                assembly.addAll(des.getAssembly());
            }
            if (des.getInverter() != null && !des.getInverter().isEmpty()) {
                inverter.addAll(des.getInverter());
            }
            if (des.getElectricityMeter() != null && !des.getElectricityMeter().isEmpty()) {
                electricityMeter.addAll(des.getElectricityMeter());
            }
            if (des.getCable() != null && !des.getCable().isEmpty()) {
                cable.addAll(des.getCable());
            }
        }
        designInformation.setAssembly(assembly);
        designInformation.setInverter(inverter);
        designInformation.setElectricityMeter(electricityMeter);
        designInformation.setCable(cable);



        // 添加对发货单信息页面的特殊处理
        if ("发货单信息".equals(sheet.getSheetName())) {
            int startRowNum = 5;
            if (null != designInformation.getAssembly()){
                List<Map<String, Object>> maps = convertList(designInformation.getAssembly());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();

                // 假设表头内容如下：
                String headerOne = "组件";
                String[] headersNames = {"物联编码", "物料名称", "电池片规格", "功率", "类型", "边框", "总功率（W）", "单/双面", "配置数量（块）", "金额（元）"};
                String[] headers = {"wlbm", "wlmc", "dcpgg", "gl", "lx", "bk", "zgl", "dsm", "pzsl", "price"};

                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != designInformation.getInverter()){
                List<Map<String, Object>> maps = convertList(designInformation.getInverter());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();
                // 假设表头内容如下：
                String headerOne = "逆变器";
                String[] headersNames = {"物联编码", "物料名称", "功率", "系列", "相位", "配置数量（块）", "金额（元）"};
                String[] headers = {"wlbm", "wlmc", "gl", "xl", "xw", "pzsl", "price"};
                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
            if (null != designInformation.getElectricityMeter()){
                List<Map<String, Object>> maps = convertList(designInformation.getElectricityMeter());
                int headerRow = startRowNum +1 ; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();
                // 假设表头内容如下：
                String headerOne = "并网箱";
                String[] headersNames = {"物联编码", "物料名称","材质",  "功率", "类型", "功能", "相位", "上网模式", "配置数量", "金额（元）"};
                String[] headers = {"wlbm", "wlmc","cz",  "gl", "lx", "gn", "xw", "swms","pzsl", "price"};

                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
            if (null != designInformation.getCable()){
                List<Map<String, Object>> maps = convertList(designInformation.getCable());
                int headerRow = startRowNum +1 ; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();

                // 假设表头内容如下：
                String headerOne = "电缆";
                String[] headersNames = {"物联编码", "物料名称", "型号", "规格", "配置数量（米）"};
                String[] headers = {"wlbm", "wlmc", "xh", "gg", "pzsl"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != preparationMoney.getHygfReplenishments()){
                List<Map<String, Object>> maps = convertList(preparationMoney.getHygfReplenishments());
                int headerRow = startRowNum +1 ; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();

                // 假设表头内容如下：
                String headerOne = "补货单";
                String[] headersNames = {"备注", "日期"};
                String[] headers = {"comment", "recDate"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != lih){
                List<Map<String, Object>> maps = convertList(lih);
                int headerRow = startRowNum +1 ; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();

                // 假设表头内容如下：
                String headerOne = "电站列表";
                String[] headersNames = {"农户编号", "业主姓名","经销商","项目地址","电站安装规模(kW)","电站实际规模(kW)"};
                String[] headers = {"peasantHouseholdNo", "ownersName","developerName","projectAddressName","scale","realScale"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

        }
    }

    private void fillSheet(Sheet sheet, Object data) {
        if (Objects.isNull(data)){
            return;
        }

        int startRow = 1;
        for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
            Row row = sheet.getRow(i);
            if (row != null && i >= startRow) {

                for (Cell cell : row) {
                    if (cell.getCellType() == CellType.STRING) {
                        String cellValue = cell.getStringCellValue();
                        String fieldName = removePlaceholders(cellValue);
                        setCellValue(cell, fieldName, data);
                    }
                }
            }
        }

        // 添加对设计信息页面的特殊处理
        if ("设计信息".equals(sheet.getSheetName())) {
            DesignInformationDto designInformation= (DesignInformationDto)data;
            int startRowNum = 5;
            if (null != designInformation.getAssembly()){
                List<Map<String, Object>> maps = convertList(designInformation.getAssembly());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();

                // 假设表头内容如下：
                String headerOne = "组件";
                String[] headersNames = {"物联编码", "物料名称", "电池片规格", "功率", "类型", "边框", "总功率（W）", "单/双面", "配置数量（块）", "金额（元）"};
                String[] headers = {"wlbm", "wlmc", "dcpgg", "gl", "lx", "bk", "zgl", "dsm", "pzsl", "price"};

                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != designInformation.getInverter()){
                List<Map<String, Object>> maps = convertList(designInformation.getInverter());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();
                // 假设表头内容如下：
                String headerOne = "逆变器";
                String[] headersNames = {"物联编码", "物料名称", "功率", "系列", "相位", "配置数量（块）", "金额（元）"};
                String[] headers = {"wlbm", "wlmc", "gl", "xl", "xw", "pzsl", "price"};
                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
            if (null != designInformation.getElectricityMeter()){
                List<Map<String, Object>> maps = convertList(designInformation.getElectricityMeter());
                int headerRow = startRowNum +1 ; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();
                // 假设表头内容如下：
                String headerOne = "并网箱";
                String[] headersNames = {"物联编码", "物料名称","材质",  "功率", "类型", "功能", "相位", "上网模式", "配置数量", "金额（元）"};
                String[] headers = {"wlbm", "wlmc","cz",  "gl", "lx", "gn", "xw", "swms","pzsl", "price"};

                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
            if (null != designInformation.getCable()){
                List<Map<String, Object>> maps = convertList(designInformation.getCable());
                int headerRow = startRowNum +1 ; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();

                // 假设表头内容如下：
                String headerOne = "电缆";
                String[] headersNames = {"物联编码", "物料名称", "型号", "规格", "配置数量（米）"};
                String[] headers = {"wlbm", "wlmc", "xh", "gg", "pzsl"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

        }

        // 添加对设计信息页面的特殊处理
        if ("工程信息".equals(sheet.getSheetName())) {
            PowerStationEngineeringInfo powerStationEngineeringInfo= (PowerStationEngineeringInfo)data;
            int startRowNum = 3;

            if (null != powerStationEngineeringInfo.getConstructionComponentInfo()){
                List<Map<String, Object>> maps = convertList(powerStationEngineeringInfo.getConstructionComponentInfo());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();

                // 假设表头内容如下：
                String headerOne = "组件序列号";
                String[] headersNames = {"序列号","功率","物联编码", "物料名称", "电池片规格",  "类型", "边框", "单/双面"};
                String[] headers = {"xlh","gl","wlbm", "wlmc", "dcpgg",  "lx", "bk",  "dsm"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != powerStationEngineeringInfo.getConstructionInverterInfo()){
                List<Map<String, Object>> maps = convertList(powerStationEngineeringInfo.getConstructionInverterInfo());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();
                // 假设表头内容如下：
                String headerOne = "逆变器序列号";
                String[] headersNames = {"序列号","验证码","功率","物联编码", "物料名称",  "系列", "相位"};
                String[] headers = {"xlh","yzm","gl", "wlbm", "wlmc", "xl", "xw"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
            if (null != powerStationEngineeringInfo.getConstructionGridBoxInfo()){
                List<Map<String, Object>> maps = convertList(powerStationEngineeringInfo.getConstructionGridBoxInfo());
                int headerRow = startRowNum +1 ; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();
                // 假设表头内容如下：
                String headerOne = "并网箱序列号";
                String[] headersNames = {"序列号", "功率","物联编码", "物料名称","材质",  "类型", "功能", "相位", "上网模式"};
                String[] headers = {"xlh","gl","wlbm", "wlmc","cz","lx", "gn", "xw", "swms"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
            if (null != powerStationEngineeringInfo.getConstructionCollectorBoxInfo()){
                List<Map<String, Object>> maps = convertList(powerStationEngineeringInfo.getConstructionCollectorBoxInfo());
                int headerRow = startRowNum +1 ; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +2+maps.size();

                // 假设表头内容如下：
                String headerOne = "采集器序列号";
                String[] headersNames = {"序列号"};
                String[] headers = {"xlh"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

        }

        // 添加对设计信息页面的特殊处理
        if ("扩展信息".equals(sheet.getSheetName())) {
            ExtendedInformationDto extendedInformationDto= (ExtendedInformationDto)data;
            int startRowNum = 3;

            if (null != extendedInformationDto.getContacts()){
                List<Map<String, Object>> maps = convertList(extendedInformationDto.getContacts());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "联系人";
                String[] headersNames = {"姓名","关系","联系电话", "电子邮箱", "QQ",  "微信"};
                String[] headers = {"userName","relation","telephone", "mailbox", "dcpgg",  "qq", "wechat"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
        }

        if ("施工信息".equals(sheet.getSheetName())) {
            PowerStationConstructionData powerStationConstructionData= (PowerStationConstructionData)data;
            int startRowNum = 3;

            if (null != powerStationConstructionData.getAreaOrders()){
                List<Map<String, Object>> maps = convertListToMap(powerStationConstructionData.getAreaOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "片区运营整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};




                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != powerStationConstructionData.getEngineeringOrders()){
                List<Map<String, Object>> maps = convertListToMap(powerStationConstructionData.getEngineeringOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "工程整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != powerStationConstructionData.getDesignOrders()){
                List<Map<String, Object>> maps = convertListToMap(powerStationConstructionData.getDesignOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "设计整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
        }

        // 添加对设计信息页面的特殊处理
        if ("并网信息".equals(sheet.getSheetName())) {
            HygfOnGrid hygfOnGrid= (HygfOnGrid)data;
            int startRowNum = 3;

            if (null != hygfOnGrid.getAreaOrders()){
                List<Map<String, Object>> maps = convertListToMap(hygfOnGrid.getAreaOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "片区运营整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};




                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != hygfOnGrid.getEngineeringOrders()){
                List<Map<String, Object>> maps = convertListToMap(hygfOnGrid.getEngineeringOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "工程整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != hygfOnGrid.getDesignOrders()){
                List<Map<String, Object>> maps = convertListToMap(hygfOnGrid.getDesignOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "设计整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
        }

        if ("验收信息".equals(sheet.getSheetName())) {
            AcceptanceCheck acceptanceCheck= (AcceptanceCheck)data;
            int startRowNum = 3;

            if (null != acceptanceCheck.getAreaOrders()){
                List<Map<String, Object>> maps = convertListToMap(acceptanceCheck.getAreaOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "片区运营整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};




                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != acceptanceCheck.getFinanceOrders()){
                List<Map<String, Object>> maps = convertListToMap(acceptanceCheck.getFinanceOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "投融整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }

            if (null != acceptanceCheck.getLegalOrders()){
                List<Map<String, Object>> maps = convertListToMap(acceptanceCheck.getLegalOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "法务整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
            if (null != acceptanceCheck.getPropertyOrders()){
                List<Map<String, Object>> maps = convertListToMap(acceptanceCheck.getPropertyOrders());
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1+maps.size();

                // 假设表头内容如下：
                String headerOne = "资产整改单";
                String[] headersNames = {"整改信息","整改结果","审核结果", "审核意见", "历史审核意见"};
                String[] headers = {"rectificationIdeas","rectificationResultWeb",  "auditResult",  "auditIdea", "rectificationHistoryWeb"};


                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne,maps);
            }
        }
        if (sheet.getSheetName().contains("审核日志")) {
            int startRowNum = 1;

            if (null !=data){
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1;

                // 假设表头内容如下：
                String headerOne = "审核日志";
                String[] headersNames = {"审核节点","审核人","审核时间", "审核状态", "审核意见"};
                String[] headers = {"taskName","operator",  "operateDate",  "approvalStatue", "approvalSuggestion"};
                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne, (List<Map<String, Object>>) data);
            }
        }

        if (sheet.getSheetName().contains("发货操作流水")) {
            int startRowNum = 1;

            if (null !=data){
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1;

//                if ((data ){
                    // 假设表头内容如下：
                    String headerOne = "发货操作流水";
                    String[] headersNames = {"审核节点","审核人","审核时间", "审核状态", "审核意见"};
                    String[] headers = {"taskName","operator",  "operateDate",  "approvalStatue", "approvalSuggestion"};
                    documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne, (List<Map<String, Object>>) data);

//                }else {
//
//
//                }
                           }
        }

        if (sheet.getSheetName().contains("审核记录")) {
            int startRowNum = 1;
            if (null !=data){
                int headerRow = startRowNum + 1; // 表头所在的行
                int headerOneRow = startRowNum; // 表头所在的行
                int dataStartRow = startRowNum+2; // 数据开始的行
                startRowNum= dataStartRow +1;

                // 假设表头内容如下：
                String headerOne = "操作记录";
                String[] headersNames = {"操作人","操作内容","操作时间", "备注",};
                String[] headers = {"operator", "operationContent",  "operationTime", "notes"};
                List<Map<String, Object>> maps = convertListToMap((List<?>) data);
                documentSpecialProcessing(sheet,headerRow,headerOneRow,dataStartRow,headersNames,headers,headerOne, maps);
            }
        }
        autoSizeColumns(sheet);
    }

    private String removePlaceholders(String fieldValue) {
        return fieldValue.replaceAll("[{}]", "");
    }

    private void setCellValue(Cell cell, String fieldName, Object data) {
        if (data instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, String> dataMap = (Map<String, String>) data;
            if (dataMap.containsKey(fieldName)) {
                cell.setCellValue(dataMap.get(fieldName));
            } else {
                cell.setCellValue("");
            }
        } else if (data instanceof List) {
            @SuppressWarnings("unchecked")
            List<Map<String, String>> dataList = (List<Map<String, String>>) data;
            int rowIndex = cell.getRowIndex();
            if (rowIndex >= 0 && rowIndex < dataList.size()) {
                Map<String, String> rowData = dataList.get(rowIndex);
                if (rowData.containsKey(fieldName)) {
                    cell.setCellValue(rowData.get(fieldName));
                } else {
                    cell.setCellValue("");
                }
            } else {
                cell.setCellValue("");
            }
        } else {
            try {
                Field field = data.getClass().getDeclaredField(fieldName);
                field.setAccessible(true); // 设置为可访问私有字段
                Object value = field.get(data);
                if (value != null) {
                    if (value instanceof List){
                        cell.setCellValue(CommonEnum.getNameByCodeList((List<String>) value));
                    }else if (value instanceof Date){
                        String s = DateUtils.date2LongStr((Date) value);
                        cell.setCellValue(s);
                    } else {
                        cell.setCellValue(CommonEnum.getNameByCode(value.toString()));
                    }
                } else {
                    cell.setCellValue("");
                }
            } catch (NoSuchFieldException | IllegalAccessException e) {
                cell.setCellValue("");
            }
        }
    }

    public static void downloadAndZipImages(Object obj,String fileName, Path tempDir,String urlPath) throws IOException {
        if (ObjectUtils.isEmpty(obj)){
            return;
        }
        Path baseInfoPath = tempDir.resolve(fileName);
        try {
            Files.createDirectories(baseInfoPath);
            System.out.println("Base info directory created at: " + baseInfoPath);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        if (fileName.contains("整改单附件")){
            List<String> strings = extractUrls((List<?>) obj, urlPath);
            for (String imageUrl : strings) {
                downloadAndSaveImage(imageUrl, baseInfoPath);
            }
        }else {
            List<Field> listFields = getAllListFields(obj.getClass());
            for (Field field : listFields) {
                try {
                    @SuppressWarnings("unchecked")
                    List<Object> list = (List<Object>) FieldUtils.readField(field, obj, true); // 读取字段值
                    if(CollectionUtil.isNotEmpty(list)){
                        for (Object item : list) {
                            if (item instanceof Map) {
                                Map<String, Object> map = (Map<String, Object>) item;
                                if (map.containsKey("url") && map.get("url") instanceof String) {
                                    String imageUrl = urlPath+(String) map.get("url");
                                    downloadAndSaveImage(imageUrl, baseInfoPath);
                                }
                            }
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }


    }


    private static void downloadAndSaveImage(String imageUrl, Path savePath) {
        try (InputStream in = new URL(imageUrl).openStream()) {
            String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
            Path imagePath = savePath.resolve(fileName);
            FileUtils.copyInputStreamToFile(in, imagePath.toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private  void createZipFile(Path folderPath, String zipFilePath, HttpServletResponse response) {
        try (ServletOutputStream out = response.getOutputStream();
             ZipOutputStream zos = new ZipOutputStream(out)) {
            // 计算ZIP文件的总大小
            long totalSize = getTotalFileSize(folderPath);
            double totalNum = (double) (totalSize/1024/1024);
            if (totalNum > 500 ){
                this.cleanup(folderPath);
                response.setHeader("content-error", URLEncoder.encode("所选文件总大小不得超过500M,当前所选文件总大小为"+totalNum+"M", "UTF-8"));
                response.setContentType("text/plain");
                throw new BadRequest("所选文件总大小不得超过500M,当前所选文件总大小为"+totalNum+"M");
            }
            //       response.setContentLengthLong((int) totalSize);
            addFolderToZip(zipFilePath, folderPath, zos,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void addFilesToZip(File sourceFile, ZipOutputStream zipOut, String baseFolder) throws IOException {
        if (sourceFile.isDirectory()) {
            File[] files = sourceFile.listFiles();
            for (File file : files) {
                addFilesToZip(file, zipOut, baseFolder);
            }
        } else {
            FileInputStream fin = new FileInputStream(sourceFile);
            String zipEntryName = sourceFile.getPath().substring(baseFolder.length() + 1).replace("\\", "/");
            zipOut.putNextEntry(new ZipEntry(zipEntryName));

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fin.read(buffer)) >= 0) {
                zipOut.write(buffer, 0, length);
            }
            zipOut.closeEntry();
            fin.close();
        }
    }

    private static long getTotalFileSize(Path folderPath) throws IOException {
        // 获取文件夹内所有文件的总大小
        return Files.walk(folderPath)
                .filter(Files::isRegularFile)
                .mapToLong(path -> {
                    try {
                        return Files.size(path);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return 0;
                    }
                })
                .sum();
    }
    private static void addFolderToZip(String relativePath, Path folderPath, ZipOutputStream zos, HttpServletResponse response) throws IOException {

        try {
//            FileOutputStream fout = new FileOutputStream(relativePath);
            File folder = new File(relativePath);

            addFilesToZip(folder, zos, folder.getName());

            zos.close();
//            fout.close();
            System.out.println("ZIP file created successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }

//        Files.walk(folderPath).forEach(filePath -> {
//            try {
//
//                String entryName = relativePath + folderPath.relativize(filePath).toString();
//                ZipEntry zipEntry = new ZipEntry(entryName);
//                zos.putNextEntry(zipEntry);
//
//                try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
//                    IOUtils.copy(fis, zos);
//                }
//
//                zos.closeEntry();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        });
    }

//@Async
//void cleanup(Path tempDir) {
//        try {
//            Files.walk(tempDir).sorted(Comparator.reverseOrder()).forEach(path -> {
//                try {
//                    Files.delete(path);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            });
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    private static String extractFileNameFromUrl(String url) {
//        String fileName = url.substring(url.lastIndexOf('/') + 1);
//        return fileName;
//    }




    public static List<String> extractUrls(  List<?>list,String urlPath) {
        List<String> urls = new ArrayList<>();

        for (Object obj : list) {
            // 获取所有类型为List<Object>的字段
            List<Field> listFields = getAllListFields(obj.getClass());

            for (Field field : listFields) {
                try {
                    @SuppressWarnings("unchecked")
                    List<Object> urlList = (List<Object>) FieldUtils.readField(field, obj, true);
                    if (CollectionUtil.isNotEmpty(urlList)){
                        // 从List<Object>中提取url值
                        for (Object item : urlList) {
                            if (item instanceof Map) {
                                Map<String, Object> map = (Map<String, Object>) item;
                                if (map.containsKey("url") && map.get("url") instanceof String) {
                                    urls.add(urlPath+(String) map.get("url"));
                                }
                            }
                        }
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }


        return urls;
    }


//
//    public static List<String> extractUrls(SurveyInformationDto surveyInfo) {
//        List<String> urls = new ArrayList<>();
//
//        // 获取所有类型为List<Object>的字段
//        List<Field> listFields = getAllListFields(surveyInfo.getClass());
//
//        for (Field field : listFields) {
//            try {
//                @SuppressWarnings("unchecked")
//                List<Object> list = (List<Object>) FieldUtils.readField(field, surveyInfo, true);
//
//                // 从List<Object>中提取url值
//                for (Object item : list) {
//                    if (item instanceof Map) {
//                        Map<String, Object> map = (Map<String, Object>) item;
//                        if (map.containsKey("url") && map.get("url") instanceof String) {
//                            urls.add("http://47.92.234.253:8088"+(String) map.get("url"));
//                        }
//                    }
//                }
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            }
//        }
//
//        return urls;
//    }


    private static List<Field> getAllListFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        Class<?> currentClass = clazz;

        while (currentClass != null) {
            for (Field field : currentClass.getDeclaredFields()) {
                if (List.class.isAssignableFrom(field.getType())) {
                    fields.add(field);
                }
            }
            currentClass = currentClass.getSuperclass();
        }

        return fields;
    }

    void documentSpecialProcessing (Sheet sheet, int headerRow,int headerOneRow,int dataStartRow, String[] headersNames, String[] headers, String headerOne,  List<Map<String, Object>> data){
        // 创建表头样式
        CellStyle headerStyle = sheet.getWorkbook().createCellStyle();
        Font headerFont = sheet.getWorkbook().createFont();

        headerFont.setBold(true); // 加粗字体
        headerFont.setFontHeightInPoints((short) 12); // 字体大小
        headerStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headerStyle.setAlignment(HorizontalAlignment.CENTER); // 居中对齐
        headerStyle.setFont(headerFont); // 设置字体样式

        // 设置边框
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);

        // 写入表头
        Row headerRowObjectOne = sheet.getRow(headerOneRow);
        if (headerRowObjectOne == null) {
            headerRowObjectOne = sheet.createRow(headerOneRow);
            Cell cell = headerRowObjectOne.getCell(0);
            if (cell == null) {
                cell = headerRowObjectOne.createCell(0);
            }
            cell.setCellValue(headerOne);
            cell.setCellStyle(headerStyle);
        }

        // 写入表头
        Row headerRowObject = sheet.getRow(headerRow);
        if (headerRowObject == null) {
            headerRowObject = sheet.createRow(headerRow);
        }
        for (int i = 0; i < headersNames.length; i++) {
            Cell headerCell = headerRowObject.getCell(i);
            if (headerCell == null) {
                headerCell = headerRowObject.createCell(i);
            }
            headerCell.setCellValue(headersNames[i]);
            headerCell.setCellStyle(headerStyle);
        }


        // 从第四行开始填充数据
        for (int dataIndex = 0; dataIndex < data.size(); dataIndex++) {
            Row dataRow = sheet.createRow(dataStartRow + dataIndex);
            Map<String, Object> result = (Map<String, Object>) data.get(dataIndex);
            Map<String, Object> rowData = new HashMap<>();
            if (result.containsKey("map")){
                rowData = (Map<String, Object>)result.get("map");
            }else {
                rowData = result;
            }
            for (int i = 0; i < headersNames.length; i++) {
                Cell dataCell = dataRow.createCell(i);
                if (rowData.containsKey(headers[i])) {
                    Object value = rowData.get(headers[i]);
                    if (value instanceof List<?>) {
                        List<String> urls = (List<String>) value;
                        if (!urls.isEmpty()) {
                            try {
                                XSSFDrawing drawing = ((XSSFSheet) sheet).getDrawingPatriarch();
                                if (drawing == null) {
                                    drawing = ((XSSFSheet) sheet).createDrawingPatriarch();
                                }

                                // 设置单元格为空
                                dataCell.setCellStyle(sheet.getWorkbook().createCellStyle());
                                dataCell.setCellType(CellType.STRING);
                                dataCell.setCellValue("");

                                // 计算第一个图片的位置
                                int colWidth = 0;
                                int rowHeight = 0;
                                int pictureIdx = -1;

                                for (int j = 0; j < urls.size(); j++) {
                                    String url = urls.get(j);
                                    InputStream inputStream = new URL(url).openStream();
                                    pictureIdx = ((XSSFWorkbook) sheet.getWorkbook()).addPicture(inputStream, XSSFWorkbook.PICTURE_TYPE_JPEG);

                                    // 输出调试信息
                                    System.out.println("Picture index: " + pictureIdx);

                                    // 创建图片对象
                                    XSSFClientAnchor anchor = new XSSFClientAnchor(
                                            0, 0, 0, 0, (short) i, dataIndex + dataStartRow,
                                            (short) (i + colWidth / 100), dataIndex + dataStartRow + rowHeight / 100
                                    );

                                    Picture pict = drawing.createPicture(anchor, pictureIdx);
                                    pict.resize();

                                    // 计算图片的宽度和高度
                                    int picWidth = 100; // 图片宽度百分比
                                    int picHeight = 100; // 图片高度百分比
                                    colWidth += picWidth;
                                    rowHeight += picHeight;
                                }

                                // 检查是否需要合并单元格
                                if (colWidth > 100) {
                                    // 合并单元格
                                    sheet.addMergedRegion(new CellRangeAddress(dataIndex + dataStartRow, dataIndex + dataStartRow, i, i + (colWidth / 100) - 1));
                                }

                                // 调整单元格的宽度和高度
                                sheet.setColumnWidth(i, (colWidth * 256) / 100);
                                dataRow.setHeightInPoints(rowHeight);
                            } catch (Exception e) {
                                // 处理异常情况
                                System.err.println("Failed to download or insert images: " + value);
                                e.printStackTrace();
                            }
                        } else {
                            dataCell.setCellValue(""); // 假设所有数据都是字符串格式
                        }
                    } else if( value instanceof Date) {
                        String s = DateUtils.date2LongStr((Date) value);
                        dataCell.setCellValue(s);
                    }
                    else   {
                        dataCell.setCellValue(null == value?"":value.toString()); // 假设所有数据都是字符串格式
                    }
                } else {
                    dataCell.setCellValue(""); // 假设所有数据都是字符串格式
                }
            }
        }

//原始方法
//        for (int dataIndex = 0; dataIndex < data.size(); dataIndex++) {
//            Row dataRow = sheet.createRow(dataStartRow + dataIndex);
//            Map<String, Object> rowData = (Map<String, Object>) data.get(dataIndex).get("map");
//            for (int i = 0; i < headersNames.length; i++) {
//                Cell dataCell = dataRow.createCell(i);
//                if (rowData.containsKey(headers[i])){
//                    dataCell.setCellValue(rowData.get(headers[i]).toString()); // 假设所有数据都是字符串格式
//                }else {
//                    dataCell.setCellValue(""); // 假设所有数据都是字符串格式
//
//                }
//            }
//        }

    }
    @Async
    public  void cleanup(Path tempDir) {
        try (Stream<Path> paths = Files.walk(tempDir)) {
            List<Path> filesToDelete = paths.sorted(Comparator.reverseOrder())
                    .collect(Collectors.toList());

            // 分批删除文件
            int batchSize = 100; // 根据实际情况调整批次大小
            for (int i = 0; i < filesToDelete.size(); i += batchSize) {
                List<Path> batch = filesToDelete.subList(i, Math.min(i + batchSize, filesToDelete.size()));
                batch.forEach(file -> {
                    try {
                        Files.delete(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static List<Map<String, Object>> convertList(List<?> objectList) {
        List<Map<String, Object>> result = new ArrayList<>();

        for (Object obj : objectList) {
            if (obj != null) {
                Map<String, Object> map = new HashMap<>();
                getAllFields(obj, map);
                result.add(map);
            }
        }
        return result;
    }

    private static void getAllFields(Object obj, Map<String, Object> map) {
        Class<?> clazz = obj.getClass();
        while (clazz != null) {
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true); // 允许访问私有字段
                try {
                    map.put(field.getName(), field.get(obj));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    // 可以选择记录日志或抛出异常
                }
            }
            clazz = clazz.getSuperclass(); // 获取父类
        }
    }

    List<Map<String, Object>> convertListToMap(List<?> objects){
        List<Map<String, Object>> maps = new ArrayList<>();
        for (Object object : objects) {
            Map<String, Object> map = BeanUtil.beanToMap(object);
//            if (map.containsKey("rectificationFile")){
//                List<String> urls = new ArrayList<>();
//
//                List<Map<String, String>> rectificationFile = (List<Map<String, String>>) map.get("rectificationFile");
//                for (Map<String, String> stringStringMap : rectificationFile) {
//                    urls.add(stringStringMap.get("url"));
//                }
//                map.put("rectificationFileUrls",urls);
//            }
//            if (map.containsKey("resultFile")){
//                List<String> urls = new ArrayList<>();
//                List<Map<String, String>> resultFile = (List<Map<String, String>>) map.get("resultFile");
//                for (Map<String, String> stringStringMap : resultFile) {
//                    urls.add(stringStringMap.get("url"));
//                }
//                map.put("resultFileUrls",urls);
//            }
            if (map.containsKey("rectificationIdea")){
                List<String> urls = new ArrayList<>();
                List<Map<String, Object>> rectificationIdeas = (List<Map<String, Object>>) map.get("rectificationIdea");
                for (Map<String, Object> stringStringMap : rectificationIdeas) {
                    List<Map<String, String>> items = (List<Map<String, String>>) stringStringMap.get("items");
                    List<String> values = new ArrayList<>();
                    int startNum = 1;
                    if (CollectionUtil.isNotEmpty(items)){
                        for (Map<String, String> item : items) {
                            values.add(startNum++ +"."+item.get("value")+"。") ;
                        }
                        urls.add(stringStringMap.get("type")+":"+ String.join("",values));
                    }

                }
                map.put("rectificationIdeas",String.join(",",urls));
            }
            maps.add(map);
        }


        return maps;
    }

    private static <T> void addNonNullList(List<T> targetList, List<T> sourceList) {
        if (sourceList != null) {
            targetList.addAll(sourceList);
        }
    }

    List<LinkedHashMap>  getWorkLog (String processInstanceId){
        if (StringUtils.isEmpty(processInstanceId)) {
            return null;
        }
        List<LinkedHashMap> flowLoggernew = new ArrayList<>();
        try {
            Map<String, Object> flowLoggerMap = workflowFeignClient.getFlowLogger(processInstanceId).getResult();
            List<LinkedHashMap> flowLogger = (List<LinkedHashMap>) flowLoggerMap.get("flowLogger");
            if (flowLogger.size() > 0) {
                Collections.reverse(flowLogger);
            }
            for (LinkedHashMap linkedHashMap : flowLogger) {
                if (linkedHashMap.get("operateDate") != null
                        && !linkedHashMap.get("operateDate").toString().isEmpty()) {
                    LinkedHashMap linke = new LinkedHashMap();
                    linke.put("approvalStatue", linkedHashMap.get("approvalStatue").toString());
                    // 审核意见
                    List<LinkedHashMap> approvalSuggestion = (List<LinkedHashMap>) linkedHashMap
                            .get("approvalSuggestion");
                    if (approvalSuggestion != null && !approvalSuggestion.isEmpty()) {
                        linke.put("approvalSuggestion", approvalSuggestion.get(0).get("message"));
                    }
                    linke.put("taskName", linkedHashMap.get("taskName").toString());
                    linke.put("operator", linkedHashMap.get("operator").toString());
                    linke.put("operateDate", linkedHashMap.get("operateDate").toString());
                    flowLoggernew.add(linke);
                }
            }

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


    List<ConstructionRecords>    getConstructionRecords   (Long workOrderPowerStationId,Long workOrderId) {
        // 施工自审操作记录
        LambdaQueryWrapper<ConstructionRecords> up5 = new LambdaQueryWrapper<ConstructionRecords>();
        up5.eq(ConstructionRecords::getWorkOrderPowerStationId,workOrderPowerStationId);
        up5.eq(ConstructionRecords::getWorkOrderId,workOrderId);
        up5.orderByAsc(ConstructionRecords::getRecDate);
        return  constructionRecordsMapper.selectList(up5);
    }

    List<ConstructionGirdRecords>    getConstructionRecordsBasic   (String peasantHouseholdId) {
        // 施工自审操作记录
        LambdaQueryWrapper<ConstructionGirdRecords> up5 = new LambdaQueryWrapper<ConstructionGirdRecords>();
        up5.eq(ConstructionGirdRecords::getPeasantHouseholdId, peasantHouseholdId);
        up5.orderByAsc(ConstructionGirdRecords::getRecDate);
        return  constructionGirdRecordsMapper.selectList(up5);
    }


    List<ConstructionAcceptanceRecords>    getConstructionRecordsAcc   (String peasantHouseholdId) {
        // 施工自审操作记录
        LambdaQueryWrapper<ConstructionAcceptanceRecords> up5 = new LambdaQueryWrapper<ConstructionAcceptanceRecords>();
        up5.eq(ConstructionAcceptanceRecords::getPeasantHouseholdId, peasantHouseholdId);
        up5.orderByAsc(ConstructionAcceptanceRecords::getRecDate);
        return  constructionAcceptanceRecordsMapper.selectList(up5);
    }


    public Object getSchedule(String peasantHouseholdId) {
        if (!redisUtils.hasKey(peasantHouseholdId)){
            return null;
        }
        Map<String, Object> map = (Map<String, Object>) redisUtils.get(peasantHouseholdId);
        Integer value = (Integer) map.get("value");
        if(100-value ==0){
            redisUtils.del(peasantHouseholdId);
        }
        return map;
    }
}