package com.xdap.self_development.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xdap.motor.utils.StringUtils;
import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.controller.request.AnalysisRequest;
import com.xdap.self_development.controller.request.AnalysisVerRequest;
import com.xdap.self_development.controller.request.ModelComparisonExportRequest;
import com.xdap.self_development.controller.request.ModelItem;
import com.xdap.self_development.domain.pojo.*;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.DataEntryEngineModelService;
import com.xdap.self_development.service.EngineParamDetailService;
import com.xdap.self_development.service.TcDataQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.Collator;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * TC数据查询服务实现类
 *
 * @version 1.0
 * @since 2025
 */
@Service
@Slf4j
public class TcDataQueryServiceImpl implements TcDataQueryService {
    @Resource
    private BusinessDatabase bd;
    @Resource
    private EngineParamDetailService engineParamDetailService;
    @Resource
    private DataEntryEngineModelService engineModelService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private ObjectMapper objectMapper = new ObjectMapper();

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    /**
     * 根据部件名称查询所有TC数据
     *
     * @param analysisRequest 分析请求对象
     * @return 引擎参数详情映射
     */
    @Override
    public Map<String, List<EngineParamDetailPojo>> tcDataSelectAllByPartsName(AnalysisRequest analysisRequest) {
        return tcDataSelectAllByPartsNameFunctionOptimized(analysisRequest);

    }

    @Override
    /**
     * 根据部件名称查询所有TC数据（备份方法）
     *
     * @param analysisRequest 分析请求对象
     * @return 引擎参数详情映射
     */
    public Map<String, List<EngineParamDetailPojo>> tcDataSelectAllByPartsNameBack(AnalysisRequest analysisRequest) {
        return tcDataSelectAllByPartsNameFunction(analysisRequest);

    }

    public Map<String, List<EngineParamDetailPojo>> tcDataSelectAllByPartsNameFunction(AnalysisRequest analysisRequest) {
        String engineModelID = analysisRequest.getEngineModelID();

        List<String> subsystemTypes = analysisRequest.getSubsystemParts();
        if (ObjectUtils.isEmpty(engineModelID) || ObjectUtils.isEmpty(subsystemTypes)) {
            throw new CommonException("传入参数为空，请检查");
        }
        List<EngineParamDetailPojo> allPojos = new ArrayList<>();
        List<ParameterPojo> parameters = engineParamDetailService.selectAllAndTcByNewVersion();
        DataEntryEngineModelPojo dataEntryEngineModelPojo = engineModelService.selectBymodelId(engineModelID);
        //查到所有TC表的参数 返回零部件，参数列表
        for (String subsystemType : subsystemTypes) {
            if (subsystemType.split("-").length != 2) {
                throw new CommonException("查询条件异常,需子系统-零部件名称,若零部件为空则传入“/”");
            }
            String subsystem = subsystemType.split("-")[0];
            String partsName = subsystemType.split("-")[1];
            //开始查找系统数据
            List<EngineParamDetailPojo> pojoList = bd.getBusinessDatabase()
                    .eq("engine_model_id", dataEntryEngineModelPojo.getId())
                    .eq("major_version", dataEntryEngineModelPojo.getVersionNumber())
                    .eq("subsystem_name", subsystem)
                    .eq("parts_name", partsName)
                    .doQuery(EngineParamDetailPojo.class);

            pojoList = pojoList.stream()
                    .filter(x -> x.getMajorVersion()
                            .equals(dataEntryEngineModelPojo.getVersionNumber())).collect(Collectors.toList());

            if (ObjectUtils.isNotEmpty(pojoList)) {
                allPojos.addAll(pojoList);
            }

            //使用selectTCFromDB查询TC数据
            List<String> tcSubsystemParts = new ArrayList<>();
            tcSubsystemParts.add(subsystem + "-" + partsName);
            List<EngineParamDetailPojo> tcPojos = selectTCFromDB(engineModelID, tcSubsystemParts);

            //处理TC数据，转换为EngineParamDetailPojo
            for (EngineParamDetailPojo tcPojo : tcPojos) {
                String paramName = tcPojo.getParameterName();
                String paramValue = tcPojo.getParameterValue();
                List<EngineParamDetailPojo> matchedPojos = parameters.stream()
                        .filter(x -> (x.getPartsName() + "&&" + x.getParameterName()).equals(partsName + "&&" + paramName))
                        .map(x -> {
                            EngineParamDetailPojo engineParamDetailPojo = new EngineParamDetailPojo();
                            engineParamDetailPojo.setEngineModelId(dataEntryEngineModelPojo.getId());
                            engineParamDetailPojo.setPartsName(x.getPartsName());
                            engineParamDetailPojo.setSubsystemName(x.getSubsystemName());
                            engineParamDetailPojo.setParameterName(x.getParameterName());
                            engineParamDetailPojo.setParameterValue(paramValue);
                            return engineParamDetailPojo;
                        }).collect(Collectors.toList());
                if (ObjectUtils.isNotEmpty(matchedPojos)) {
                    allPojos.addAll(matchedPojos);
                }
            }

        }
        return allPojos.stream().collect(Collectors.groupingBy(EngineParamDetailPojo::getSubsystemName));
    }


