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.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.definesys.mpaas.query.MpaasQueryFactory;
import com.definesys.mpaas.query.db.PageQueryResult;
import com.xdap.api.moudle.user.pojo.XdapUsers;
import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.controller.request.DataEntryEngineModelExcel;
import com.xdap.self_development.controller.request.DataEntryEngineModelPageRequest;
import com.xdap.self_development.domain.dto.DataEntryEngineModelDto;
import com.xdap.self_development.domain.dto.PageResultDTO;
import com.xdap.self_development.domain.enums.AuthorizationClassEnum;
import com.xdap.self_development.domain.enums.DistributeStatusEnum;
import com.xdap.self_development.domain.enums.ParamValueVersionEnum;
import com.xdap.self_development.domain.pojo.*;
import com.xdap.self_development.domain.view.MenuParamView;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.exception.ExcelImportException;
import com.xdap.self_development.listener.EngineModelListener;
import com.xdap.self_development.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 数据录入发动机型号服务实现类
 *
 * @version 1.0
 * @since 2025
 */
@Slf4j
@Service
public class DataEntryEngineModelServiceImpl implements DataEntryEngineModelService {
    @Resource
    private AuthService authService;
    @Resource
    private BusinessDatabase bd;
    @Resource
    private ResponsiblePerService responsiblePerService;
    @Resource
    private XdapDeptUsersService xdapDeptUsersService;
    @Resource
    private EngineParamDetailService engineParamDetailService;
    @Resource
    private MpaasQueryFactory sw;
    @Resource
    private ModelRoleService modelRoleService;

    private int page = 1;
    private int size = 10;

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


    /**
     * 查询所有发动机型号
     * 获取数据库中所有发动机型号数据
     *
     * @return 发动机型号POJO列表
     */
    @Override
    public List<DataEntryEngineModelPojo> selectAll() {
        return bd.getBusinessDatabase()
                .eq("is_delete", 0)
                .doQuery(DataEntryEngineModelPojo.class);
    }


    /**
     * 条件分页查询发动机型号
     * 根据指定条件分页查询发动机型号数据
     *
     * @param request 数据录入发动机型号页面请求对象
     * @return 分页结果DTO
     */
    @Override
    public PageResultDTO<DataEntryEngineModelDto> selectByConditionPage(DataEntryEngineModelPageRequest request) {
        //责任人ID
        ResponsiblePersonPojo responsiblePersonPojo;
        List<String> resPerIds = new ArrayList<>();
        List<DataEntryEngineModelDto> dataEntryEngineModelDtos = new ArrayList<>();
        PageResultDTO<DataEntryEngineModelDto> tPageResultDTO = new PageResultDTO<>();
        if (!Objects.isNull(request)) {
            if (Objects.equals(request.getYcOrOth(), "玉柴")) {
                authService.checkUserHasPermission(request.getLoginUserId(), "玉柴"+ AuthorizationClassEnum.ENGINE_VIEW.getPermissionPath());
            } else if (Objects.equals(request.getYcOrOth(), "竞品")) {
                authService.checkUserHasPermission(request.getLoginUserId(), "竞品"+ AuthorizationClassEnum.ENGINE_VIEW.getPermissionPath());
            } else {
                throw new CommonException("无效的查询条件");
            }
            page = request.getPage();
            size = request.getSize();
            String department = request.getDepartment();
            String resPerson = request.getResPerson();
            //部门和人员筛选
            if (ObjectUtils.isNotEmpty(department) && ObjectUtils.isNotEmpty(resPerson)) {
                responsiblePersonPojo = responsiblePerService.selectByDepAndPer(department, resPerson);
                if (!ObjectUtils.isEmpty(responsiblePersonPojo)) {
                    resPerIds.add(responsiblePersonPojo.getId());
                } else {
                    throw new CommonException("没有找到该责任人");
                }
                //部门筛选
            } else if (ObjectUtils.isNotEmpty(department) && ObjectUtils.isEmpty(resPerson)) {
                List<String> strings = responsiblePerService.selectByDepName(department).stream()
                        .map(ResponsiblePersonPojo::getId).collect(Collectors.toList());
                if (ObjectUtils.isNotEmpty(strings)) {
                    resPerIds.addAll(strings);
                } else {
                    throw new CommonException("没有找到该部门下责任人");
                }
                //人员筛选
            } else if (ObjectUtils.isEmpty(department) && ObjectUtils.isNotEmpty(resPerson)) {
                List<XdapUsers> userByName = xdapDeptUsersService.selectUserByPersonName(resPerson);
                List<String> strings = responsiblePerService.selectByUserId(userByName).stream().map(ResponsiblePersonPojo::getId).collect(Collectors.toList());
                if (ObjectUtils.isNotEmpty(strings)) {
                    resPerIds.addAll(strings);
                } else {
                    throw new CommonException("没有找到该责任人");
                }
            }


        } else {
            request = new DataEntryEngineModelPageRequest();
            log.warn("注意：传入参数为空默认无条件首页十条");
        }
        log.info("查找到的责任人：{}", resPerIds);
        DistributeStatusEnum byDesc = DistributeStatusEnum.getByDesc(request.getDistributeStatus());
        Integer status = byDesc != null ? byDesc.getCode() : null;

        PageQueryResult<DataEntryEngineModelPojo> pageQueryResult = bd.getBusinessDatabase()
                .eq("yc_or_oth", request.getYcOrOth())
                .eq("is_delete", 0)
                .like("model_name", request.getModelName())
                .like("product_number", request.getProductNumber())
                .like("plate", request.getPlate())
                .like("platform", request.getPlatform())
                .like("series", request.getSeries())
                .like("market_segment", request.getMarketSegment())
                .like("project_name", request.getProjectName())
                .like("project_number", request.getProjectNumber())
                .like("brand", request.getBrand())
                .in("responsible_person_id", resPerIds)
                .eq("distribute_status", status)
                .orderBy("creation_date", "desc")
                .doPageQuery(page, size, DataEntryEngineModelPojo.class);

        for (DataEntryEngineModelPojo modelPojo : pageQueryResult.getResult()) {
            DataEntryEngineModelDto dataEntryEngineModelDto = new DataEntryEngineModelDto();
            BeanUtils.copyProperties(modelPojo, dataEntryEngineModelDto);
            dataEntryEngineModelDto.setId(modelPojo.getId());

            DistributeStatusEnum byDesc1 = DistributeStatusEnum.getByCode(modelPojo.getDistributeStatus());
            dataEntryEngineModelDto.setDistributeStatus(byDesc1 != null ? byDesc1.getDesc() : null);
            dataEntryEngineModelDtos.add(dataEntryEngineModelDto);
        }
        dataEntryEngineModelDtos.sort(Comparator.comparing(DataEntryEngineModelDto::getCreationDate).reversed());
        tPageResultDTO.setList(dataEntryEngineModelDtos);
        tPageResultDTO.setTotalCount(pageQueryResult.getCount());
        return tPageResultDTO;
    }


    /**
     * Excel导入发动机型号数据
     * 从Excel文件导入发动机型号相关信息
     *
     * @param file   Excel文件
     * @param userId 用户ID
     * @param ycOrOt 玉柴或其他标识
     * @return void
     */
    @Override
//    @Transactional
    public void excelImport(MultipartFile file, String userId, String ycOrOt) {
        if (ObjectUtils.isEmpty(userId)) {
            throw new ExcelImportException("执行上传操作的用户查不到,无法上传");
        }
        List<XdapUsers> users = bd.getSystemDatabase()
                .eq("id", userId)
                .doQuery(XdapUsers.class);
        if (ObjectUtils.isEmpty(users)) {
            throw new ExcelImportException("执行上传操作的用户查不到,无法上传");
        }
        XdapUsers xdapUsersPojo = users.get(0);
        try {
            EasyExcel.read(file.getInputStream(),
                            DataEntryEngineModelExcel.class,
                            new EngineModelListener(
                                    bd,
                                    engineParamDetailService,
                                    ycOrOt,
                                    xdapUsersPojo
                            ))
                    .sheet()
                    .doRead();
        } catch (IOException e) {
            log.error("读取文件异常");
            throw new CommonException("读取文件异常");
        } catch (RuntimeException e) {
            throw new ExcelImportException(e.getMessage());
        }
    }