    public Map<String, List<EngineParamDetailPojo>> tcDataSelectAllByPartsNameFunctionOptimized(AnalysisRequest analysisRequest) {
        String engineModelID = analysisRequest.getEngineModelID();
        List<String> subsystemTypes = analysisRequest.getSubsystemParts();
        String userID = analysisRequest.getUserID();

        if (ObjectUtils.isEmpty(engineModelID) || ObjectUtils.isEmpty(subsystemTypes) || ObjectUtils.isEmpty(userID)) {
            throw new CommonException("传入参数部分为空，请检查");
        }


        List<EngineParamDetailPojo> allPojos = new ArrayList<>();
        List<ParameterPojo> parameters = engineParamDetailService.selectAllAndTcByNewVersion();
        DataEntryEngineModelPojo dataEntryEngineModelPojo = engineModelService.selectBymodelId(engineModelID);

        // 预加载所有参数信息
        Map<String, List<ParameterPojo>> parameterMap = parameters.stream()
                .collect(Collectors.groupingBy(p -> p.getPartsName() + "&&" + p.getParameterName()));

        //解析所有子系统-零部件对
        List<Map.Entry<String, String>> subsystemPartsPairs = subsystemTypes.stream()
                .map(subsystemType -> {
                    if (subsystemType.split("-").length != 2) {
                        throw new CommonException("查询条件异常,需子系统-零部件名称,若零部件为空则传入“/ ”");
                    }
                    String subsystem = subsystemType.split("-")[0];
                    String partsName = subsystemType.split("-")[1];
                    return new AbstractMap.SimpleEntry<>(subsystem, partsName);
                })
                .collect(Collectors.toList());

        //批量查询所有系统数据
        List<EngineParamDetailPojo> systemDataList = new ArrayList<>();
        for (Map.Entry<String, String> subsystemPartsPair : subsystemPartsPairs) {
            List<EngineParamDetailPojo> pojoList = bd.getBusinessDatabase()
                    .eq("engine_model_id", dataEntryEngineModelPojo.getId())
                    .eq("major_version", dataEntryEngineModelPojo.getVersionNumber())
                    .eq("subsystem_name", subsystemPartsPair.getKey())
                    .eq("parts_name", subsystemPartsPair.getValue())
                    .doQuery(EngineParamDetailPojo.class);
            if (ObjectUtils.isNotEmpty(pojoList)) {
                systemDataList.addAll(pojoList);
            }
        }

        // 过滤版本号
        List<EngineParamDetailPojo> filteredSystemData = systemDataList.stream()
                .filter(x -> x.getMajorVersion().equals(dataEntryEngineModelPojo.getVersionNumber()))
                .collect(Collectors.toList());

        allPojos.addAll(filteredSystemData);

        //使用selectTCFromDB批量查询TC数据
        List<EngineParamDetailPojo> tcDataPojos = selectTCFromDB(engineModelID, subsystemTypes);

        //处理TC数据，转换为EngineParamDetailPojo
        List<EngineParamDetailPojo> convertedTcPojos = tcDataPojos.stream()
                .filter(tcPojo -> parameterMap.containsKey(tcPojo.getPartsName() + "&&" + tcPojo.getParameterName()))
                .map(tcPojo -> {
                    ParameterPojo param = parameterMap.get(tcPojo.getPartsName() + "&&" + tcPojo.getParameterName()).get(0);
                    EngineParamDetailPojo pojo = new EngineParamDetailPojo();
                    pojo.setEngineModelId(dataEntryEngineModelPojo.getId());
                    pojo.setPartsName(param.getPartsName());
                    pojo.setSubsystemName(param.getSubsystemName());
                    pojo.setParameterName(param.getParameterName());
                    pojo.setParameterValue(tcPojo.getParameterValue());
                    return pojo;
                })
                .collect(Collectors.toList());

        allPojos.addAll(convertedTcPojos);
        //将allPojos存到Redis,KEY为userID+engineModelID+预操作，过期时间24小时
        try {
            String redisKey = userID + ":" + engineModelID + ":" + "ComparisonExport";
            String jsonValue = objectMapper.writeValueAsString(allPojos);

            redisTemplate.opsForValue().set(redisKey, jsonValue, 24, java.util.concurrent.TimeUnit.HOURS);
            log.info("成功将数据存储到Redis，KEY: {}", redisKey);
        } catch (Exception e) {
            log.error("存储数据到Redis失败: {}", e.getMessage());
            throw new CommonException("存储数据到Redis失败：" + e.getMessage());
        }


        return allPojos.stream().collect(Collectors.groupingBy(EngineParamDetailPojo::getSubsystemName));
    }