    /**
     * 插入发动机型号数据
     * 添加新的发动机型号数据到数据库
     *
     * @param request 数据录入发动机型号页面请求对象
     * @param userId  用户ID
     * @return 插入结果
     */
    @Override
    @Transactional
    public int insert(DataEntryEngineModelPageRequest request, String userId) {
        List<ParameterPojo> parameters = engineParamDetailService.selectAllByNewVersion();
        DataEntryEngineModelPojo modelPojo = new DataEntryEngineModelPojo();
        BeanUtils.copyProperties(request, modelPojo, "status");
        List<DataEntryEngineModelPojo> modelPojos = bd.getBusinessDatabase()
                .eq("product_number", request.getProductNumber())
                .eq("is_delete", 0)
                .doQuery(DataEntryEngineModelPojo.class);
        if (ObjectUtils.isNotEmpty(modelPojos)) {
            throw new ExcelImportException(
                    "请检查该型号是否已经存在"
            );
        }

        List<XdapUsers> users = bd.getSystemDatabase()
                .eq("id", userId)
                .doQuery(XdapUsers.class);
        if (ObjectUtils.isEmpty(users)) {
            throw new ExcelImportException("执行上传操作的用户查不到,无法上传");
        }
        XdapUsers xdapUsersPojo = users.get(0);

        //获取状态码
        DistributeStatusEnum byDesc = DistributeStatusEnum.getByDesc(request.getDistributeStatus());
        modelPojo.setDistributeStatus(byDesc != null ? byDesc.getCode() : null);
        modelPojo.setParameterNum(parameters.toArray().length);
        modelPojo.setMaintainedParameterNum(0);
        modelPojo.setVersionNumber(versionNumber);
        modelPojo.setIsDelete(0);
        modelPojo.setCreatedBy(userId);
        modelPojo.setLastUpdatedBy("");
        modelPojo.setLastUpdateDate(Timestamp.valueOf(LocalDateTime.now()));
        modelPojo.setCreationDate(Timestamp.valueOf(LocalDateTime.now()));
        modelPojo.setId(UUID.randomUUID().toString());
        bd.getBusinessDatabase().doInsert(modelPojo);

        saveDataParamDetail(modelPojo, parameters, versionNumber, xdapUsersPojo);
        return 0;
    }

    /**
     * 为每个机型绑定参数
     * 将参数与发动机型号进行绑定
     *
     * @param modelPojo     发动机型号POJO
     * @param parameters    参数列表
     * @param newVersionNum 新版本号
     * @param xdapUsersPojo 用户POJO
     * @return void
     */
    public void saveDataParamDetail(DataEntryEngineModelPojo modelPojo, List<ParameterPojo> parameters, Integer newVersionNum, XdapUsers xdapUsersPojo) {
        /*
          遍历机型
          查找参数 将每个机型都把参数，和参数所属的填写部门关联上
          参数值暂时放空
         */
        List<EngineParamDetailPojo> engineParamDetailPojos = new ArrayList<>();
        if (Objects.equals(modelPojo.getYcOrOth(), "玉柴")) {
            for (ParameterPojo parameter : parameters) {
                EngineParamDetailPojo engineParamDetailPojo = new EngineParamDetailPojo();
                engineParamDetailPojo.setEngineModelId(modelPojo.getId());
                engineParamDetailPojo.setParameterId(parameter.getId());
                engineParamDetailPojo.setSubsystemName(parameter.getSubsystemName());
                engineParamDetailPojo.setParameterType(parameter.getParameterType());
                engineParamDetailPojo.setPartsName(parameter.getPartsName());
                engineParamDetailPojo.setParameterName(parameter.getParameterName());
                engineParamDetailPojo.setDepartment(parameter.getDepartment());
                engineParamDetailPojo.setParameterSource(parameter.getParameterSource());
                engineParamDetailPojo.setMajorVersion(newVersionNum);
                engineParamDetailPojo.setVersionStatus(ParamValueVersionEnum.DRAFT.getCode());
                engineParamDetailPojo.setCreatedBy(ObjectUtils.isNotEmpty(xdapUsersPojo) ? xdapUsersPojo.getId() : null);
                engineParamDetailPojo.setLastUpdatedBy("");
                engineParamDetailPojo.setLastUpdateDate(Timestamp.valueOf(LocalDateTime.now()));
                engineParamDetailPojo.setCreationDate(Timestamp.valueOf(LocalDateTime.now()));
                engineParamDetailPojo.setIsDistributedRes(Objects.equals(parameter.getParameterSource(), "数据平台手工录入") ? 0 : 2);
                engineParamDetailPojo.setIsDistributedFilled(Objects.equals(parameter.getParameterSource(), "数据平台手工录入") ? 0 : 2);
                engineParamDetailPojos.add(engineParamDetailPojo);
            }
        } else {
            for (ParameterPojo parameter : parameters) {
                EngineParamDetailPojo engineParamDetailPojo = new EngineParamDetailPojo();
                engineParamDetailPojo.setEngineModelId(modelPojo.getId());
                engineParamDetailPojo.setParameterId(parameter.getId());
                engineParamDetailPojo.setSubsystemName(parameter.getSubsystemName());
                engineParamDetailPojo.setParameterType(parameter.getParameterType());
                engineParamDetailPojo.setPartsName(parameter.getPartsName());
                engineParamDetailPojo.setParameterName(parameter.getParameterName());
                engineParamDetailPojo.setDepartment(parameter.getDepartment());
                engineParamDetailPojo.setParameterSource("数据平台手工录入");
                engineParamDetailPojo.setMajorVersion(newVersionNum);
                engineParamDetailPojo.setVersionStatus(ParamValueVersionEnum.DRAFT.getCode());
                engineParamDetailPojo.setCreatedBy(ObjectUtils.isNotEmpty(xdapUsersPojo) ? xdapUsersPojo.getId() : null);
                engineParamDetailPojo.setLastUpdatedBy("");
                engineParamDetailPojo.setLastUpdateDate(Timestamp.valueOf(LocalDateTime.now()));
                engineParamDetailPojo.setCreationDate(Timestamp.valueOf(LocalDateTime.now()));
                engineParamDetailPojo.setIsDistributedRes(0);
                engineParamDetailPojo.setIsDistributedFilled(0);
                engineParamDetailPojos.add(engineParamDetailPojo);

            }
        }
        bd.getBusinessDatabase().doBatchInsert(engineParamDetailPojos);
    }

    /**
     * Excel导出发动机型号数据
     * 导出发动机型号数据到Excel文件
     *
     * @param response HTTP响应对象
     * @return void
     */
    @Override
    public void excelExport(HttpServletResponse response) {
        // 定义Sheet名称集合
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build()) {
            setupResponse(response, "机型导入模板" + (formatter.format(LocalDateTime.now())));
            List<DataEntryEngineModelExcel> dataEntryEngineModelExcel = new ArrayList<>();
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            // 设置背景色为灰色
            headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            // 设置字体
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 12); // 字体大小
            headWriteFont.setBold(true); // 加粗
            headWriteCellStyle.setWriteFont(headWriteFont);

            // 创建表头策略
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());

            WriteSheet sheet = EasyExcel.writerSheet()
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .head(DataEntryEngineModelExcel.class)  // 所有Sheet使用相同的表头
                    .build();
            excelWriter.write(dataEntryEngineModelExcel, sheet); // 写入数据，只生成表头
        } catch (Exception e) {
            throw new CommonException("导出Excel文件异常");
        }
    }

    /**
     * 根据型号ID查询发动机型号
     * 通过ID获取特定的发动机型号信息
     *
     * @param modelId 型号ID
     * @return 发动机型号POJO
     */
    @Override
    public DataEntryEngineModelPojo selectBymodelId(String modelId) {
        if (ObjectUtils.isNotEmpty(modelId)) {
            List<DataEntryEngineModelPojo> modelPojos = bd.getBusinessDatabase()
                    .eq("id", modelId).doQuery(DataEntryEngineModelPojo.class);
            if (ObjectUtils.isNotEmpty(modelPojos)) {
                return modelPojos.get(0);
            }
        }
        log.error("该发动机不存在");
        return null;
    }

    /**
     * 条件分页查询版本信息
     * 根据条件分页获取版本信息
     *
     * @return 分页结果DTO
     */
    @Override
    public PageResultDTO<DataEntryEngineModelDto> selectVersionByConditionPage(String userId) {
        //todo
        List<MenuParamView> menuParamViews = modelRoleService.selectPersByUser(userId);
        boolean ycFlag = false;
        boolean othFlag = false;

        for (MenuParamView item : menuParamViews) {
            if (item.getIsAdmin() != null && item.getIsAdmin() == 1) {
                othFlag = true;
                ycFlag = true;
                break;
            }
            if (item.getPermissionPath().startsWith("竞品发动机数据") && !item.getPermissionPath().equals("竞品发动机数据审批流程")) {
                othFlag = true;
                continue;
            }
            if (item.getPermissionPath().startsWith("玉柴发动机数据") && !item.getPermissionPath().equals("玉柴发动机数据审批流程")) {
                ycFlag = true;
                continue;
            }
            if (ycFlag && othFlag) {
                break;
            }
        }


        List<DataEntryEngineModelDto> list = bd.getBusinessDatabase()
                .viewQueryMode(true)
                .view("selectVersionByConditionPage")
                .doQuery(DataEntryEngineModelDto.class);
        PageResultDTO<DataEntryEngineModelDto> pageResultDTO = new PageResultDTO<>();

        boolean finalYcFlag = ycFlag;
        boolean finalOthFlag = othFlag;
        List<DataEntryEngineModelDto> collect = list.stream().filter(x -> {
            if (finalYcFlag && Objects.equals(x.getYcOrOth(), "玉柴")) {
                return true;
            }

            return finalOthFlag && Objects.equals(x.getYcOrOth(), "竞品");
        }).collect(Collectors.toList());

        pageResultDTO.setList(collect);
        pageResultDTO.setTotalCount(collect.size());
        return pageResultDTO;
    }

    /**
     * 删除发动机型号
     * 根据ID删除指定的发动机型号数据
     *
     * @param modelId 型号ID
     * @return void
     */
    @Override
    public void delete(String modelId) {

        DataEntryEngineModelPojo model = bd.getBusinessDatabase()
                .eq("id", modelId)
                .doQueryFirst(DataEntryEngineModelPojo.class);
        if (ObjectUtils.isEmpty(model)) {
            throw new CommonException("机型不存在");
        }

        if (model.getDistributeStatus() != 2) {
            throw new CommonException("机型已分发，无法删除");
        }

        bd.getBusinessDatabase()
                .eq("id", modelId)
                .update("is_delete", 1)
                .doUpdate(DataEntryEngineModelPojo.class);
    }

    private static EngineParamDetailPojo getEngineParamDetailPojo(ParameterPojo parameter, DataEntryEngineModelPojo model) {
        EngineParamDetailPojo detailPojo = new EngineParamDetailPojo();
        detailPojo.setEngineModelId(model.getId());
        detailPojo.setSubsystemName(parameter.getSubsystemName());
        detailPojo.setDepartment(parameter.getDepartment());
        detailPojo.setPartsName(parameter.getPartsName());
        detailPojo.setParameterId(parameter.getId());
        detailPojo.setParameterName(parameter.getParameterName());
        detailPojo.setParameterSource(parameter.getParameterSource());
        detailPojo.setParameterType(parameter.getParameterType());
        detailPojo.setIsDistributedFilled("数据平台手工录入".equals(parameter.getParameterSource()) ? 0 : 2);
        detailPojo.setIsDistributedRes("数据平台手工录入".equals(parameter.getParameterSource()) ? 0 : 2);
        detailPojo.setResponsiblePersonId(null);
        detailPojo.setFilledBy(null);
        detailPojo.setMajorVersion(model.getVersionNumber());
        detailPojo.setCreationDate(new Date());
        return detailPojo;
    }

    @Override
    @Transactional
    public Integer synchronizeParams(String modelId, String userId) {
        // 检查机型
        DataEntryEngineModelPojo model = bd.getBusinessDatabase()
                .eq("id", modelId)
                .in("distribute_status",
                        DistributeStatusEnum.UNDISTRIBUTED.getCode(),
                        DistributeStatusEnum.COMPLETE.getCode()
                )
                .doQueryFirst(DataEntryEngineModelPojo.class);
        if (model == null) {
            throw new CommonException("机型不存在或已分发");
        }

        // 找到最新版本模板的参数
        List<TemplatePojo> templates = bd.getBusinessDatabase()
                .eq("status", "COMPLETE")
                .doQuery(TemplatePojo.class);
        if (templates.isEmpty()) {
            throw new CommonException("没有找到完成状态的模板");
        }
        List<String> templateIds = templates.stream().map(TemplatePojo::getId).collect(Collectors.toList());
        List<TemplateAndParameterPojo> templateAndParameters = bd.getBusinessDatabase()
                .in("template_id", templateIds)
                .doQuery(TemplateAndParameterPojo.class);
        if (templateAndParameters.isEmpty()) {
            throw new CommonException("没有找到模板对应的参数");
        }
        List<String> parameterIds = templateAndParameters.stream().map(TemplateAndParameterPojo::getParameterId).collect(Collectors.toList());
        List<ParameterPojo> parameters = bd.getBusinessDatabase()
                .in("id", parameterIds)
                .doQuery(ParameterPojo.class);
        if (parameters.isEmpty()) {
            throw new CommonException("没有找到参数");
        }

        // 检查当前版本机型是否有参数正在审批中
        List<EngineParamDetailPojo> paramsInApproval = bd.getBusinessDatabase()
                .eq("engine_model_id", modelId)
                .eq("major_version", model.getVersionNumber())
                .eq("version_status", ParamValueVersionEnum.UNDER.getCode())
                .doQuery(EngineParamDetailPojo.class);
        if (!paramsInApproval.isEmpty()) {
            throw new CommonException("当前版本机型有参数正在审批中，请等待审批完成");
        }

        // 获取当前机型版本对应的所有参数
        List<EngineParamDetailPojo> modelParams = bd.getBusinessDatabase()
                .eq("engine_model_id", model.getId())
                .eq("major_version", model.getVersionNumber())
                .doQuery(EngineParamDetailPojo.class);
        List<String> modelParamIds = modelParams.stream()
                .map(EngineParamDetailPojo::getParameterId)
                .collect(Collectors.toList());
        Map<String, EngineParamDetailPojo> modelParamMap = modelParams.stream()
                .collect(Collectors.
                        toMap(
                                EngineParamDetailPojo::getParameterId,
                                pojo -> pojo,
                                (existing, replacement) -> existing)
                );

        // 验证是否需要更新
        if (modelParams.size() == parameters.size() && isSameParams(modelParams, parameters, model)) {
            throw new CommonException("当前版本机型参数已同步最新模板参数");
        }

        Map<String, ParameterPojo> uniqueParamsMap = new LinkedHashMap<>();
        for (ParameterPojo parameter : parameters) {
            String key = parameter.getParameterName() + "_" + parameter.getPartsName() + "_" + parameter.getSubsystemName();
            uniqueParamsMap.putIfAbsent(key, parameter);
        }
        List<ParameterPojo> uniqueParameters = new ArrayList<>(uniqueParamsMap.values());

        // 过滤新批次模板的参数，更新到机型参数中
        // 统计需要插入的参数
        List<EngineParamDetailPojo> toInsertParams = new ArrayList<>();
        // 更新机型版本
        model.setVersionNumber(model.getVersionNumber() + 1);
        if (Objects.equals(model.getYcOrOth(), "玉柴")) {
            uniqueParameters.forEach(parameter -> {
                // 检查老机型参数中是否存在新版本参数
                // 存在则更新
                if (modelParamIds.contains(parameter.getId())) {
                    // 拿到老参数
                    EngineParamDetailPojo detailPojo = modelParamMap.get(parameter.getId());
                    detailPojo.setId(null);
                    detailPojo.setSubsystemName(parameter.getSubsystemName());
                    detailPojo.setDepartment(parameter.getDepartment());
                    detailPojo.setPartsName(parameter.getPartsName());
                    detailPojo.setParameterName(parameter.getParameterName());
                    detailPojo.setParameterSource(parameter.getParameterSource());
                    detailPojo.setParameterType(parameter.getParameterType());
                    detailPojo.setIsDistributedFilled("数据平台手工录入".equals(parameter.getParameterSource()) ? 0 : 2);
                    detailPojo.setIsDistributedRes("数据平台手工录入".equals(parameter.getParameterSource()) ? 0 : 2);
                    detailPojo.setResponsiblePersonId(null);
                    detailPojo.setFilledBy(null);
                    detailPojo.setMajorVersion(model.getVersionNumber());
                    toInsertParams.add(detailPojo);
                }
                // 不存在则新增
                else {
                    toInsertParams.add(getEngineParamDetailPojo(parameter, model));
                }
            });
        } else {
            uniqueParameters.forEach(parameter -> {
                // 检查老机型参数中是否存在新版本参数
                // 存在则更新
                if (modelParamIds.contains(parameter.getId())) {
                    // 拿到老参数
                    EngineParamDetailPojo detailPojo = modelParamMap.get(parameter.getId());
                    detailPojo.setId(null);
                    detailPojo.setSubsystemName(parameter.getSubsystemName());
                    detailPojo.setDepartment(parameter.getDepartment());
                    detailPojo.setPartsName(parameter.getPartsName());
                    detailPojo.setParameterName(parameter.getParameterName());
                    detailPojo.setParameterSource("数据平台手工录入");
                    detailPojo.setParameterType(parameter.getParameterType());
                    detailPojo.setIsDistributedFilled(0);
                    detailPojo.setIsDistributedRes(0);
                    detailPojo.setResponsiblePersonId(null);
                    detailPojo.setFilledBy(null);
                    detailPojo.setMajorVersion(model.getVersionNumber());
                    toInsertParams.add(detailPojo);
                }
                // 不存在则新增
                else {
                    toInsertParams.add(getEngineParamDetailPojo(parameter, model));
                }
            });
        }

        // 更新机型
        bd.getBusinessDatabase()
                .eq("id", model.getId())
                .update("version_number", model.getVersionNumber())
                .update("parameter_num", uniqueParameters.size())
                .doUpdate(DataEntryEngineModelPojo.class);

        // 更新新版本机型的参数
        bd.getBusinessDatabase().doBatchInsert(toInsertParams);

        // 更新待办已办完成状态
        bd.getBusinessDatabase()
                .update("is_delete", 1)
                .eq("model_id", model.getId())
                .doUpdate(TodoTaskPojo.class);
        bd.getBusinessDatabase()
                .update("is_delete", 1)
                .eq("model_id", model.getId())
                .doUpdate(InitiatedTaskPojo.class);
        bd.getBusinessDatabase()
                .update("is_delete", 1)
                .eq("model_id", model.getId())
                .doUpdate(CompletedTaskPojo.class);

        return model.getVersionNumber();
    }

    private boolean isSameParams(
            List<EngineParamDetailPojo> modelParams,
            List<ParameterPojo> parameters,
            DataEntryEngineModelPojo model
    ) {
        Map<String, EngineParamDetailPojo> modelParamMap = modelParams.stream()
                .collect(Collectors.
                        toMap(
                                EngineParamDetailPojo::getParameterId,
                                pojo -> pojo,
                                (existing, replacement) -> existing
                        )
                );
        return parameters.stream().allMatch(parameter -> {
            EngineParamDetailPojo detailPojo = modelParamMap.get(parameter.getId());
            if (Objects.equals(model.getYcOrOth(), "玉柴")) {
                return detailPojo != null &&
                        Objects.equals(detailPojo.getParameterName(), parameter.getParameterName()) &&
                        Objects.equals(detailPojo.getParameterSource(), parameter.getParameterSource()) &&
                        Objects.equals(detailPojo.getParameterType(), parameter.getParameterType()) &&
                        Objects.equals(detailPojo.getSubsystemName(), parameter.getSubsystemName()) &&
                        Objects.equals(detailPojo.getDepartment(), parameter.getDepartment()) &&
                        Objects.equals(detailPojo.getPartsName(), parameter.getPartsName());
            } else {
                return detailPojo != null &&
                        Objects.equals(detailPojo.getParameterName(), parameter.getParameterName()) &&
                        Objects.equals(detailPojo.getParameterType(), parameter.getParameterType()) &&
                        Objects.equals(detailPojo.getSubsystemName(), parameter.getSubsystemName()) &&
                        Objects.equals(detailPojo.getDepartment(), parameter.getDepartment()) &&
                        Objects.equals(detailPojo.getPartsName(), parameter.getPartsName());
            }
        });
    }

    /**
     * 设置响应
     * 设置HTTP响应的头部信息用于文件下载
     *
     * @param response HTTP响应对象
     * @param fileName 文件名
     * @return void
     */
    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");
    }

}