    @Override
    /**
     * 导出Excel A格式
     *
     * @param response HTTP响应对象
     */
    public void excelExportA(HttpServletResponse response) {
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build()) {
            setupResponse(response, "参数值导入模板" + (new Date()));
            ArrayList<EnginePartsCollectionPojo> enginePartsCollections = new ArrayList<>();
            List<EnginePartsCollectionPojo> lbjmcs = new ArrayList<>();
            for (EnginePartsCollectionPojo parameter : lbjmcs) {
                EnginePartsCollectionPojo engineParamDetailExcel = new EnginePartsCollectionPojo();
                engineParamDetailExcel.setZtj(parameter.getZtj());
                engineParamDetailExcel.setLbjth(parameter.getLbjth());
                engineParamDetailExcel.setLbjmc(parameter.getLbjmc());
                enginePartsCollections.add(engineParamDetailExcel);
            }
            WriteSheet sheet = EasyExcel.writerSheet()
                    .head(EnginePartsCollectionPojo.class)  // 所有Sheet使用相同的表头
                    .build();
            excelWriter.write(enginePartsCollections, sheet); // 写入数据，只生成表头
        } catch (Exception e) {
            throw new CommonException("导出Excel文件异常");
        }
    }

    @Override
    /**
     * 导出Excel B格式
     *
     * @param response HTTP响应对象
     */
    public void excelExportB(HttpServletResponse response) {
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build()) {
            ArrayList<ClassificationAttributePojo> enginePartsCollections = new ArrayList<>();
            List<ClassificationAttributePojo> lbjmcs = new ArrayList<>();
            for (ClassificationAttributePojo parameter : lbjmcs) {
                ClassificationAttributePojo engineParamDetailExcel = new ClassificationAttributePojo();
                engineParamDetailExcel.setFieldvalue(parameter.getFieldvalue());
                engineParamDetailExcel.setIdattrtbutehame(parameter.getIdattrtbutehame());
                engineParamDetailExcel.setPitemId(parameter.getPitemId());
                enginePartsCollections.add(engineParamDetailExcel);
            }
            WriteSheet sheet = EasyExcel.writerSheet()
                    .head(ClassificationAttributePojo.class)  // 所有Sheet使用相同的表头
                    .build();
            excelWriter.write(enginePartsCollections, sheet); // 写入数据，只生成表头
        } catch (Exception e) {
            throw new CommonException("导出Excel文件异常");
        }
    }

    @Override
    /**
     * 模型对比导出
     *
     * @param request 模型对比导出请求对象
     * @param response HTTP响应对象
     */
    public void modelComparisonExport(ModelComparisonExportRequest request, HttpServletResponse response) {
        List<ModelItem> models = request.getModelIds();
        String userID = request.getUserID();
        List<String> subsystemParts = request.getSubsystemParts();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

        if (models == null || models.isEmpty()) {
            log.error("导出失败：机型列表为null或空");
            throw new CommonException("导出失败：机型列表不能为空");
        }
        if (StringUtils.isEmpty(userID)) {
            log.error("导出失败：用户ID为空");
            throw new CommonException("导出失败：用户ID不能为空");
        }
        if (subsystemParts == null || subsystemParts.isEmpty()) {
            log.error("导出失败：子系统部件列表为null或空");
            throw new CommonException("导出失败：子系统部件列表不能为空");
        }
        if (response == null) {
            log.error("导出失败：响应对象为null");
            throw new CommonException("导出失败：响应对象异常");
        }

        try {
            setupExcelResponse(response, "机型参数对比表" + formatter.format(LocalDateTime.now()) + ".xlsx");

            // 获取机型名称映射
            Map<String, String> modelNames = getModelNameMapping(models);

            // 从Redis加载并处理数据
            Map<String, Map<String, String>> parameterValues = new TreeMap<>(Collator.getInstance(Locale.CHINA));

            loadAndProcessRedisData(request, models, userID, subsystemParts, parameterValues);

            // 构建表头和数据
            List<List<String>> excelData = buildExcelData(models, parameterValues);

            // 写入
            try (OutputStream outputStream = response.getOutputStream()) {
                EasyExcel.write(outputStream)
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .sheet("机型参数对比")
                        .head(getCustomHeader(models, modelNames)) // 自定义表头
                        .doWrite(excelData);
            }

            log.info("机型参数对比表导出成功，共导出{}行数据（含表头）", excelData.size());

        } catch (Exception e) {
            String errorMsg = "导出失败: " + e.getMessage();
            log.error(errorMsg, e);
            throw new CommonException(errorMsg, e);
        }
    }

    @Override
    /**
     * 根据版本查询TC数据（优化版）
     *
     * @param analysisRequest 版本分析请求对象
     * @return 引擎参数详情映射
     */
    public Map<String, List<EngineParamDetailPojo>> tcDataSelectByVersion(AnalysisVerRequest analysisRequest) {
        long startTime = System.currentTimeMillis();
        log.info("开始执行tcDataSelectByVersion查询");
        
        DataEntryEngineModelPojo dataEntryEngineModelPojo = engineModelService.selectBymodelId(analysisRequest.getEngineModelID());
        if (dataEntryEngineModelPojo == null) {
            throw new CommonException("查询失败：机型不存在");
        }

        //解析所有子系统-零部件对
        Set<String> subsystemSet = new HashSet<>();
        Set<String> partsNameSet = new HashSet<>();
        analysisRequest.getSubsystemParts().forEach(subsystemType -> {
            if (subsystemType.split("-").length != 2) {
                throw new CommonException("查询条件异常,需子系统-零部件名称,若零部件为空则传入“/”");
            }
            String subsystem = subsystemType.split("-")[0];
            String partsName = subsystemType.split("-")[1];
            subsystemSet.add(subsystem);
            partsNameSet.add(partsName);
        });

        //批量查询所有系统数据（优化：一次查询，内存过滤）
        long queryStartTime = System.currentTimeMillis();
        List<EngineParamDetailPojo> allParamList = bd.getBusinessDatabase()
                .eq("engine_model_id", analysisRequest.getEngineModelID())
                .eq("major_version", analysisRequest.getParameterVersion())
                .in("subsystem_name", subsystemSet)
                .in("parts_name", partsNameSet)
                .doQuery(EngineParamDetailPojo.class);
        log.info("查询所有参数数据耗时: {}ms, 数据量: {}", System.currentTimeMillis() - queryStartTime, allParamList.size());
        
        List<EngineParamDetailPojo> systemDataList = allParamList.stream()
                .filter(p -> !"TC分类表".equals(p.getParameterSource()))
                .collect(Collectors.toList());
        
        List<EngineParamDetailPojo> tcPojos = allParamList.stream()
                .filter(p -> "TC分类表".equals(p.getParameterSource()))
                .collect(Collectors.toList());
        
        // 批量查询所有系统数据（优化前代码 - 已屏蔽）
//        List<EngineParamDetailPojo> systemDataList = new ArrayList<>(
//                bd.getBusinessDatabase()
//                        .eq("engine_model_id", analysisRequest.getEngineModelID())
//                        .eq("major_version", analysisRequest.getParameterVersion())
//                        .in("subsystem_name", subsystemSet)
//                        .in("parts_name", partsNameSet)
//                        .ne("parameter_source", "TC分类表")
//                        .doQuery(EngineParamDetailPojo.class)
//        );
//        List<EngineParamDetailPojo> tcPojos = new ArrayList<>(
//                bd.getBusinessDatabase()
//                        .eq("engine_model_id", analysisRequest.getEngineModelID())
//                        .eq("major_version", analysisRequest.getParameterVersion())
//                        .in("subsystem_name", subsystemSet)
//                        .in("parts_name", partsNameSet)
//                        .eq("parameter_source", "TC分类表")
//                        .doQuery(EngineParamDetailPojo.class)
//        );

        //批量查询所有TC数据
        Map<String, List<EngineParamDetailPojo>> parameterMapTc = tcPojos.stream()
                .collect(Collectors.groupingBy(p -> p.getPartsName() + "&&" + p.getParameterName()));

        //使用selectTCFromDB查询TC数据
        List<EngineParamDetailPojo> tcDataResults = selectTCFromDB(analysisRequest.getEngineModelID(), analysisRequest.getSubsystemParts());

        //处理TC数据，更新parameterValue
        List<EngineParamDetailPojo> convertedTcPojos = tcDataResults.stream()
                .filter(tcPojo -> parameterMapTc.containsKey(tcPojo.getPartsName() + "&&" + tcPojo.getParameterName()))
                .map(tcPojo -> {
                    EngineParamDetailPojo param = parameterMapTc.get(tcPojo.getPartsName() + "&&" + tcPojo.getParameterName()).get(0);
                    param.setParameterValue(tcPojo.getParameterValue());
                    return param;
                })
                .collect(Collectors.toList());

        systemDataList.addAll(convertedTcPojos);

        // 按权限过滤返回数据
        long authStartTime = System.currentTimeMillis();
        List<EngineParamDetailPojo> filerData = engineParamDetailService.selectModelParamByIsUserId(systemDataList, analysisRequest.getUserID());
        log.info("权限过滤耗时: {}ms, 过滤后数据量: {}", System.currentTimeMillis() - authStartTime, filerData.size());

        //将allPojos存到Redis（异步执行，不阻塞主流程）
        String redisKey = analysisRequest.getUserID() + ":" + analysisRequest.getEngineModelID() + ":" + analysisRequest.getParameterVersion() + ":" + "ComparisonExport";
        java.util.concurrent.CompletableFuture.runAsync(() -> {
            try {
                String jsonValue = objectMapper.writeValueAsString(filerData);
                redisTemplate.opsForValue().set(redisKey, jsonValue, 24, java.util.concurrent.TimeUnit.HOURS);
                log.info("异步存储数据到Redis成功，KEY: {}", redisKey);
            } catch (Exception e) {
                log.error("异步存储数据到Redis失败: {}", e.getMessage());
            }
        });
        
        // 将allPojos存到Redis（优化前代码 - 已屏蔽）
//        try {
//            String redisKey = analysisRequest.getUserID() + ":" + analysisRequest.getEngineModelID() + ":" + analysisRequest.getParameterVersion() + ":" + "ComparisonExport";
//            String jsonValue = objectMapper.writeValueAsString(filerData);
//            redisTemplate.opsForValue().set(redisKey, jsonValue, 24, java.util.concurrent.TimeUnit.HOURS);
//            log.info("成功将数据存储到Redis，KEY: {}", redisKey);
//        } catch (Exception e) {
//            log.error("存储数据到Redis失败: {}", e.getMessage());
//        }

        log.info("tcDataSelectByVersion总耗时: {}ms", System.currentTimeMillis() - startTime);
        return filerData.stream().collect(Collectors.groupingBy(EngineParamDetailPojo::getSubsystemName));
    }

    @Override
    /**
     * 批量根据产品编号查询所有TC数据
     *
     * @param engineModelPojos 引擎模型对象列表
     * @return 引擎参数详情列表
     */
    public List<EngineParamDetailPojo> tcDataSelectAllByproductNumberBatch(List<DataEntryEngineModelPojo> engineModelPojos) {
        // 一次性查询所有参数模板 TC 参数数据
        List<ParameterPojo> parameters = engineParamDetailService.selectAllAndTcByNewVersion();
        List<ParameterPojo> collect = parameters.stream()
                .filter(x -> "TC分类表".equals(x.getParameterSource()))
                .collect(Collectors.toList());

        if (collect.isEmpty()) {
            return Collections.emptyList();
        }

        // 按 partsName 分组
        Map<String, List<ParameterPojo>> stringListMap = collect.stream()
                .collect(Collectors.groupingBy(ParameterPojo::getPartsName));

        Set<String> partsNames = stringListMap.keySet();
        // 预处理参数名集合
        Map<String, Set<String>> partsParamNameMap = new HashMap<>(partsNames.size());
        for (String partsName : partsNames) {
            List<ParameterPojo> parameterList = stringListMap.get(partsName);
            if (parameterList != null) {
                Set<String> paramNameSet = parameterList.stream()
                        .map(ParameterPojo::getParameterName)
                        .collect(Collectors.toSet());
                partsParamNameMap.put(partsName, paramNameSet);
            }
        }

        // 构建结果
        List<EngineParamDetailPojo> result = new ArrayList<>();

        for (DataEntryEngineModelPojo engineModelPojo : engineModelPojos) {
            if (ObjectUtils.isEmpty(engineModelPojo.getId())) {
                continue;
            }

            // 构建 subsystemParts 列表
            List<String> subsystemPartsList = new ArrayList<>();
            for (String partsName : partsNames) {
                // 由于没有 subsystem 信息，使用 partsName 作为占位符
                // 实际应用中需要根据业务逻辑获取 subsystem
                subsystemPartsList.add("*-" + partsName);
            }

            // 使用 selectTCFromDB 查询
            List<EngineParamDetailPojo> tcDataResults = selectTCFromDB(engineModelPojo.getId(), subsystemPartsList);

            // 过滤并构建结果
            for (EngineParamDetailPojo tcData : tcDataResults) {
                String partsName = tcData.getPartsName();
                String paramName = tcData.getParameterName();

                Set<String> parameterNameSet = partsParamNameMap.get(partsName);
                if (parameterNameSet != null && parameterNameSet.contains(paramName)) {
                    EngineParamDetailPojo engineParamDetailPojo = new EngineParamDetailPojo();
                    engineParamDetailPojo.setEngineModelId(engineModelPojo.getId());
                    engineParamDetailPojo.setPartsName(partsName);
                    engineParamDetailPojo.setParameterName(paramName);
                    engineParamDetailPojo.setParameterValue(tcData.getParameterValue());
                    result.add(engineParamDetailPojo);
                }
            }
        }

        return result;
    }

    @Override
    public List<EngineParamDetailPojo> selectTCFromDB(String modelId, List<String> subsystemParts) {
        DataEntryEngineModelPojo model = engineModelService.selectBymodelId(modelId);
        if (model == null) {
            throw new CommonException("查询失败：机型不存在");
        }

        Set<String> subsystemSet = new HashSet<>();
        Set<String> partsNameSet = new HashSet<>();
        subsystemParts.forEach(subsystemType -> {
            if (subsystemType.split("-").length != 2) {
                throw new CommonException("查询条件异常,需子系统-零部件名称,若零部件为空则传入“/”");
            }
            String subsystem = subsystemType.split("-")[0];
            String partsName = subsystemType.split("-")[1];
            subsystemSet.add(subsystem);
            partsNameSet.add(partsName);
        });

        return bd.getBusinessDatabase()
                .eq("engine_model_id", model.getId())
                .eq("major_version", model.getVersionNumber())
                .in("subsystem_name", subsystemSet)
                .in("parts_name", partsNameSet)
                .doQuery(EngineParamDetailPojo.class);
    }

    private void setupResponse(HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");
    }

    private void setupExcelResponse(HttpServletResponse response, String fileName) {
        try {
            // 设置响应内容类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            // 处理文件名中文乱码
            String encodedFileName = java.net.URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
            // 禁止缓存
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
        } catch (Exception e) {
            log.error("设置Excel响应头失败", e);
            throw new CommonException("设置导出响应头失败");
        }
    }

    private Map<String, String> getModelNameMapping(List<ModelItem> models) {
        Map<String, String> modelNames = new HashMap<>();
        for (ModelItem model : models) {
            if (model == null || StringUtils.isEmpty(model.getModelId())) {
                log.warn("无效的机型项：model为null或modelId为空");
                continue;
            }
            DataEntryEngineModelPojo tempModel = engineModelService.selectBymodelId(model.getModelId());
            if (tempModel != null) {
                modelNames.put(model.getModelId() + "-V" + model.getParameterVersion(), tempModel.getModelName() + "-V" + model.getParameterVersion());
            }
        }
        return modelNames;
    }

    private void loadAndProcessRedisData(ModelComparisonExportRequest request, List<ModelItem> models, String userID,
                                         List<String> subsystemParts, Map<String, Map<String, String>> parameterValues) {
        for (ModelItem model : models) {
            try {
                if (model == null) {
                    log.warn("跳过空的机型项");
                    continue;
                }
                String modelId = model.getModelId();
                String paramVersion = model.getParameterVersion();
                if (StringUtils.isEmpty(modelId) || StringUtils.isEmpty(paramVersion)) {
                    log.warn("机型ID或参数版本为空，跳过该机型：modelId={}, paramVersion={}", modelId, paramVersion);
                    continue;
                }

                String redisKey = userID + ":" + modelId + ":" + paramVersion + ":" + "ComparisonExport";
                if (redisTemplate == null) {
                    throw new CommonException("Redis模板对象未初始化");
                }
                String cachedData = redisTemplate.opsForValue().get(redisKey);

                if (ObjectUtils.isNotEmpty(cachedData)) {
                    if (objectMapper == null) {
                        throw new CommonException("ObjectMapper对象未初始化");
                    }
                    List<EngineParamDetailPojo> allPojos = objectMapper.readValue(cachedData,
                            objectMapper.getTypeFactory().constructCollectionType(List.class, EngineParamDetailPojo.class));

                    // 筛选数据
                    List<EngineParamDetailPojo> filteredPojos = filterEngineParams(allPojos, subsystemParts, request);

                    // 处理筛选后的数据
                    processFilteredParams(filteredPojos, modelId, parameterValues);
                }
            } catch (Exception e) {
                String errorMsg = model != null ?
                        String.format("从Redis读取机型%s数据失败: %s", model.getModelId(), e.getMessage()) :
                        "从Redis读取机型数据失败: " + e.getMessage();
                log.error(errorMsg, e);
                throw new CommonException(errorMsg, e);
            }
        }
    }

    private List<EngineParamDetailPojo> filterEngineParams(List<EngineParamDetailPojo> allPojos,
                                                           List<String> subsystemParts,
                                                           ModelComparisonExportRequest request) {
        if (allPojos == null) {
            return new ArrayList<>();
        }

        return allPojos.stream()
//                .filter(Objects::nonNull) // 增加null过滤
                .filter(pojo -> subsystemParts.stream().anyMatch(part -> {
                    String[] parts = part.split("-");
                    if (parts.length != 2) {
                        return false;
                    }
                    String subsystem = parts[0];
                    String partsName = parts[1];

                    // 参数ID筛选优先
                    if (request.getParameterIds() != null && !request.getParameterIds().isEmpty()) {
                        return request.getParameterIds().contains(pojo.getParameterId());
                    }

                    // 子系统和零部件匹配逻辑
                    if ("/".equals(partsName)) {
                        return Objects.equals(subsystem, pojo.getSubsystemName());
                    } else {
                        return Objects.equals(subsystem, pojo.getSubsystemName()) && Objects.equals(partsName, pojo.getPartsName());
                    }
                }))
                .collect(Collectors.toList());
    }

    private void processFilteredParams(List<EngineParamDetailPojo> filteredPojos, String modelId,
                                       Map<String, Map<String, String>> parameterValues) {
        for (EngineParamDetailPojo pojo : filteredPojos) {
            if (pojo == null || StringUtils.isEmpty(pojo.getParameterName()) ||
                    StringUtils.isEmpty(pojo.getSubsystemName())) {
                log.warn("跳过无效参数项: {}", pojo);
                continue;
            }

            String subsystem = pojo.getSubsystemName();
            String parts = pojo.getPartsName();
            String paramName = pojo.getParameterName();
            String paramValue = pojo.getParameterValue();

            String key = subsystem + "-" + parts + "-" + paramName;

            parameterValues.computeIfAbsent(key, k -> new HashMap<>())
                    .put(modelId + "-" + pojo.getMajorVersion(), paramValue);
        }
    }

    private List<List<String>> buildExcelData(List<ModelItem> models,
                                              Map<String, Map<String, String>> parameterValues) {
        List<List<String>> excelData = new ArrayList<>();

        for (Map.Entry<String, Map<String, String>> entry : parameterValues.entrySet()) {
            String key = entry.getKey();
            Map<String, String> values = entry.getValue();

            List<String> row = new ArrayList<>();
            row.add(key.split("-")[0]); // 子系统
            row.add(key.split("-")[1]); // 零部件
            row.add(key.split("-")[2]); // 参数名

            // 各机型值
            for (ModelItem model : models) {
                String modelKey = model != null ?
                        model.getModelId() + "-" + model.getParameterVersion() : "";
                row.add(values.getOrDefault(modelKey, ""));
            }

            excelData.add(row);
        }

        return excelData;
    }

    private List<List<String>> getCustomHeader(List<ModelItem> models, Map<String, String> modelNames) {
        List<List<String>> header = new ArrayList<>();
        // 固定表头：子系统、零部件、参数
        header.add(Collections.singletonList("子系统"));
        header.add(Collections.singletonList("零部件"));
        header.add(Collections.singletonList("参数"));

        // 动态添加机型表头
        for (ModelItem model : models) {
            String modelName = model == null ? "未知机型" : modelNames.getOrDefault(model.getModelId() + "-V" + model.getParameterVersion(), "未知机型");
            header.add(Collections.singletonList(modelName));
        }
        return header;
    }
}
