package com.aps.service.common;

import cn.hutool.core.bean.BeanUtil;
import com.aps.common.util.R;
import com.aps.entity.Algorithm.Chromosome;
import com.aps.entity.Algorithm.GAScheduleResult;
import com.aps.entity.Algorithm.OrderMaterialRequirement;
import com.aps.entity.Gantt.ResourceGanttVO;
import com.aps.entity.Gantt.TaskVO;
import com.aps.entity.ProdProcessExec;
import com.aps.entity.Algorithm.GlobalOperationInfo;
import com.aps.entity.Algorithm.IDAndChildID.GroupResult;
import com.aps.entity.basic.Entry;
import com.aps.entity.basic.Machine;
import com.aps.entity.basic.MachineOption;
import com.aps.entity.basic.Order;
import com.aps.entity.common.*;
import com.aps.entity.Schedule.SceneChromsome;
import com.aps.service.plan.PlanResultService;
import com.aps.service.plan.SceneService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import com.aps.service.MaterialInfoService;
import com.aps.entity.MaterialInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@Service
@Slf4j
public class ChromosomeDataService {

    private static final DateTimeFormatter FRONTEND_UTC_MILLIS_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    @Autowired
    private SceneService sceneService;

    @Autowired
    private DatabaseQueryService databaseQueryService;

    @Autowired
    private MaterialInfoService materialInfoService;

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private Map<String, EntityConfig> entityConfigMap;

    @Autowired
    private PlanResultService planResultService;
    
    /**
     * 字段注释缓存，避免重复读取源文件
     */
    private final ConcurrentHashMap<Class<?>, Map<String, String>> fieldCommentCache = new ConcurrentHashMap<>();
    
    /**
     * 实体配置缓存，避免重复创建配置
     */
    private final ConcurrentHashMap<String, EntityConfig> entityConfigCache = new ConcurrentHashMap<>();
    
    /**
     * 文件数据查询缓存，避免重复加载文件
     */
    private final ConcurrentHashMap<String, Object> fileDataCache = new ConcurrentHashMap<>();
    
    /**
     * 反射字段缓存，避免重复反射操作
     */
    private final ConcurrentHashMap<Class<?>, Map<String, Field>> fieldCache = new ConcurrentHashMap<>();
    
    /**
     * 根据场景ID和实体名称查询Chromosome中的数据
     */

    ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule())
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    /**
     * 驼峰命名转下划线大写：prodProduct -> PROD_PRODUCT, apsOder -> APS_ORDER
     */
    private String camelCaseToUnderScoreUpperCase(String camelCase) {
        if (camelCase == null || camelCase.isEmpty()) {
            return camelCase;
        }

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < camelCase.length(); i++) {
            char c = camelCase.charAt(i);

            // 遇到大写字母且不是第一个字符时，添加下划线
            if (Character.isUpperCase(c) && i > 0) {
                // 检查前一个字符是否是小写，避免连续大写的情况
                char prevChar = camelCase.charAt(i - 1);
                if (Character.isLowerCase(prevChar)) {
                    result.append('_');
                }
            }
            result.append(Character.toUpperCase(c));
        }

        return result.toString();
    }


    /**
     * 为查询条件包装器添加条件
     */
    private void addConditionToWrapper(LambdaQueryWrapper<MaterialInfo> wrapper, ConditionEntity condition) {
        String fieldName = condition.getFieldName();
        String conditionType = condition.getConditionalType();
        String fieldValue = condition.getFieldValue();

        switch (fieldName.toLowerCase()) {
            case "name":
                if ("LIKE".equalsIgnoreCase(conditionType)) {
                    wrapper.like(MaterialInfo::getName, fieldValue);
                } else if ("EQUAL".equalsIgnoreCase(conditionType)) {
                    wrapper.eq(MaterialInfo::getName, fieldValue);
                }
                break;
            case "code":
                if ("LIKE".equalsIgnoreCase(conditionType)) {
                    wrapper.like(MaterialInfo::getCode, fieldValue);
                } else if ("EQUAL".equalsIgnoreCase(conditionType)) {
                    wrapper.eq(MaterialInfo::getCode, fieldValue);
                }
                break;
            case "categoryname":
                if ("LIKE".equalsIgnoreCase(conditionType)) {
                    wrapper.like(MaterialInfo::getCategoryName, fieldValue);
                } else if ("EQUAL".equalsIgnoreCase(conditionType)) {
                    wrapper.eq(MaterialInfo::getCategoryName, fieldValue);
                }
                break;
            // 可以继续添加其他字段的条件处理
        }
    }


    /**
     * 获取实体的字段信息
     * @param entityName 实体名称
     * @return 字段信息列表
     */
    public List<FieldInfo> getEntityInfo(String entityName) {
        List<FieldInfo> fieldInfos = new ArrayList<>();

        // 检查是否有对应的实体类
        Class<?> entityClass = getEntityClass(entityName);
        if (entityClass != null) {
            // 通过反射获取所有字段（包括父类字段）
            List<Field> fields = new ArrayList<>();
            Class<?> currentClass = entityClass;
            while (currentClass != null && currentClass != Object.class) {
                fields.addAll(Arrays.asList(currentClass.getDeclaredFields()));
                currentClass = currentClass.getSuperclass();
            }

            // 获取字段描述映射
            Map<String, String> fieldDescriptions = new HashMap<>();

            // 遍历字段，生成FieldInfo
            for (Field field : fields) {
                // 跳过静态字段
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                FieldInfo fieldInfo = new FieldInfo();
                fieldInfo.setFieldName(field.getName());
                fieldInfo.setFieldType(field.getType().getSimpleName());

                // 设置字段描述
                fieldInfo.setDescription(fieldDescriptions.getOrDefault(field.getName(), ""));

                fieldInfo.setDataSource("ENTITY");
                fieldInfo.setEntityName(entityName);

                fieldInfos.add(fieldInfo);
            }
            return fieldInfos;
        }

        // 获取实体配置
        EntityConfig config = getEntityConfig(entityName);

        // 处理文件实体
        if (config.getDataSource() == DataSourceType.FILE) {
            // 实体类映射
            Map<String, Class<?>> fileEntityClassMap = new HashMap<>();
            fileEntityClassMap.put("order", Order.class);
            fileEntityClassMap.put("entry", Entry.class);
            fileEntityClassMap.put("machine", Machine.class);
            fileEntityClassMap.put("machineoption", MachineOption.class);
            fileEntityClassMap.put("prodprocessexec", ProdProcessExec.class);
            fileEntityClassMap.put("globaloperationinfo", GlobalOperationInfo.class);
            fileEntityClassMap.put("groupresult", GroupResult.class);

            // 获取实体类
            Class<?> fileEntityClass = fileEntityClassMap.get(entityName.toLowerCase());

            // 如果没有找到实体类，返回空列表
            if (fileEntityClass == null) {
                return fieldInfos;
            }

            // 通过反射获取所有字段（包括父类字段）
            List<Field> fields = new ArrayList<>();
            Class<?> currentClass = fileEntityClass;
            while (currentClass != null && currentClass != Object.class) {
                fields.addAll(Arrays.asList(currentClass.getDeclaredFields()));
                currentClass = currentClass.getSuperclass();
            }

            // 获取字段描述映射
            Map<String, String> fieldDescriptions = getFieldDescriptions(entityName);

            // 遍历字段，生成FieldInfo
            for (Field field : fields) {
                // 跳过静态字段
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }

                FieldInfo fieldInfo = new FieldInfo();
                fieldInfo.setFieldName(field.getName());
                fieldInfo.setFieldType(field.getType().getSimpleName());

                // 设置字段描述
                fieldInfo.setDescription(fieldDescriptions.getOrDefault(field.getName(), ""));

                fieldInfo.setDataSource(config.getDataSource().name());
                fieldInfo.setEntityName(entityName);

                fieldInfos.add(fieldInfo);
            }
        }
        // 处理数据库实体
        else {
            try (// 获取数据库连接
                 java.sql.Connection connection = jdbcTemplate.getDataSource().getConnection();
                 // 获取表的列信息
                 java.sql.ResultSet columns = connection.getMetaData().getColumns(null, null, config.getTableName(), null)) {
                
                // 遍历列信息，生成FieldInfo
                while (columns.next()) {
                    FieldInfo fieldInfo = new FieldInfo();
                    fieldInfo.setFieldName(columns.getString("COLUMN_NAME"));
                    // 将数据库字段类型转换为Java类型
                    fieldInfo.setFieldType(mapDbTypeToJavaType(columns.getString("TYPE_NAME")));
                    fieldInfo.setDescription(columns.getString("REMARKS"));
                    fieldInfo.setDataSource(config.getDataSource().name());
                    fieldInfo.setEntityName(entityName);

                    fieldInfos.add(fieldInfo);
                }
            } catch (Exception e) {
                log.error("获取数据库表字段信息失败: {}", e.getMessage(), e);
            }
        }

        return fieldInfos;
    }
    /**
     * 获取实体对应的Java类
     * @param entityName 实体名称
     * @return 实体类，无对应类时返回null
     */
    private Class<?> getEntityClass(String entityName) {
        // 实体类映射
        Map<String, Class<?>> entityClassMap = new HashMap<>();
        // 数据库实体类映射
        entityClassMap.put("materialinfo", MaterialInfo.class);
        // 文件实体类映射
        entityClassMap.put("order", Order.class);
        entityClassMap.put("entry", Entry.class);
        entityClassMap.put("machine", Machine.class);
        entityClassMap.put("machineoption", MachineOption.class);
        entityClassMap.put("prodprocessexec", ProdProcessExec.class);
        entityClassMap.put("globaloperationinfo", GlobalOperationInfo.class);
        entityClassMap.put("groupresult", GroupResult.class);
        entityClassMap.put("task", TaskVO.class);

        return entityClassMap.get(entityName.toLowerCase());
    }


    /**
     * 将数据库字段类型转换为Java类型
     * @param dbType 数据库字段类型
     * @return Java类型
     */
    private String mapDbTypeToJavaType(String dbType) {
        // 简单的类型映射
        Map<String, String> typeMap = new HashMap<>();
        typeMap.put("VARCHAR", "String");
        typeMap.put("NVARCHAR", "String");
        typeMap.put("CHAR", "String");
        typeMap.put("TEXT", "String");
        typeMap.put("NUMBER", "Integer");
        typeMap.put("INT", "Integer");
        typeMap.put("INTEGER", "Integer");
        typeMap.put("BIGINT", "Long");
        typeMap.put("FLOAT", "Float");
        typeMap.put("DOUBLE", "Double");
        typeMap.put("DECIMAL", "BigDecimal");
        typeMap.put("BOOLEAN", "Boolean");
        typeMap.put("DATE", "Date");
        typeMap.put("TIMESTAMP", "Timestamp");

        return typeMap.getOrDefault(dbType.toUpperCase(), dbType);
    }


    /**
     * 获取指定实体的字段描述映射
     * @param entityName 实体名称
     * @return 字段描述映射
     */
    private Map<String, String> getFieldDescriptions(String entityName) {
        Map<String, String> fieldDescriptions = new HashMap<>();

        // 首先尝试从实体类注解和JavaDoc注释中提取字段描述
        Class<?> entityClass = getEntityClass(entityName);
        if (entityClass != null) {
            // 通过反射获取所有字段（包括父类字段）
            List<Field> fields = new ArrayList<>();
            Class<?> currentClass = entityClass;
            while (currentClass != null && currentClass != Object.class) {
                fields.addAll(Arrays.asList(currentClass.getDeclaredFields()));
                currentClass = currentClass.getSuperclass();
            }

            // 提取字段注释
            for (Field field : fields) {



                // 3. 尝试从JavaDoc注释中提取描述
                String javaDocComment = getFieldCommentFromSource(entityClass, field.getName());
                if (javaDocComment != null && !javaDocComment.isEmpty() && !fieldDescriptions.containsKey(field.getName())) {
                    fieldDescriptions.put(field.getName(), javaDocComment);
                }
            }

            // 如果成功提取到字段描述，直接返回
            if (!fieldDescriptions.isEmpty()) {
                return fieldDescriptions;
            }
        }

        return fieldDescriptions;
    }

    /**
     * 从源文件中提取字段注释
     * @param clazz 实体类
     * @param fieldName 字段名
     * @return 字段注释
     */
    private String getFieldCommentFromSource(Class<?> clazz, String fieldName) {
        try {
            // 获取类的源文件路径
            String packagePath = clazz.getPackage().getName().replace('.', '/');
            String fileName = clazz.getSimpleName() + ".java";
            String sourcePath = "src/main/java/" + packagePath + "/" + fileName;

            java.io.File file = new java.io.File(sourcePath);
            if (file.exists()) {
                String content = new String(java.nio.file.Files.readAllBytes(file.toPath()), "UTF-8");

                // 使用正则表达式匹配字段注释
                String pattern = "/\\*\\*\\s*(?:\\*\\s*(.*?))+\\s*\\*/\\s*private\\s+\\w+\\s+" + fieldName + "\\s*";
                java.util.regex.Pattern regex = java.util.regex.Pattern.compile(pattern, java.util.regex.Pattern.DOTALL);
                java.util.regex.Matcher matcher = regex.matcher(content);

                if (matcher.find()) {
                    String comment = matcher.group(1);
                    return comment.replaceAll("\\*\\s*", "").trim();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 创建空的分页结果
     */
    private Map<String, Object> createEmptyResult(Paged paged) {
        Map<String, Object> emptyResult = new HashMap<>();
        emptyResult.put("records", Collections.emptyList());
        emptyResult.put("totalCount", 0);
        emptyResult.put("pageIndex", paged.getPageIndex() != null ? Math.max(1, paged.getPageIndex()) : 1);
        emptyResult.put("size", paged.getPageSize() != null ? paged.getPageSize() : 10);
        return emptyResult;
    }

    /**
     * 过滤Machine对象，移除不需要的字段
     */
    private List<Object> filterMachineData(List<?> machineList) {
        List<Object> filteredMachines = new ArrayList<>();
        for (Object obj : machineList) {
            if (obj instanceof Machine) {
                Machine originalMachine = (Machine) obj;
                Machine filteredMachine = new Machine();
                // 只复制需要的字段
                filteredMachine.setId(originalMachine.getId());
                filteredMachine.setName(originalMachine.getName());
                filteredMachine.setEarliestTime(originalMachine.getEarliestTime());
                filteredMachine.setTotalTaskTime(originalMachine.getTotalTaskTime());
                filteredMachine.setCode(originalMachine.getCode());
                filteredMachine.setCapacityTypeName(originalMachine.getCapacityTypeName());
                filteredMachine.setActualWorkTime(originalMachine.getActualWorkTime());
                filteredMachine.setRate(originalMachine.getRate());
                filteredMachine.setDepartment(originalMachine.getDepartment());
                filteredMachine.setShifts(originalMachine.getShifts());
                filteredMachine.setMaintenanceWindows(originalMachine.getMaintenanceWindows());
                // 不设置不需要的字段：shifts, maintenanceWindows, availability, holidays, shiftsChanged, maintenanceWindowsChanged
                filteredMachines.add(filteredMachine);
            } else {
                filteredMachines.add(obj);
            }
        }
        return filteredMachines;
    }

    /**
     * 根据场景ID和实体名称查询Chromosome中的分页数据，带条件过滤
     */
    public Map<String, Object> queryChromosomeDataWithConditions(String sceneId, String entityName, Paged paged) {
        // 对于materialInfo且有sceneId时，在conditions中添加排产物料ID过滤


        if ("materialinfo".equalsIgnoreCase(entityName) && sceneId != null && !sceneId.isEmpty()) {
            boolean hasProductIds = false;
            try {
                // 从文件中加载Chromosome对象
                Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
                if (chromosome != null && chromosome.getResult() != null) {
                    // 从排产结果中提取产品ID列表
                    Set<String> productIds = chromosome.getResult().stream()
                            .map(GAScheduleResult::getProductId)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toSet());

                    if (!productIds.isEmpty()) {
                        // 创建物料ID的IN条件
                        ConditionEntity idCondition = new ConditionEntity();
                        idCondition.setFieldName("id");
                        idCondition.setConditionalType("IN");
                        idCondition.setFieldValue(String.join(",", productIds));

                        // 添加到conditions中
                        if (paged.getConditions() == null) {
                            paged.setConditions(new ArrayList<>());
                        }
                        paged.getConditions().add(idCondition);
                        hasProductIds = true;
                    }
                }
                // 如果没有找到productIds，返回空结果
                if (!hasProductIds) {
                    return createEmptyResult(paged);
                }
            } catch (Exception e) {
                log.error("提取排产物料ID失败，场景ID: " + sceneId, e);
                return createEmptyResult(paged);
            } finally {
                // 无论是否发生异常，都移除原始的sceneId条件
                if (paged.getConditions() != null) {
                    paged.getConditions().removeIf(condition -> "sceneId".equalsIgnoreCase(condition.getFieldName()));
                }
            }


        }

        EntityConfig config = getEntityConfig(entityName);

        if (config.getDataSource() == DataSourceType.FILE) {
            return queryFileDataWithConditions(sceneId, config, paged);
        } else {
            // 数据库查询
            return databaseQueryService.queryDatabaseDataWithConditions(config, paged);
        }
    }

    /**
     * 查询文件数据列表（支持条件过滤）
     */
    public List<Object> queryChromosomeDataList(String sceneId, String entityName, Paged paged) {
        // 对于materialInfo且有sceneId时，在conditions中添加排产物料ID过滤
        if ("materialinfo".equalsIgnoreCase(entityName) && sceneId != null && !sceneId.isEmpty()) {
            boolean hasProductIds = false;
            try {
                // 从文件中加载Chromosome对象
                Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
                if (chromosome != null && chromosome.getResult() != null) {
                    // 从排产结果中提取产品ID列表
                    Set<String> productIds = chromosome.getResult().stream()
                            .map(GAScheduleResult::getProductId)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toSet());

                    if (!productIds.isEmpty()) {
                        // 创建物料ID的IN条件
                        ConditionEntity idCondition = new ConditionEntity();
                        idCondition.setFieldName("id");
                        idCondition.setConditionalType("IN");
                        idCondition.setFieldValue(String.join(",", productIds));

                        // 添加到conditions中
                        if (paged.getConditions() == null) {
                            paged.setConditions(new ArrayList<>());
                        }
                        paged.getConditions().add(idCondition);
                        hasProductIds = true;
                    }
                }
                // 如果没有找到productIds，返回空结果
                if (!hasProductIds) {
                    return Collections.emptyList();
                }
            } catch (Exception e) {
                log.error("提取排产物料ID失败，场景ID: " + sceneId, e);
                return Collections.emptyList();
            } finally {
                // 无论是否发生异常，都移除原始的sceneId条件
                if (paged.getConditions() != null) {
                    paged.getConditions().removeIf(condition -> "sceneId".equalsIgnoreCase(condition.getFieldName()));
                }
            }
        }

        EntityConfig config = getEntityConfig(entityName);

        if (config.getDataSource() == DataSourceType.FILE) {
            // 特殊处理：当实体是MachineOption时，需要先获取Entry列表，再提取符合条件的Entry的MachineOption
            if ("machineoption".equalsIgnoreCase(config.getEntityName())) {
                // 先获取Entry列表（而不是MachineOption列表）
                EntityConfig entryConfig = new EntityConfig();
                entryConfig.setEntityName("entry");
                entryConfig.setDataSource(DataSourceType.FILE);
                entryConfig.setFieldName("allOperations");

                Object entryData = queryFileData(sceneId, entryConfig);

                if (entryData instanceof List) {
                    List<?> entryList = (List<?>) entryData;
                    List<Object> resultEntries = new ArrayList<>();

                    // 先将Entry对象转换为Object对象，方便后续处理
                    for (Object obj : entryList) {
                        if (obj instanceof Entry) {
                            Entry entry = (Entry) obj;
                            // 检查Entry的SceneId是否匹配
                            if (entry.getSceneId() == null || entry.getSceneId().equals(sceneId)) {
                                resultEntries.add(obj);
                            }
                        }
                    }

                    // 应用条件过滤，支持AND/OR关系
                    if (!CollectionUtils.isEmpty(paged.getConditions())) {
                        resultEntries = filterDataByConditions(resultEntries, paged.getConditions(), paged.getAnd());
                    }

                    // 提取符合条件的Entry的MachineOptions
                    List<MachineOption> resultMachineOptions = new ArrayList<>();
                    for (Object obj : resultEntries) {
                        if (obj instanceof Entry) {
                            Entry entry = (Entry) obj;
                            if (entry.getMachineOptions() != null) {
                                resultMachineOptions.addAll(entry.getMachineOptions());
                            }
                        }
                    }

                    List<Object> listResult = (List<Object>) (List<?>) resultMachineOptions;
                    return applyGroupAndFieldsToList(listResult, paged);
                } else {
                    return new ArrayList<>();
                }
            } else if ("ordermaterialrequirement".equalsIgnoreCase(config.getEntityName())) {
                // 特殊处理：当实体是OrderMaterialRequirement时，需要先获取Entry列表，再提取所有Entry的OrderMaterialRequirement
                EntityConfig entryConfig = new EntityConfig();
                entryConfig.setEntityName("entry");
                entryConfig.setDataSource(DataSourceType.FILE);
                entryConfig.setFieldName("allOperations");

                Object entryData = queryFileData(sceneId, entryConfig);

                if (entryData instanceof List) {
                    List<?> entryList = (List<?>) entryData;
                    List<Object> resultEntries = new ArrayList<>();

                    // 先将Entry对象转换为Object对象，方便后续处理
                    for (Object obj : entryList) {
                        if (obj instanceof Entry) {
                            Entry entry = (Entry) obj;
                            // 检查Entry的SceneId是否匹配
                            if (entry.getSceneId() == null || entry.getSceneId().equals(sceneId)) {
                                resultEntries.add(obj);
                            }
                        }
                    }

                    // 提取所有Entry的OrderMaterialRequirement
                    List<Object> resultOrderMaterialRequirements = new ArrayList<>();
                    
                    // 加载Chromosome对象，用于获取基准时间和GAScheduleResult
                    Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
                    if (chromosome != null) {
                        // 构建execId到GAScheduleResult的映射
                        Map<String, GAScheduleResult> execIdToScheduleMap = new HashMap<>();
                        if (chromosome.getResult() != null) {
                            for (GAScheduleResult result : chromosome.getResult()) {
                                if (result.getExecId() != null) {
                                    execIdToScheduleMap.put(result.getExecId(), result);
                                }
                            }
                        }
                        
                        // 获取基准时间
                        LocalDateTime baseTime = chromosome.getBaseTime() != null ? chromosome.getBaseTime() : LocalDateTime.now();
                        
                        for (Object obj : resultEntries) {
                            if (obj instanceof Entry) {
                                Entry entry = (Entry) obj;
                                // 获取该Entry对应的GAScheduleResult
                                GAScheduleResult gaResult = execIdToScheduleMap.get(entry.getExecId());
                                LocalDateTime operationStartTime = null;
                                
                                // 计算工序开始时间
                                if (gaResult != null) {
                                    operationStartTime = baseTime.plusSeconds((long) gaResult.getStartTime());
                                }
                                
                                // 假设Entry类中有getMaterialRequirements方法返回List<OrderMaterialRequirement>
                                // 这里需要根据实际的字段名和方法名进行调整
                                try {
                                    // 使用反射获取Entry对象的MaterialRequirements字段
                                    Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
                                    materialRequirementsField.setAccessible(true);
                                    Object materialRequirementsObj = materialRequirementsField.get(entry);
                                    
                                    if (materialRequirementsObj instanceof List) {
                                        List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                                        // 遍历MaterialRequirements列表，设置shortageTime字段
                                        for (Object reqObj : materialRequirementsList) {
                                            if (reqObj instanceof OrderMaterialRequirement) {
                                                OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
                                                // 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
                                                if (operationStartTime != null) {
                                                    req.setShortageTime(operationStartTime);
                                                }
                                                resultOrderMaterialRequirements.add(req);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    // 如果反射失败，尝试其他可能的字段名
                                    try {
                                        Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
                                        materialRequirementsField.setAccessible(true);
                                        Object materialRequirementsObj = materialRequirementsField.get(entry);
                                        
                                        if (materialRequirementsObj instanceof List) {
                                            List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                                            // 遍历MaterialRequirements列表，设置shortageTime字段
                                            for (Object reqObj : materialRequirementsList) {
                                                if (reqObj instanceof OrderMaterialRequirement) {
                                                    OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
                                                    // 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
                                                    if (operationStartTime != null) {
                                                        req.setShortageTime(operationStartTime);
                                                    }
                                                    resultOrderMaterialRequirements.add(req);
                                                }
                                            }
                                        }
                                    } catch (Exception ex) {
                                        // 如果所有尝试都失败，记录错误并继续
                                        log.error("获取Entry的MaterialRequirements失败", ex);
                                    }
                                }
                            }
                        }
                    } else {
                        // 如果chromosome为null，使用原来的方式处理
                        for (Object obj : resultEntries) {
                            if (obj instanceof Entry) {
                                Entry entry = (Entry) obj;
                                
                                // 假设Entry类中有getMaterialRequirements方法返回List<OrderMaterialRequirement>
                                // 这里需要根据实际的字段名和方法名进行调整
                                try {
                                    // 使用反射获取Entry对象的MaterialRequirements字段
                                    Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
                                    materialRequirementsField.setAccessible(true);
                                    Object materialRequirementsObj = materialRequirementsField.get(entry);
                                    
                                    if (materialRequirementsObj instanceof List) {
                                        List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                                        resultOrderMaterialRequirements.addAll(materialRequirementsList);
                                    }
                                } catch (Exception e) {
                                    // 如果反射失败，尝试其他可能的字段名
                                    try {
                                        Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
                                        materialRequirementsField.setAccessible(true);
                                        Object materialRequirementsObj = materialRequirementsField.get(entry);
                                        
                                        if (materialRequirementsObj instanceof List) {
                                            List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                                            resultOrderMaterialRequirements.addAll(materialRequirementsList);
                                        }
                                    } catch (Exception ex) {
                                        // 如果所有尝试都失败，记录错误并继续
                                        log.error("获取Entry的MaterialRequirements失败", ex);
                                    }
                                }
                            }
                        }
                    }

                    // 应用条件过滤，支持AND/OR关系
                    if (!CollectionUtils.isEmpty(paged.getConditions())) {
                        resultOrderMaterialRequirements = filterDataByConditions(resultOrderMaterialRequirements, paged.getConditions(), paged.getAnd());
                    }

                    // 应用排序
                    List<Object> sortedData = sortData(resultOrderMaterialRequirements, paged);
                    return applyGroupAndFieldsToList(sortedData, paged);
                } else {
                    return new ArrayList<>();
                }
            } else if ("order".equalsIgnoreCase(config.getEntityName())) {
                // 特殊处理：当实体是Order时，使用orderId字段进行查询
                Object data = queryFileData(sceneId, config);

                if (data instanceof List) {
                    List<?> orderList = (List<?>) data;
                    List<Object> resultOrders = new ArrayList<>();

                    // 先将Order对象转换为Object对象，方便后续处理
                    for (Object obj : orderList) {
                        if (obj instanceof Order) {
                            resultOrders.add(obj);
                        }
                    }

                    // 应用条件过滤，支持AND/OR关系
                    if (!CollectionUtils.isEmpty(paged.getConditions())) {
                        resultOrders = filterDataByConditions(resultOrders, paged.getConditions(), paged.getAnd());
                    }

                    // 应用排序
                    List<Object> sortedData = sortData(resultOrders, paged);
                    return applyGroupAndFieldsToList(sortedData, paged);
                } else {
                    return new ArrayList<>();
                }
            } else {
                Object data = queryFileData(sceneId, config);
                List<Object> listResult = applyConditionsToList(data, paged, entityName);
                return applyGroupAndFieldsToList(listResult, paged);
            }
        } else {
            // 数据库查询（已支持 groupName、fields）
            return databaseQueryService.queryDatabaseDataList(config, paged);
        }
    }

    /**
     * List 接口统一应用 groupName、fields：先分组（若有）再投影（若有）。
     */
    private List<Object> applyGroupAndFieldsToList(List<?> dataList, Paged paged) {
        if (dataList == null) {
            return new ArrayList<>();
        }
        List<?> result = new ArrayList<>(dataList);
        if (paged.getGroupName() != null && !paged.getGroupName().trim().isEmpty()) {
            result = groupListByFields(result, paged.getGroupName());
        }
        if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) {
            result = projectListToFields(result, paged.getFields());
        }
        // 应用分页
        if (paged.getPageIndex() != null && paged.getPageSize() != null && paged.getPageSize() > 0) {
            int pageIndex = Math.max(1, paged.getPageIndex());
            int pageSize = paged.getPageSize();
            int start = (pageIndex - 1) * pageSize;
            int end = Math.min(start + pageSize, result.size());
            if (start >= result.size()) {
                return new ArrayList<>();
            }
            result = result.subList(start, end);
        }
        // 格式化时间字段
        List<Object> formattedResult = new ArrayList<>();
        for (Object item : result) {
            formattedResult.add(formatFileEntityTimeFields(item));
        }
        return formattedResult;
    }

    /**
     * 格式化文件实体的时间字段
     * @param data 要格式化的数据
     * @return 格式化后的数据
     */
    private Object formatFileEntityTimeFields(Object data) {
        if (data == null) {
            return null;
        }

        // 处理Map类型的对象（如分组结果）
        if (data instanceof Map) {
            Map<?, ?> originalMap = (Map<?, ?>) data;
            Map<String, Object> formattedMap = new LinkedHashMap<>();
            
            for (Map.Entry<?, ?> entry : originalMap.entrySet()) {
                String key = entry.getKey().toString();
                Object value = entry.getValue();
                
                // 检查值是否是时间类型
                if (value instanceof LocalDateTime) {
                    LocalDateTime dateTime = (LocalDateTime) value;
                    formattedMap.put(key, formatFrontendUtcDateTime(dateTime));
                } else {
                    formattedMap.put(key, value);
                }
            }
            
            return formattedMap;
        }

        // 处理普通实体类对象
        // 为了简化，我们返回一个包含格式化时间的Map
        Map<String, Object> formattedData = new LinkedHashMap<>();
        
        // 获取对象的所有字段（包括父类字段）
        List<Field> fields = new ArrayList<>();
        Class<?> currentClass = data.getClass();
        while (currentClass != null && currentClass != Object.class) {
            fields.addAll(Arrays.asList(currentClass.getDeclaredFields()));
            currentClass = currentClass.getSuperclass();
        }
        
        // 遍历所有字段
        for (Field field : fields) {
            // 跳过静态字段，避免反射访问权限错误
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            
            field.setAccessible(true);
            try {
                Object value = field.get(data);
                // 检查是否是时间类型字段
                if (value instanceof LocalDateTime) {
                    LocalDateTime dateTime = (LocalDateTime) value;
                    formattedData.put(field.getName(), formatFrontendUtcDateTime(dateTime));
                } else {
                    // 对于String类型字段，如果值为null，设置为空字符串
                    if (value == null && field.getType() == String.class) {
                        formattedData.put(field.getName(), "");
                    } else {
                        formattedData.put(field.getName(), value);
                    }
                }
            } catch (Exception e) {
                // 忽略字段访问错误
            }
        }
        
        return formattedData;
    }

    private String formatFrontendUtcDateTime(LocalDateTime dateTime) {
        return dateTime == null ? null : dateTime.format(FRONTEND_UTC_MILLIS_FORMATTER);
    }

    /**
     * 处理materialInfo实体的特殊查询逻辑
     */
    private boolean handleMaterialInfoQuery(String sceneId, Paged paged) {
        boolean hasProductIds = false;
        try {
            // 从文件中加载Chromosome对象
            Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
            if (chromosome != null && chromosome.getResult() != null) {
                // 从排产结果中提取产品ID列表
                Set<String> productIds = chromosome.getResult().stream()
                        .map(GAScheduleResult::getProductId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toSet());

                if (!productIds.isEmpty()) {
                    // 创建物料ID的IN条件
                    ConditionEntity idCondition = new ConditionEntity();
                    idCondition.setFieldName("id");
                    idCondition.setConditionalType("IN");
                    idCondition.setFieldValue(String.join(",", productIds));

                    // 添加到conditions中
                    if (paged.getConditions() == null) {
                        paged.setConditions(new ArrayList<>());
                    }
                    paged.getConditions().add(idCondition);
                    hasProductIds = true;
                }
            }
        } catch (Exception e) {
            log.error("提取排产物料ID失败，场景ID: " + sceneId, e);
            hasProductIds = false;
        } finally {
            // 无论是否发生异常，都移除原始的sceneId条件
            if (paged.getConditions() != null) {
                paged.getConditions().removeIf(condition -> "sceneId".equalsIgnoreCase(condition.getFieldName()));
            }
        }
        return hasProductIds;
    }


    /**
     * 从Entry列表中提取OrderMaterialRequirement
     */
    private List<Object> extractOrderMaterialRequirements(String sceneId, List<Object> resultEntries) {
        List<Object> resultOrderMaterialRequirements = new ArrayList<>();
        
        // 加载Chromosome对象，用于获取基准时间和GAScheduleResult
        Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
        if (chromosome != null) {
            // 构建execId到GAScheduleResult的映射
            Map<String, GAScheduleResult> execIdToScheduleMap = new HashMap<>();
            if (chromosome.getResult() != null) {
                for (GAScheduleResult result : chromosome.getResult()) {
                    if (result.getExecId() != null) {
                        execIdToScheduleMap.put(result.getExecId(), result);
                    }
                }
            }
            
            // 获取基准时间
            LocalDateTime baseTime = chromosome.getBaseTime() != null ? chromosome.getBaseTime() : LocalDateTime.now();
            
            for (Object obj : resultEntries) {
                if (obj instanceof Entry) {
                    Entry entry = (Entry) obj;
                    extractMaterialRequirementsWithTime(entry, execIdToScheduleMap, baseTime, resultOrderMaterialRequirements);
                }
            }
        } else {
            // 如果chromosome为null，使用原来的方式处理
            for (Object obj : resultEntries) {
                if (obj instanceof Entry) {
                    Entry entry = (Entry) obj;
                    extractMaterialRequirements(entry, resultOrderMaterialRequirements);
                }
            }
        }
        return resultOrderMaterialRequirements;
    }

    /**
     * 提取带时间信息的物料需求
     */
    private void extractMaterialRequirementsWithTime(Entry entry, Map<String, GAScheduleResult> execIdToScheduleMap, 
                                                   LocalDateTime baseTime, List<Object> resultList) {
        // 获取该Entry对应的GAScheduleResult
        GAScheduleResult gaResult = execIdToScheduleMap.get(entry.getExecId());
        LocalDateTime operationStartTime = null;
        
        // 计算工序开始时间
        if (gaResult != null) {
            operationStartTime = baseTime.plusSeconds((long) gaResult.getStartTime());
        }
        
        // 尝试获取Entry对象的MaterialRequirements字段
        try {
            // 使用反射获取Entry对象的MaterialRequirements字段
            Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
            materialRequirementsField.setAccessible(true);
            Object materialRequirementsObj = materialRequirementsField.get(entry);
            
            if (materialRequirementsObj instanceof List) {
                List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                // 遍历MaterialRequirements列表，设置shortageTime字段
                for (Object reqObj : materialRequirementsList) {
                    if (reqObj instanceof OrderMaterialRequirement) {
                        OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
                        // 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
                        if (operationStartTime != null) {
                            req.setShortageTime(operationStartTime);
                        }
                        resultList.add(req);
                    }
                }
            }
        } catch (Exception e) {
            // 如果反射失败，尝试其他可能的字段名
            try {
                Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
                materialRequirementsField.setAccessible(true);
                Object materialRequirementsObj = materialRequirementsField.get(entry);
                
                if (materialRequirementsObj instanceof List) {
                    List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                    // 遍历MaterialRequirements列表，设置shortageTime字段
                    for (Object reqObj : materialRequirementsList) {
                        if (reqObj instanceof OrderMaterialRequirement) {
                            OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
                            // 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
                            if (operationStartTime != null) {
                                req.setShortageTime(operationStartTime);
                            }
                            resultList.add(req);
                        }
                    }
                }
            } catch (Exception ex) {
                // 如果所有尝试都失败，记录错误并继续
                log.error("获取Entry的MaterialRequirements失败", ex);
            }
        }
    }

    /**
     * 提取物料需求（不包含时间信息）
     */
    private void extractMaterialRequirements(Entry entry, List<Object> resultList) {
        // 尝试获取Entry对象的MaterialRequirements字段
        try {
            // 使用反射获取Entry对象的MaterialRequirements字段
            Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
            materialRequirementsField.setAccessible(true);
            Object materialRequirementsObj = materialRequirementsField.get(entry);
            
            if (materialRequirementsObj instanceof List) {
                List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                resultList.addAll(materialRequirementsList);
            }
        } catch (Exception e) {
            // 如果反射失败，尝试其他可能的字段名
            try {
                Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
                materialRequirementsField.setAccessible(true);
                Object materialRequirementsObj = materialRequirementsField.get(entry);
                
                if (materialRequirementsObj instanceof List) {
                    List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                    resultList.addAll(materialRequirementsList);
                }
            } catch (Exception ex) {
                // 如果所有尝试都失败，记录错误并继续
                log.error("获取Entry的MaterialRequirements失败", ex);
            }
        }
    }


    /**
     * 根据ID查询单条数据
     */
    public Object queryChromosomeDataById(String sceneId, String entityName, String id) {
        // 对于materialInfo且有sceneId时，从排产结果中检查
        if ("materialinfo".equalsIgnoreCase(entityName) && sceneId != null && !sceneId.isEmpty()) {
            try {
                // 1. 从文件中加载Chromosome对象
                Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
                if (chromosome == null || chromosome.getResult() == null) {
                    return null;
                }

                // 2. 检查该ID是否在排产结果中
                boolean isScheduled = chromosome.getResult().stream()
                        .anyMatch(result -> id.equals(result.getProductId()));

                if (!isScheduled) {
                    return null;
                }
            } catch (Exception e) {
                log.error("检查排产物料失败，场景ID: " + sceneId + ", 物料ID: " + id, e);
                return null;
            }
        }

        EntityConfig config = getEntityConfig(entityName);

        if (config.getDataSource() == DataSourceType.FILE) {
            return queryFileDataById(sceneId, config, id);
        } else {
            // 数据库查询
            return databaseQueryService.queryDatabaseDataById(config, id);
        }
    }

    /**
     * 获取实体配置（智能默认）
     */
    private EntityConfig getEntityConfig(String entityName) {
        if (entityName == null || entityName.isEmpty()) {
            throw new RuntimeException("实体名称不能为空");
        }

        String key = entityName.toLowerCase();
        EntityConfig config = entityConfigMap.get(key);

        if (config == null) {
            // 特殊处理：当实体是ProdProcessExec时，映射到allOperations字段
            if ("prodprocessexec".equalsIgnoreCase(key)) {
                config = new EntityConfig();
                config.setEntityName(entityName);
                config.setDataSource(DataSourceType.FILE);
                config.setFieldName("allOperations");
            }
            // 特殊处理：当实体是MachineOption时，映射到allOperations字段
            else if ("machineoption".equalsIgnoreCase(key)) {
                config = new EntityConfig();
                config.setEntityName(entityName);
                config.setDataSource(DataSourceType.FILE);
                config.setFieldName("allOperations");
            }
            // 特殊处理：当实体是OrderMaterialRequirement时，映射到allOperations字段
            else if ("ordermaterialrequirement".equalsIgnoreCase(key)) {
                config = new EntityConfig();
                config.setEntityName(entityName);
                config.setDataSource(DataSourceType.FILE);
                config.setFieldName("allOperations");
            }
            // 特殊处理：当实体是KpiMetrics时，映射到kpiMetrics字段
            else if ("kpimetrics".equalsIgnoreCase(key)) {
                config = new EntityConfig();
                config.setEntityName(entityName);
                config.setDataSource(DataSourceType.FILE);
                config.setFieldName("kpiMetrics");
            }
            // 特殊处理：当实体是Machine时，映射到Machines字段
            else if ("machine".equalsIgnoreCase(key)) {
                config = new EntityConfig();
                config.setEntityName(entityName);
                config.setDataSource(DataSourceType.FILE);
                config.setFieldName("Machines");
            }
            // 特殊处理：当实体是Order时，映射到orders字段
            else if ("order".equalsIgnoreCase(key)) {
                config = new EntityConfig();
                config.setEntityName(entityName);
                config.setDataSource(DataSourceType.FILE);
                config.setFieldName("orders");
            }
            // 特殊处理：当实体是Task时，取资源甘特图中的TaskVO列表。
            else if ("task".equalsIgnoreCase(key)) {
                config = new EntityConfig();
                config.setEntityName(entityName);
                config.setDataSource(DataSourceType.FILE);
                config.setFieldName("task");
            } else {
                // 自动创建数据库配置（默认行为）
                config = createDefaultDbConfig(entityName);
                System.out.println(config.getTableName()
                );
            }
            // 缓存这个自动创建的配置
            entityConfigMap.put(key, config);
        }

        return config;
    }
//





    private EntityConfig createDefaultDbConfig(String entityName) {
        EntityConfig config = new EntityConfig();
        config.setEntityName(entityName);
        config.setDataSource(DataSourceType.DATABASE);

        // 智能表名映射
        String tableName = mapEntityNameToTableName(entityName);

        System.out.println("智能表名映射：" + entityName + " -> " + tableName);
        config.setTableName(tableName);

        // 尝试设置对应的实体类
        try {
            // 特殊处理：materialInfo 映射到 MaterialInfo
            if ("materialinfo".equalsIgnoreCase(entityName)) {
                config.setEntityClass(MaterialInfo.class);
            } else {
                // 假设实体类都在 com.aps.entity 包下
                String entityClassName = "com.aps.entity." + entityName.substring(0, 1).toUpperCase() + entityName.substring(1);
                Class<?> entityClass = Class.forName(entityClassName);
                config.setEntityClass(entityClass);
            }
        } catch (ClassNotFoundException e) {
            // 如果没有对应的实体类，设置为null，查询返回Map
            config.setEntityClass(null);
        }

        return config;
    }

    /**
     * 将实体名映射为数据库表名
     * 规则：ProdProduct -> PROD_PRODUCT
     */
    private String mapEntityNameToTableName(String entityName) {
        if (entityName == null || entityName.isEmpty()) {
            return entityName;
        }

        // 处理常见的命名约定
        String[] commonPrefixes = {"Prod", "Sys", "Tbl", "Tab", "Biz"};
        String processedName = entityName;

        // 检查是否有常见前缀
        for (String prefix : commonPrefixes) {
            if (entityName.startsWith(prefix) && entityName.length() > prefix.length()) {
                // 保留前缀，如ProdProduct -> PROD_PRODUCT
                break;
            }
        }

        // 驼峰命名转下划线大写
        return camelCaseToUnderScoreUpperCase(processedName);
    }

    /**
     * 查询文件数据
     */
    private Object queryFileData(String sceneId, EntityConfig config) {
        SceneChromsome sceneChromsome = sceneService.getSceneChromsome(sceneId);
        String versionTag = sceneChromsome != null && sceneChromsome.getVersion() != null
                ? sceneChromsome.getVersion().toString()
                : "base";

        // 生成缓存键（包含版本号，避免读取到旧场景缓存）
        String cacheKey = sceneId + ":" + versionTag + ":" + config.getEntityName() + ":" + config.getFieldName();
        
        // 先从缓存中获取
        Object cachedData = fileDataCache.get(cacheKey);
        if (cachedData != null) {
            return cachedData;
        }
        
        Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
        if (chromosome == null) {
            return null;
        }

        try {
            if ("task".equalsIgnoreCase(config.getEntityName())) {
                Object result = extractResourceGanttTasks(chromosome);
                fileDataCache.put(cacheKey, result);
                return result;
            }

            String fieldName = config.getFieldName();

            // 特殊处理：当实体是MachineOption时，使用allOperations字段
            if ("machineoption".equalsIgnoreCase(config.getEntityName())) {
                fieldName = "allOperations";
            }

            // 从缓存中获取反射字段
            Field field = getCachedField(Chromosome.class, fieldName);
            Object result = field.get(chromosome);

            // 如果实体是MachineOption，提取Entry中的MachineOption列表
            if ("machineoption".equalsIgnoreCase(config.getEntityName())) {
                result = extractMachineOptionsFromEntries(result);
            }

            // 缓存结果
            fileDataCache.put(cacheKey, result);

            return result;
        } catch (NoSuchFieldException e) {
            throw new RuntimeException("Chromosome类中未找到字段: " + config.getFieldName(), e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("访问Chromosome字段失败: " + e.getMessage(), e);
        }
    }

    private List<TaskVO> extractResourceGanttTasks(Chromosome chromosome) {
        if (chromosome == null) {
            return new ArrayList<>();
        }
        List<Machine> machineList = planResultService.InitCalendarToAllMachines3(chromosome);
        List<ResourceGanttVO> resourceGanttVOs = planResultService.convertToResourceGanttVO1(chromosome, machineList);
        if (resourceGanttVOs == null || resourceGanttVOs.isEmpty()) {
            return new ArrayList<>();
        }
        return resourceGanttVOs.stream()
                .filter(Objects::nonNull)
                .filter(vo -> vo.getList() != null)
                .flatMap(vo -> vo.getList().stream())
                .collect(Collectors.toList());
    }
    
    /**
     * 从缓存中获取反射字段，避免重复反射操作
     */
    private Field getCachedField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
        Map<String, Field> classFields = fieldCache.computeIfAbsent(clazz, k -> new HashMap<>());
        Field field = classFields.get(fieldName);
        if (field == null) {
            field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            classFields.put(fieldName, field);
        }
        return field;
    }

    /**
     * 查询文件数据（分页+条件）
     */
    private Map<String, Object> queryFileDataWithConditions(String sceneId, EntityConfig config, Paged paged) {
        Object data;

        // 特殊处理：当实体是MachineOption时，需要先获取Entry列表，再提取符合条件的Entry的MachineOption
        if ("machineoption".equalsIgnoreCase(config.getEntityName())) {
            // 先获取Entry列表（而不是MachineOption列表）
            EntityConfig entryConfig = new EntityConfig();
            entryConfig.setEntityName("entry");
            entryConfig.setDataSource(DataSourceType.FILE);
            entryConfig.setFieldName("allOperations");

            Object entryData = queryFileData(sceneId, entryConfig);

            if (entryData instanceof List) {
                List<?> entryList = (List<?>) entryData;
                List<Object> resultEntries = new ArrayList<>();

                // 先将Entry对象转换为Object对象，方便后续处理
                for (Object obj : entryList) {
                    if (obj instanceof Entry) {
                        Entry entry = (Entry) obj;
                        // 检查Entry的SceneId是否匹配
                        if (entry.getSceneId() == null || entry.getSceneId().equals(sceneId)) {
                            resultEntries.add(obj);
                        }
                    }
                }

                // 应用条件过滤，支持AND/OR关系
                if (!CollectionUtils.isEmpty(paged.getConditions())) {
                    resultEntries = filterDataByConditions(resultEntries, paged.getConditions(), paged.getAnd());
                }

                // 提取符合条件的Entry的MachineOptions
                List<MachineOption> resultMachineOptions = new ArrayList<>();
                for (Object obj : resultEntries) {
                    if (obj instanceof Entry) {
                        Entry entry = (Entry) obj;
                        if (entry.getMachineOptions() != null) {
                            resultMachineOptions.addAll(entry.getMachineOptions());
                        }
                    }
                }

                data = resultMachineOptions;
            } else {
                data = new ArrayList<MachineOption>();
            }
        } else if ("order".equalsIgnoreCase(config.getEntityName())) {
            // 特殊处理：当实体是Order时，使用orderId字段进行查询
            Object orderData = queryFileData(sceneId, config);

            if (orderData instanceof List) {
                List<?> orderList = (List<?>) orderData;
                List<Object> resultOrders = new ArrayList<>();

                // 先将Order对象转换为Object对象，方便后续处理
                for (Object obj : orderList) {
                    if (obj instanceof Order) {
                        resultOrders.add(obj);
                    }
                }

                // 应用条件过滤，支持AND/OR关系
                if (!CollectionUtils.isEmpty(paged.getConditions())) {
                    resultOrders = filterDataByConditions(resultOrders, paged.getConditions(), paged.getAnd());
                }

                // 应用排序
                List<Object> sortedData = sortData(resultOrders, paged);
                data = sortedData;
            } else {
                data = new ArrayList<Order>();
            }
        } else if ("ordermaterialrequirement".equalsIgnoreCase(config.getEntityName())) {
            // 特殊处理：当实体是OrderMaterialRequirement时，需要先获取Entry列表，再提取所有Entry的OrderMaterialRequirement
            EntityConfig entryConfig = new EntityConfig();
            entryConfig.setEntityName("entry");
            entryConfig.setDataSource(DataSourceType.FILE);
            entryConfig.setFieldName("allOperations");

            Object entryData = queryFileData(sceneId, entryConfig);

            if (entryData instanceof List) {
                List<?> entryList = (List<?>) entryData;
                List<Object> resultEntries = new ArrayList<>();

                // 先将Entry对象转换为Object对象，方便后续处理
                for (Object obj : entryList) {
                    if (obj instanceof Entry) {
                        Entry entry = (Entry) obj;
                        // 检查Entry的SceneId是否匹配
                        if (entry.getSceneId() == null || entry.getSceneId().equals(sceneId)) {
                            resultEntries.add(obj);
                        }
                    }
                }

                // 提取所有Entry的OrderMaterialRequirement
                List<Object> resultOrderMaterialRequirements = new ArrayList<>();
                
                // 加载Chromosome对象，用于获取基准时间和GAScheduleResult
                Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
                if (chromosome != null) {
                    // 构建execId到GAScheduleResult的映射
                    Map<String, GAScheduleResult> execIdToScheduleMap = new HashMap<>();
                    if (chromosome.getResult() != null) {
                        for (GAScheduleResult result : chromosome.getResult()) {
                            if (result.getExecId() != null) {
                                execIdToScheduleMap.put(result.getExecId(), result);
                            }
                        }
                    }
                    
                    // 获取基准时间
                    LocalDateTime baseTime = chromosome.getBaseTime() != null ? chromosome.getBaseTime() : LocalDateTime.now();
                    
                    for (Object obj : resultEntries) {
                        if (obj instanceof Entry) {
                            Entry entry = (Entry) obj;
                            // 获取该Entry对应的GAScheduleResult
                            GAScheduleResult gaResult = execIdToScheduleMap.get(entry.getExecId());
                            LocalDateTime operationStartTime = null;
                            
                            // 计算工序开始时间
                            if (gaResult != null) {
                                operationStartTime = baseTime.plusSeconds((long) gaResult.getStartTime());
                            }
                            
                            // 假设Entry类中有getMaterialRequirements方法返回List<OrderMaterialRequirement>
                            // 这里需要根据实际的字段名和方法名进行调整
                            try {
                                // 使用反射获取Entry对象的MaterialRequirements字段
                                Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
                                materialRequirementsField.setAccessible(true);
                                Object materialRequirementsObj = materialRequirementsField.get(entry);
                                
                                if (materialRequirementsObj instanceof List) {
                                    List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                                    // 遍历MaterialRequirements列表，设置shortageTime字段
                                    for (Object reqObj : materialRequirementsList) {
                                        if (reqObj instanceof OrderMaterialRequirement) {
                                            OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
                                            // 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
                                            if (operationStartTime != null) {
                                                req.setShortageTime(operationStartTime);
                                            }
                                            resultOrderMaterialRequirements.add(req);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                // 如果反射失败，尝试其他可能的字段名
                                try {
                                    Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
                                    materialRequirementsField.setAccessible(true);
                                    Object materialRequirementsObj = materialRequirementsField.get(entry);
                                    
                                    if (materialRequirementsObj instanceof List) {
                                        List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                                        // 遍历MaterialRequirements列表，设置shortageTime字段
                                        for (Object reqObj : materialRequirementsList) {
                                            if (reqObj instanceof OrderMaterialRequirement) {
                                                OrderMaterialRequirement req = (OrderMaterialRequirement) reqObj;
                                                // 将计算出的工序开始时间设置为OrderMaterialRequirement的shortageTime
                                                if (operationStartTime != null) {
                                                    req.setShortageTime(operationStartTime);
                                                }
                                                resultOrderMaterialRequirements.add(req);
                                            }
                                        }
                                    }
                                } catch (Exception ex) {
                                    // 如果所有尝试都失败，记录错误并继续
                                    log.error("获取Entry的MaterialRequirements失败", ex);
                                }
                            }
                        }
                    }
                } else {
                    // 如果chromosome为null，使用原来的方式处理
                    for (Object obj : resultEntries) {
                        if (obj instanceof Entry) {
                            Entry entry = (Entry) obj;
                            
                            // 假设Entry类中有getMaterialRequirements方法返回List<OrderMaterialRequirement>
                            // 这里需要根据实际的字段名和方法名进行调整
                            try {
                                // 使用反射获取Entry对象的MaterialRequirements字段
                                Field materialRequirementsField = Entry.class.getDeclaredField("MaterialRequirements");
                                materialRequirementsField.setAccessible(true);
                                Object materialRequirementsObj = materialRequirementsField.get(entry);
                                
                                if (materialRequirementsObj instanceof List) {
                                    List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                                    resultOrderMaterialRequirements.addAll(materialRequirementsList);
                                }
                            } catch (Exception e) {
                                // 如果反射失败，尝试其他可能的字段名
                                try {
                                    Field materialRequirementsField = Entry.class.getDeclaredField("materialRequirements");
                                    materialRequirementsField.setAccessible(true);
                                    Object materialRequirementsObj = materialRequirementsField.get(entry);
                                    
                                    if (materialRequirementsObj instanceof List) {
                                        List<?> materialRequirementsList = (List<?>) materialRequirementsObj;
                                        resultOrderMaterialRequirements.addAll(materialRequirementsList);
                                    }
                                } catch (Exception ex) {
                                    // 如果所有尝试都失败，记录错误并继续
                                    log.error("获取Entry的MaterialRequirements失败", ex);
                                }
                            }
                        }
                    }
                }

                // 应用条件过滤，支持AND/OR关系
                if (!CollectionUtils.isEmpty(paged.getConditions())) {
                    resultOrderMaterialRequirements = filterDataByConditions(resultOrderMaterialRequirements, paged.getConditions(), paged.getAnd());
                }

                // 应用排序
                List<Object> sortedData = sortData(resultOrderMaterialRequirements, paged);
                data = sortedData;
            } else {
                data = new ArrayList<Object>();
            }
        } else {
            data = queryFileData(sceneId, config);

            if (data instanceof List) {
                List<?> dataList = (List<?>) data;

                // 应用条件过滤
                if (!CollectionUtils.isEmpty(paged.getConditions())) {
                    dataList = filterDataByConditions(dataList, paged.getConditions(), paged.getAnd());
                }

                // 应用排序
                List<Object> sortedData = sortData(dataList, paged);

                // 特殊处理：当实体是Machine时，过滤不需要的字段
                if ("machine".equalsIgnoreCase(config.getEntityName())) {
                    sortedData = filterMachineData(sortedData);
                }

                data = sortedData;
            }
        }

        Map<String, Object> result = new HashMap<>();
        int page = paged.getPageIndex() != null ? Math.max(1, paged.getPageIndex()) : 1;
        int size = paged.getPageSize() != null ? paged.getPageSize() : 10;

        if (data instanceof List) {
            List<?> dataList = (List<?>) data;
            if (paged.getGroupName() != null && !paged.getGroupName().trim().isEmpty()) {
                dataList = groupListByFields(dataList, paged.getGroupName());
                // 确保分组结果根据count倒序排序
                if (dataList instanceof List) {
                    ((List<?>) dataList).sort((o1, o2) -> {
                        if (o1 instanceof Map && o2 instanceof Map) {
                            Map<?, ?> m1 = (Map<?, ?>) o1;
                            Map<?, ?> m2 = (Map<?, ?>) o2;
                            Object count1 = m1.get("count");
                            Object count2 = m2.get("count");
                            if (count1 instanceof Number && count2 instanceof Number) {
                                return ((Number) count2).longValue() - ((Number) count1).longValue() > 0 ? 1 : -1;
                            }
                        }
                        return 0;
                    });
                }
            }
            if (paged.getFields() != null && !paged.getFields().trim().isEmpty()) {
                dataList = projectListToFields(dataList, paged.getFields());
            }

            int total = dataList.size();
            int fromIndex = (page - 1) * size;
            fromIndex = Math.min(fromIndex, total);
            int toIndex = Math.min(fromIndex + size, total);

            List<?> pagedData = dataList.subList(fromIndex, toIndex);

            // 格式化时间字段
            List<Object> formattedPagedData = new ArrayList<>();
            for (Object item : pagedData) {
                formattedPagedData.add(formatFileEntityTimeFields(item));
            }

            result.put("records", formattedPagedData);
            result.put("totalCount", total);
            result.put("pageIndex", page);
            result.put("size", size);
        } else if (data == null) {
            result.put("records", Collections.emptyList());
            result.put("totalCount", 0);
            result.put("pageIndex", page);
            result.put("size", size);
        } else {
            result.put("records", data);
            result.put("totalCount", 1);
            result.put("pageIndex", 1);
            result.put("size", 1);
        }

        return result;
    }

    /**
     * 过滤单个Machine对象，移除不需要的字段
     */
    private Object filterSingleMachineData(Object machineObj) {
        if (machineObj instanceof Machine) {
            Machine originalMachine = (Machine) machineObj;
            Machine filteredMachine = new Machine();
            // 只复制需要的字段
            filteredMachine.setId(originalMachine.getId());
            filteredMachine.setName(originalMachine.getName());
            filteredMachine.setEarliestTime(originalMachine.getEarliestTime());
            filteredMachine.setTotalTaskTime(originalMachine.getTotalTaskTime());
            filteredMachine.setCode(originalMachine.getCode());
            filteredMachine.setCapacityTypeName(originalMachine.getCapacityTypeName());
            filteredMachine.setActualWorkTime(originalMachine.getActualWorkTime());
            filteredMachine.setRate(originalMachine.getRate());
            filteredMachine.setDepartment(originalMachine.getDepartment());
            filteredMachine.setShifts(originalMachine.getShifts());
            filteredMachine.setMaintenanceWindows(originalMachine.getMaintenanceWindows());
            // 不设置不需要的字段：shifts, maintenanceWindows, availability, holidays, shiftsChanged, maintenanceWindowsChanged
            return filteredMachine;
        }
        return machineObj;
    }

    /**
     * 根据ID查询文件数据
     */
    private Object queryFileDataById(String sceneId, EntityConfig config, String id) {
        // 特殊处理：当实体是MachineOption时，需要先获取Entry列表，再提取特定Entry的MachineOption
        if ("machineoption".equalsIgnoreCase(config.getEntityName())) {
            // 先获取Entry列表（而不是MachineOption列表）
            EntityConfig entryConfig = new EntityConfig();
            entryConfig.setEntityName("entry");
            entryConfig.setDataSource(DataSourceType.FILE);
            entryConfig.setFieldName("allOperations");

            Object result = queryFileData(sceneId, entryConfig);

            if (result instanceof List) {
                List<?> entryList = (List<?>) result;
                // 查找ID匹配的Entry
                for (Object obj : entryList) {
                    if (obj instanceof Entry) {
                        Entry entry = (Entry) obj;
                        // 检查Entry的SceneId是否匹配（如果Entry中有SceneId的话）
                        if (entry.getSceneId() != null && !entry.getSceneId().equals(sceneId)) {
                            continue; // 跳过不属于当前场景的Entry
                        }
                        // 检查Entry的ID是否匹配
                        if (String.valueOf(entry.getId()).equals(id)) {
                            // 如果ID匹配，返回该Entry的MachineOptions
                            return entry.getMachineOptions() != null ? entry.getMachineOptions() : new ArrayList<>();
                        }
                    }
                }
            }
            return null; // 找不到数据时返回null而不是抛出异常
        }

        Object result = queryFileData(sceneId, config);

        // 如果结果是List类型，则根据ID查找特定项
        if (result instanceof List) {
            List<Object> dataList = (List<Object>) result;
            Object item = dataList.stream()
                    .filter(obj -> {
                        try {
                            // 尝试获取对象的id字段（兼容大小写）
                            Field idField = getFieldIgnoreCase(obj.getClass(), "id");
                            if (idField != null) {
                                idField.setAccessible(true);
                                Object itemId = idField.get(obj);
                                return itemId != null && itemId.toString().equals(id);
                            }
                            return false;
                        } catch (Exception e) {
                            return false;
                        }
                    })
                    .findFirst()
                    .orElse(null);

            if (item != null) {
                // 特殊处理：当实体是Machine时，过滤不需要的字段
                if ("machine".equalsIgnoreCase(config.getEntityName())) {
                    item = filterSingleMachineData(item);
                }
                // 格式化时间字段
                return formatFileEntityTimeFields(item);
            } else {
                return null; // 找不到数据时返回null而不是抛出异常
            }
        } else {
            // 如果不是列表，直接返回结果
            // 特殊处理：当实体是Machine时，过滤不需要的字段
            if ("machine".equalsIgnoreCase(config.getEntityName())) {
                result = filterSingleMachineData(result);
            }
            // 格式化时间字段
            return formatFileEntityTimeFields(result);
        }
    }

    /**
     * 忽略大小写获取字段
     */
    private Field getFieldIgnoreCase(Class<?> clazz, String fieldName) {
        // 遍历所有声明的字段，查找忽略大小写匹配的字段
        for (Field field : clazz.getDeclaredFields()) {
            if (field.getName().equalsIgnoreCase(fieldName)) {
                return field;
            }
        }
        // 如果当前类没有找到，递归查找父类
        if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) {
            return getFieldIgnoreCase(clazz.getSuperclass(), fieldName);
        }
        return null;
    }

    /**
     * 将数据应用条件过滤并返回列表
     */
    private List<Object> applyConditionsToList(Object data, Paged paged, String entityName) {
        // 检查是否是直接传入的EntityConfig（这种情况可能需要获取场景ID和实体类型）
        // 实际上这个方法是在queryChromosomeDataList中调用的，此时数据已经从文件中获取

        if (data == null) {
            return new ArrayList<>();
        }

        if (data instanceof List) {
            List<Object> dataList = (List<Object>) data;

            // 应用条件过滤
            if (!CollectionUtils.isEmpty(paged.getConditions())) {
                dataList = filterDataByConditions(dataList, paged.getConditions(), paged.getAnd());
            }

            // 应用排序
            dataList = sortData(dataList, paged);

            // 特殊处理：当实体是Machine时，过滤不需要的字段
            if ("machine".equalsIgnoreCase(entityName)) {
                dataList = filterMachineData(dataList);
            }

            return dataList;
        } else {
            List<Object> resultList = new ArrayList<>();
            resultList.add(data);

            // 特殊处理：当实体是Machine时，过滤不需要的字段
            if ("machine".equalsIgnoreCase(entityName) && data instanceof Machine) {
                resultList = filterMachineData(resultList);
            }

            return resultList;
        }
    }

    /**
     * 按 fields 只保留指定字段，返回 List<Map>，每个 Map 仅含 fields 中的列（key 小写）。
     * fields 格式如 "id,name"；若项已是 Map 则按 key 过滤，否则按实体反射取字段值。
     */
    private List<Object> projectListToFields(List<?> dataList, String fields) {
        if (CollectionUtils.isEmpty(dataList) || fields == null || fields.trim().isEmpty()) {
            return new ArrayList<>(dataList);
        }
        List<String> fieldNames = Arrays.stream(fields.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
        if (fieldNames.isEmpty()) {
            return new ArrayList<>(dataList);
        }
        List<Object> result = new ArrayList<>();
        for (Object item : dataList) {
            Map<String, Object> row = new LinkedHashMap<>();
            if (item instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> m = (Map<String, Object>) item;
                for (String fn : fieldNames) {
                    Object val = null;
                    for (Map.Entry<String, Object> e : m.entrySet()) {
                        if (e.getKey() != null && e.getKey().equalsIgnoreCase(fn)) {
                            val = e.getValue();
                            break;
                        }
                    }
                    row.put(fn, val);
                }
            } else {
                try {
                    for (String fn : fieldNames) {
                        Field field = getFieldIgnoreCase(item.getClass(), fn);
                        if (field != null) {
                            field.setAccessible(true);
                            row.put(fn, field.get(item));
                        }
                    }
                } catch (Exception e) {
                    log.warn("投影字段失败 fields={}", fieldNames, e);
                }
            }
            result.add(row);
        }
        return result;
    }

    /**
     * 按 groupName 对列表做内存分组，返回分组列 + count（每组条数）。
     * groupName 格式如 "id,name"，返回 List<Map>，每个 Map 含分组字段（小写 key）+ "count"。
     */
    private List<Object> groupListByFields(List<?> dataList, String groupName) {
        if (CollectionUtils.isEmpty(dataList) || groupName == null || groupName.trim().isEmpty()) {
            return new ArrayList<>(dataList);
        }
        List<String> fieldNames = Arrays.stream(groupName.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
        if (fieldNames.isEmpty()) {
            return new ArrayList<>(dataList);
        }

        Map<String, Long> countByKey = new LinkedHashMap<>();
        List<List<Object>> keyOrder = new ArrayList<>();

        for (Object item : dataList) {
            List<Object> key = new ArrayList<>();
            try {
                for (String fn : fieldNames) {
                    Field field = getFieldIgnoreCase(item.getClass(), fn);
                    if (field != null) {
                        field.setAccessible(true);
                        Object value = field.get(item);
                        // 处理日期类型字段，只保留年月日部分
                        if (value instanceof LocalDateTime) {
                            LocalDateTime dateTime = (LocalDateTime) value;
                            // 截断时间到天，只保留日期部分
                            LocalDateTime truncatedDateTime = dateTime.truncatedTo(ChronoUnit.DAYS);
                            // 格式化时间为只包含日期的格式
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                            String formattedDate = truncatedDateTime.format(formatter);
                            key.add(formattedDate);
                        } else {
                            key.add(value);
                        }
                    } else {
                        key.add(null);
                    }
                }
            } catch (Exception e) {
                log.warn("分组取字段失败 fieldNames={}", fieldNames, e);
                continue;
            }
            String keyStr = key.stream()
                    .map(v -> v == null ? "" : v.toString())
                    .collect(Collectors.joining("\u0000"));
            if (!countByKey.containsKey(keyStr)) {
                keyOrder.add(key);
            }
            countByKey.merge(keyStr, 1L, Long::sum);
        }

        List<Object> result = new ArrayList<>();
        for (List<Object> key : keyOrder) {
            String keyStr = key.stream()
                    .map(v -> v == null ? "" : v.toString())
                    .collect(Collectors.joining("\u0000"));
            Long count = countByKey.get(keyStr);
            Map<String, Object> row = new LinkedHashMap<>();
            for (int i = 0; i < fieldNames.size(); i++) {
                row.put(fieldNames.get(i), key.get(i));
            }
            row.put("count", count != null ? count : 0L);
            result.add(row);
        }
        // 根据count倒序排序，如果count相同，则按照分组键的字典序排序
        result.sort((o1, o2) -> {
            if (o1 instanceof Map && o2 instanceof Map) {
                Map<?, ?> m1 = (Map<?, ?>) o1;
                Map<?, ?> m2 = (Map<?, ?>) o2;
                Object count1 = m1.get("count");
                Object count2 = m2.get("count");
                if (count1 instanceof Number && count2 instanceof Number) {
                    long c1 = ((Number) count1).longValue();
                    long c2 = ((Number) count2).longValue();
                    if (c1 != c2) {
                        return c2 - c1 > 0 ? 1 : -1;
                    } else {
                        // count相同，按照分组键的字典序排序
                        for (String fieldName : fieldNames) {
                            Object v1 = m1.get(fieldName);
                            Object v2 = m2.get(fieldName);
                            if (v1 != null && v2 != null) {
                                int compareResult = v1.toString().compareTo(v2.toString());
                                if (compareResult != 0) {
                                    return compareResult;
                                }
                            } else if (v1 != null) {
                                return 1;
                            } else if (v2 != null) {
                                return -1;
                            }
                        }
                    }
                }
            }
            return 0;
        });
        return result;
    }

    /**
     * 根据条件过滤数据（文件数据使用）- 修复版本
     */
    private List<Object> filterDataByConditions(List<?> dataList, List<ConditionEntity> conditions, Boolean and) {
        if (CollectionUtils.isEmpty(conditions)) {
            return new ArrayList<>(dataList);
        }

        // 分离sceneId条件和其他条件
        List<ConditionEntity> sceneIdConditions = new ArrayList<>();
        List<ConditionEntity> otherConditions = new ArrayList<>();
        for (ConditionEntity condition : conditions) {
            if (condition != null && condition.getFieldName() != null && condition.getFieldValue() != null) {
                if ("sceneId".equalsIgnoreCase(condition.getFieldName())) {
                    sceneIdConditions.add(condition);
                } else {
                    otherConditions.add(condition);
                }
            }
        }

        // 如果只有sceneId条件，返回所有数据（因为sceneId已经在查询层面处理了）
        if (otherConditions.isEmpty()) {
            return new ArrayList<>(dataList);
        }

        List<Object> filteredList = new ArrayList<>(dataList);
        boolean isAnd = and != null && and;

        if (isAnd) {
            // 与关系：逐个应用条件，只有满足所有条件的记录才会保留
            for (ConditionEntity condition : otherConditions) {
                final String fieldName = condition.getFieldName();
                final String fieldValue = condition.getFieldValue();
                ConditionEnum conditionType = ConditionEnum.getByName(condition.getConditionalType());
                if (conditionType == null) {
                    conditionType = ConditionEnum.Equal;
                }
                final ConditionEnum finalConditionType = conditionType;

                List<Object> tempList = new ArrayList<>();
                for (Object item : filteredList) {
                    if (matchesCondition(item, fieldName, fieldValue, finalConditionType)) {
                        tempList.add(item);
                    }
                }
                filteredList = tempList;
            }
        } else {
            // 或关系：只要满足一个条件的记录就会保留
            List<Object> resultList = new ArrayList<>();
            for (Object item : filteredList) {
                boolean matches = false;
                for (ConditionEntity condition : otherConditions) {
                    final String fieldName = condition.getFieldName();
                    final String fieldValue = condition.getFieldValue();
                    ConditionEnum conditionType = ConditionEnum.getByName(condition.getConditionalType());
                    if (conditionType == null) {
                        conditionType = ConditionEnum.Equal;
                    }

                    if (matchesCondition(item, fieldName, fieldValue, conditionType)) {
                        matches = true;
                        break;
                    }
                }
                if (matches) {
                    resultList.add(item);
                }
            }
            filteredList = resultList;
        }

        return filteredList;
    }

    /**
     * 根据排序规则对数据进行排序
     */
    private List<Object> sortData(List<?> dataList, Paged paged) {
        if (CollectionUtils.isEmpty(dataList)) {
            return new ArrayList<>(dataList);
        }

        List<Object> sortedList = new ArrayList<>(dataList);

        // 优先使用sortByList进行多字段排序
        if (!CollectionUtils.isEmpty(paged.getSortByList())) {
            // 构建Comparator链
            Comparator<Object> comparator = null;

            for (String sortBy : paged.getSortByList()) {
                String[] parts = sortBy.trim().split("\\s+");
                if (parts.length < 2) {
                    continue; // 跳过格式不正确的排序规则
                }

                String fieldName = parts[0];
                boolean isAsc = !"desc".equalsIgnoreCase(parts[1]);

                // 创建字段比较器
                Comparator<Object> fieldComparator = (o1, o2) -> {
                    try {
                        Field field1 = getFieldIgnoreCase(o1.getClass(), fieldName);
                        Field field2 = getFieldIgnoreCase(o2.getClass(), fieldName);

                        if (field1 == null || field2 == null) {
                            return 0;
                        }

                        field1.setAccessible(true);
                        field2.setAccessible(true);

                        Object value1 = field1.get(o1);
                        Object value2 = field2.get(o2);

                        // 处理null值
                        if (value1 == null && value2 == null) {
                            return 0;
                        }
                        if (value1 == null) {
                            return isAsc ? -1 : 1;
                        }
                        if (value2 == null) {
                            return isAsc ? 1 : -1;
                        }

                        // 比较值
                        if (value1 instanceof Comparable && value2 instanceof Comparable) {
                            @SuppressWarnings("unchecked")
                            int compareResult = ((Comparable<Object>) value1).compareTo(value2);
                            return isAsc ? compareResult : -compareResult;
                        }

                        return 0;
                    } catch (Exception e) {
                        log.error("排序字段获取失败: " + fieldName, e);
                        return 0;
                    }
                };

                // 链式比较
                comparator = comparator == null ? fieldComparator : comparator.thenComparing(fieldComparator);
            }

            if (comparator != null) {
                sortedList.sort(comparator);
            }
        }
        // 使用原有sortBy和desc字段进行单字段排序
        else if (paged.getSortBy() != null && !paged.getSortBy().isEmpty()) {
            String sortBy = paged.getSortBy();
            boolean isDesc = paged.getDesc() != null && paged.getDesc();

            sortedList.sort((o1, o2) -> {
                try {
                    Field field1 = getFieldIgnoreCase(o1.getClass(), sortBy);
                    Field field2 = getFieldIgnoreCase(o2.getClass(), sortBy);

                    if (field1 == null || field2 == null) {
                        return 0;
                    }

                    field1.setAccessible(true);
                    field2.setAccessible(true);

                    Object value1 = field1.get(o1);
                    Object value2 = field2.get(o2);

                    // 处理null值
                    if (value1 == null && value2 == null) {
                        return 0;
                    }
                    if (value1 == null) {
                        return isDesc ? 1 : -1;
                    }
                    if (value2 == null) {
                        return isDesc ? -1 : 1;
                    }

                    // 比较值
                    if (value1 instanceof Comparable && value2 instanceof Comparable) {
                        @SuppressWarnings("unchecked")
                        int compareResult = ((Comparable<Object>) value1).compareTo(value2);
                        return isDesc ? -compareResult : compareResult;
                    }

                    return 0;
                } catch (Exception e) {
                    log.error("排序字段获取失败: " + sortBy, e);
                    return 0;
                }
            });
        }

        return sortedList;
    }

    /**
     * 判断单个对象是否匹配条件
     */
    private boolean matchesCondition(Object item, String fieldName, String fieldValue, ConditionEnum conditionType) {
        try {
            // 获取字段值
            Object actualValue = getFieldValue(item, fieldName);
            if (actualValue == null) {
                return conditionType == ConditionEnum.IsEmpty;
            }

            // 特殊处理时间类型字段
            if (actualValue instanceof LocalDateTime) {
                LocalDateTime actualDateTime = (LocalDateTime) actualValue;
                if (conditionType == ConditionEnum.Between) {
                    LocalDateTime[] range = parseDateTimeRange(fieldValue);
                    if (range != null) {
                        // Between用于时间范围筛选时需要精确到时分秒，不能按日期截断。
                        return !actualDateTime.isBefore(range[0]) && !actualDateTime.isAfter(range[1]);
                    }
                }
                
                // 尝试解析输入的时间字符串
                LocalDateTime inputDateTime = parseDateTimeString(fieldValue);
                if (inputDateTime != null) {
                    // 截断时间到天，只比较日期部分
                    LocalDateTime truncatedActualDateTime = actualDateTime.truncatedTo(ChronoUnit.DAYS);
                    LocalDateTime truncatedInputDateTime = inputDateTime.truncatedTo(ChronoUnit.DAYS);
                    
                    // 时间类型比较
                    int compareResult = truncatedActualDateTime.compareTo(truncatedInputDateTime);
                    
                    switch (conditionType) {
                        case Equal:
                            return compareResult == 0;
                        case NoEqual:
                            return compareResult != 0;
                        case GreaterThan:
                            return compareResult > 0;
                        case GreaterThanOrEqual:
                            return compareResult >= 0;
                        case LessThan:
                            return compareResult < 0;
                        case LessThanOrEqual:
                            return compareResult <= 0;
                        default:
                            return compareResult == 0;
                    }
                }
            }

            // 非时间类型字段的处理
            String actualValueStr = actualValue.toString();

            switch (conditionType) {
                case Equal:
                    // 使用compareValues方法比较，支持数字和字符串
                    return compareValues(actualValueStr, fieldValue) == 0;
                case NoEqual:
                    // 使用compareValues方法比较，支持数字和字符串
                    return compareValues(actualValueStr, fieldValue) != 0;
                case Like:
                    return actualValueStr.toLowerCase().contains(fieldValue.toLowerCase());
                case NotLike:
                    return !actualValueStr.toLowerCase().contains(fieldValue.toLowerCase());
                case GreaterThan:
                    return compareValues(actualValueStr, fieldValue) > 0;
                case GreaterThanOrEqual:
                    return compareValues(actualValueStr, fieldValue) >= 0;
                case LessThan:
                    return compareValues(actualValueStr, fieldValue) < 0;
                case LessThanOrEqual:
                    return compareValues(actualValueStr, fieldValue) <= 0;
                case Between:
                    String[] range = splitBetweenValue(fieldValue);
                    return range != null
                            && compareValues(actualValueStr, range[0]) >= 0
                            && compareValues(actualValueStr, range[1]) <= 0;
                case In:
                    return Arrays.asList(fieldValue.split(",")).contains(actualValueStr);
                case NotIn:
                    return !Arrays.asList(fieldValue.split(",")).contains(actualValueStr);
                case IsEmpty:
                    return actualValueStr.isEmpty();
                case NotEmpty:
                    return !actualValueStr.isEmpty();
                default:
                    return compareValues(actualValueStr, fieldValue) == 0;
            }
        } catch (Exception e) {
            // 如果匹配过程中出错，保守起见返回true（不过滤掉数据）
            return true;
        }
    }

    private String[] splitBetweenValue(String fieldValue) {
        if (fieldValue == null || fieldValue.trim().isEmpty()) {
            return null;
        }
        String[] values = fieldValue.split(",", 2);
        if (values.length != 2) {
            return null;
        }
        return new String[]{values[0].trim(), values[1].trim()};
    }

    private LocalDateTime[] parseDateTimeRange(String fieldValue) {
        String[] values = splitBetweenValue(fieldValue);
        if (values == null) {
            return null;
        }
        LocalDateTime start = parseDateTimeString(values[0]);
        LocalDateTime end = parseDateTimeString(values[1]);
        if (start == null || end == null) {
            return null;
        }
        if (start.isAfter(end)) {
            return new LocalDateTime[]{end, start};
        }
        return new LocalDateTime[]{start, end};
    }

    /**
     * 解析时间字符串为LocalDateTime（兼容Java 8）
     * @param dateTimeStr 时间字符串
     * @return 解析后的LocalDateTime，解析失败返回null
     */
    private LocalDateTime parseDateTimeString(String dateTimeStr) {
        try {
            if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) {
                return null;
            }

            String trimmed = dateTimeStr.trim();

            // 处理带Z后缀的格式
            if (trimmed.endsWith("Z")) {
                // Java 8兼容处理：移除Z后缀，解析为LocalDateTime
                trimmed = trimmed.substring(0, trimmed.length() - 1);
                // 处理可能的毫秒部分
                if (trimmed.contains(".")) {
                    // 保留三位小数
                    int dotIndex = trimmed.indexOf(".");
                    if (dotIndex + 4 < trimmed.length()) {
                        trimmed = trimmed.substring(0, dotIndex + 4);
                    }
                }
                return LocalDateTime.parse(trimmed, DateTimeFormatter.ISO_DATE_TIME);
            }

            // 处理包含空格的格式
            if (trimmed.contains(" ")) {
                return LocalDateTime.parse(trimmed, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }

            // 处理只包含日期的格式
            if (trimmed.length() == 10 && trimmed.contains("-")) {
                // 先解析为LocalDate，然后转换为LocalDateTime
                LocalDate localDate = LocalDate.parse(trimmed, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                return localDate.atStartOfDay();
            }

            // 处理ISO格式
            return LocalDateTime.parse(trimmed, DateTimeFormatter.ISO_DATE_TIME);
        } catch (Exception e) {
            // 解析失败，返回null
            return null;
        }
    }

    /**
     * 安全获取字段值（支持多种字段名格式）
     */
    private Object getFieldValue(Object item, String fieldName) {
        try {
            // 使用getFieldIgnoreCase方法获取字段，支持忽略大小写和父类字段
            Field field = getFieldIgnoreCase(item.getClass(), fieldName);
            if (field != null) {
                field.setAccessible(true);
                // 对于基本数据类型，field.get(item)会返回对应的包装类型，不会返回null
                // 所以不需要检查value是否为null
                return field.get(item);
            }
        } catch (Exception e) {
            // 如果获取字段值时出错，返回null
            log.error("获取字段值失败: {}", fieldName, e);
        }

        return null;
    }

    /**
     * 比较值（支持数字和字符串）
     */
    private int compareValues(String str1, String str2) {
        try {
            // 尝试数字比较
            Double num1 = Double.parseDouble(str1);
            Double num2 = Double.parseDouble(str2);
            return num1.compareTo(num2);
        } catch (NumberFormatException e) {
            // 数字解析失败，使用字符串比较
            return str1.compareTo(str2);
        }
    }



    /**
     * 更新Chromosome中的数据（支持文件实体和数据库实体）
     */
    public boolean updateChromosomeData(String sceneId, String entityName, Map<String, Object> data) {
        EntityConfig config = getEntityConfig(entityName);

        if (config.getDataSource() == DataSourceType.FILE) {
            if ("entry".equalsIgnoreCase(entityName)) {
                convertNestedObjects(data);
            }
            return updateFileEntity(sceneId, entityName, data);
        } else {
            // 数据库实体更新
            return updateDatabaseEntity(entityName, data);
        }
    }

    /**
     * 更新文件实体数据
     */
    private boolean updateFileEntity(String sceneId, String entityName, Map<String, Object> data) {
        EntityConfig config = getEntityConfig(entityName);

        // 从文件中加载Chromosome对象
        Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);
        if (chromosome == null) {
            throw new RuntimeException("未找到场景ID为 " + sceneId + " 的Chromosome数据");
        }

        try {
            // 根据实体名称映射到Chromosome中的字段名
            String fieldName = config.getFieldName();

            // 使用反射设置字段值
            Field field = Chromosome.class.getDeclaredField(fieldName);
            field.setAccessible(true);

            // 获取原始数据
            Object originalData = field.get(chromosome);

            // 如果原始数据是List类型，并且传入的data包含id字段，则更新列表中的特定项
            if (originalData instanceof List && data.containsKey("id")) {
                List<Object> dataList = (List<Object>) originalData;
                String id = data.get("id").toString();

                // 查找并更新匹配的项
                for (int i = 0; i < dataList.size(); i++) {
                    Object item = dataList.get(i);
                    try {
                        Field idField = item.getClass().getDeclaredField("id");
                        idField.setAccessible(true);
                        Object itemId = idField.get(item);
                        if (itemId != null && itemId.toString().equals(id)) {
                            // 找到匹配项，更新它
                            updateObjectFields(item, data);
                            break;
                        }
                    } catch (Exception e) {
                        // 如果没有id字段或访问失败，尝试使用Id字段
                        try {
                            Field idField = item.getClass().getDeclaredField("Id");
                            idField.setAccessible(true);
                            Object itemId = idField.get(item);
                            if (itemId != null && itemId.toString().equals(id)) {
                                // 找到匹配项，更新它
                                updateObjectFields(item, data);
                                break;
                            }
                        } catch (Exception ex) {
                            // 忽略异常，继续下一个
                        }
                    }
                }
            } else {
                // 如果不是列表类型或没有id字段，抛出异常提示
                throw new RuntimeException("更新文件实体时必须提供id字段以标识要更新的具体对象");
            }

            if (entityName.equals("order")) {
                Order bean = BeanUtil.toBean(data, Order.class);
                Order order = chromosome.getOrders().stream().filter(o -> o.getId() == (bean.getId())).findFirst().orElse(null);
                chromosome = planResultService.editOrder(chromosome, sceneId, order);

            }else if (entityName.equals("entry")) {
                // 获取原有entry对象
                List<Object> dataList = (List<Object>) originalData;
                String id = data.get("id").toString();
                Entry originalEntry = null;
                for (Object item : dataList) {
                    if (item instanceof Entry) {
                        Entry entry = (Entry) item;
                        if (String.valueOf(entry.getId()).equals(id)) {
                            originalEntry = entry;
                            break;
                        }
                    }
                }

                // 如果找到了原有entry对象，直接使用它
                if (originalEntry != null) {
                    // 如果传入了machineOptions字段，需要特殊处理
                    if (data.containsKey("machineOptions")) {
                        List<?> machineOptionsList = (List<?>) data.get("machineOptions");
                        List<MachineOption> convertedOptions = new ArrayList<>();
                        for (Object item : machineOptionsList) {
                            // 手动转换每个MachineOption对象
                            MachineOption option = objectMapper.convertValue(item, MachineOption.class);
                            convertedOptions.add(option);
                        }
                        // 设置转换后的machineOptions
                        originalEntry.setMachineOptions(convertedOptions);
                        // 从data中移除machineOptions，避免updateObjectFields再次处理
                        data.remove("machineOptions");
                    }

                    // 更新其他传入的字段
                    updateObjectFields(originalEntry, data);

                    // 调用editOperation方法
                    chromosome = planResultService.editOperation(chromosome, sceneId, originalEntry );
                    if (originalEntry.getDesignatedStartTime()== null)
                        planResultService.unlockStartTime(chromosome, originalEntry.getId());
                    else {

                        List<Integer> opids = new ArrayList<>();
                        opids.add(originalEntry.getId());
                        chromosome = planResultService.lock(chromosome, opids, originalEntry.getDesignatedStartTime(), 0L, 1);

                    }

                }

            }

            // 保存更新后的Chromosome到文件
            return sceneService.saveChromosomeToFile(chromosome, sceneId);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException("Chromosome类中未找到字段: " + entityName, e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("访问Chromosome字段失败: " + e.getMessage(), e);
        }
    }

    /**
     * 更新数据库实体数据
     */
    private boolean updateDatabaseEntity(String entityName, Map<String, Object> data) {
        EntityConfig config = getEntityConfig(entityName);
        String tableName = config.getTableName();

        if (data == null || !data.containsKey("id")) {
            throw new RuntimeException("更新数据库实体时必须提供id字段");
        }

        String id = data.get("id").toString();

        // 构建更新SQL
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ").append(tableName).append(" SET ");

        List<String> setParts = new ArrayList<>();
        MapSqlParameterSource params = new MapSqlParameterSource();

        // 遍历要更新的字段，排除id字段
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String fieldName = entry.getKey();
            Object fieldValue = entry.getValue();

            if (!"id".equalsIgnoreCase(fieldName)) {
                // 将驼峰命名转换为下划线大写格式
                String dbFieldName = camelCaseToUnderScoreUpperCase(fieldName).toUpperCase();
                setParts.add(dbFieldName + " = :" + fieldName);
                params.addValue(fieldName, fieldValue);
            }
        }

        if (setParts.isEmpty()) {
            throw new RuntimeException("没有有效的字段用于更新");
        }

        sql.append(String.join(", ", setParts));

        // 添加WHERE条件
        sql.append(" WHERE ID = :idParam");
        params.addValue("idParam", id);

        try {
            int rowsAffected = namedParameterJdbcTemplate.update(sql.toString(), params);
            return rowsAffected > 0;
        } catch (Exception e) {
            throw new RuntimeException("数据库更新失败: " + e.getMessage(), e);
        }
    }




    /**
     * 更新对象的字段值
     */
    private void updateObjectFields(Object obj, Map<String, Object> data) {
        Class<?> clazz = obj.getClass();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String fieldName = entry.getKey();
            Object fieldValue = entry.getValue();

            try {
                // 尝试直接查找字段（区分大小写）
                Field field = null;
                try {
                    field = clazz.getDeclaredField(fieldName);
                } catch (NoSuchFieldException e) {
                    // 如果找不到，尝试忽略大小写查找
                    for (Field declaredField : clazz.getDeclaredFields()) {
                        if (declaredField.getName().equalsIgnoreCase(fieldName)) {
                            field = declaredField;
                            break;
                        }
                    }
                }

                if (field != null) {
                    field.setAccessible(true);

                    // 简单的类型转换处理
                    if (fieldValue != null) {
                        Class<?> fieldType = field.getType();
                        if (fieldType == String.class) {
                            field.set(obj, fieldValue.toString());
                        } else if (fieldType == Integer.class || fieldType == int.class) {
                            field.set(obj, Integer.parseInt(fieldValue.toString()));
                        } else if (fieldType == Long.class || fieldType == long.class) {
                            field.set(obj, Long.parseLong(fieldValue.toString()));
                        } else if (fieldType == Double.class || fieldType == double.class) {
                            field.set(obj, Double.parseDouble(fieldValue.toString()));
                        } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                            field.set(obj, Boolean.parseBoolean(fieldValue.toString()));
                        } else if (fieldType == List.class) {
                            // 特殊处理List类型字段，特别是MachineOption列表
                            List<?> valueList = (List<?>) fieldValue;
                            if (!valueList.isEmpty() && valueList.get(0) instanceof Map) {
                                // 如果列表中的元素是Map（如JSON反序列化结果），需要特殊处理
                                // 对于MachineOption这类复杂对象，我们暂时直接赋值
                                field.set(obj, fieldValue);
                            } else {
                                field.set(obj, fieldValue);
                            }
                        } else if (fieldType == LocalDateTime.class) {
                            // 特殊处理LocalDateTime类型字段
                            if (fieldValue instanceof String) {
                                // 如果是字符串，尝试解析为LocalDateTime
                                String dateString = (String) fieldValue;
                                // 处理不同格式的日期时间字符串，包括带Z后缀的ISO格式
                                LocalDateTime parsedDateTime;
                                if (dateString.endsWith("Z")) {
                                    // 处理带Z后缀的格式，将其转换为带+00:00时区的格式
                                    dateString = dateString.substring(0, dateString.length() - 1) + "+00:00";
                                    parsedDateTime = OffsetDateTime.parse(dateString).toLocalDateTime();
                                } else if (dateString.contains(" ")) {
                                    // 处理包含空格的日期时间格式，如 "2026-01-07 00:00:00"
                                    DateTimeFormatter spaceFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                    parsedDateTime = LocalDateTime.parse(dateString, spaceFormatter);
                                } else {
                                    // 尝试解析为OffsetDateTime然后转换为LocalDateTime
                                    try {
                                        parsedDateTime = OffsetDateTime.parse(dateString).toLocalDateTime();
                                    } catch (DateTimeParseException e) {
                                        // 如果不是偏移格式，尝试直接解析为LocalDateTime
                                        try {
                                            parsedDateTime = LocalDateTime.parse(dateString, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                                        } catch (DateTimeParseException ex) {
                                            // 最后尝试使用 "yyyy-MM-dd HH:mm:ss" 格式
                                            DateTimeFormatter fallbackFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                            parsedDateTime = LocalDateTime.parse(dateString, fallbackFormatter);
                                        }
                                    }
                                }
                                field.set(obj, parsedDateTime);
                            } else if (fieldValue instanceof LocalDateTime) {
                                field.set(obj, (LocalDateTime) fieldValue);
                            } else {
                                // 尝试将其他类型转换为字符串再解析
                                String dateString = fieldValue.toString();
                                // 同样处理各种格式
                                LocalDateTime parsedDateTime;
                                if (dateString.contains(" ")) {
                                    DateTimeFormatter spaceFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                    parsedDateTime = LocalDateTime.parse(dateString, spaceFormatter);
                                } else {
                                    parsedDateTime = LocalDateTime.parse(dateString, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                                }
                                field.set(obj, parsedDateTime);
                            }
                        } else {
                            field.set(obj, fieldValue);
                        }
                    } else {
                        field.set(obj, null);
                    }
                }
            } catch (Exception e) {
                // 忽略无法设置的字段
            }
        }
    }


    /**
     * 从Entry列表中提取MachineOption列表
     */
    private Object extractMachineOptionsFromEntries(Object data) {
        if (data instanceof List) {
            List<?> entryList = (List<?>) data;
            List<MachineOption> result = new ArrayList<>();


            for (Object obj : entryList) {
                if (obj instanceof Entry) {
                    Entry entry = (Entry) obj;
                    if (entry.getMachineOptions() != null) {
                        // 返回所有Entry中的MachineOption
                        result.addAll(entry.getMachineOptions());
                    } else {
                    }
                }
            }

            return result;
        } else if (data instanceof Entry) {
            Entry entry = (Entry) data;
            return entry.getMachineOptions() != null ? entry.getMachineOptions() : new ArrayList<>();
        }

        return new ArrayList<>(); // 如果不是Entry类型，返回空列表
    }

    private void convertNestedObjects(Map<String, Object> data) {
        // 转换machineOptions（支持大小写）
        convertListField(data, "MachineOptions", MachineOption.class);
        // 可以添加其他需要转换的字段
    }

    private <T> void convertListField(Map<String, Object> data, String fieldName, Class<T> targetClass) {
        if (data.containsKey(fieldName)) {
            Object fieldValue = data.get(fieldName);
            if (fieldValue instanceof List) {
                List<?> list = (List<?>) fieldValue;
                List<T> convertedList = new ArrayList<>();

                for (Object item : list) {
                    if (item instanceof LinkedHashMap) {
                        T convertedItem = BeanUtil.toBean((Map<?, ?>) item, targetClass);
                        convertedList.add(convertedItem);
                    }
                }

                data.put(fieldName, convertedList);
            }
        }
    }


    public R<String> updateMachineOption(String sceneId, String taskId, Map<String, Object> data) {

        // 1. 加载Chromosome对象
        Chromosome chromosome = sceneService.loadChromosomeFromFile(sceneId);


        // 2. 根据taskId找到对应的entry
        Entry targetEntry = null;
        for (Entry entry : chromosome.getAllOperations()) {
            if (String.valueOf(entry.getId()).equals(taskId)) {
                targetEntry = entry;
                break;
            }
        }

        Long machineId = null;
        Object machineIdObj = data.get("machineId");
        if (machineIdObj instanceof Long) {
            machineId = (Long) machineIdObj;
        } else if (machineIdObj instanceof Integer) {
            machineId = ((Integer) machineIdObj).longValue();
        } else if (machineIdObj instanceof String) {
            machineId = Long.parseLong((String) machineIdObj);
        }

        // 4. 在entry的machineOptions列表中找到对应的machineOption
        MachineOption targetMachineOption = null;
        for (MachineOption machineOption : targetEntry.getMachineOptions()) {
            if (machineOption.getMachineId().equals(machineId)) {
                targetMachineOption = machineOption;
                break;
            }
        }



        // 5. 只更新传入的字段，保留原有字段值
        updateMachineOptionFields(targetMachineOption, data);

        // 6. 调用editMachine方法
        planResultService.editMachine(chromosome, sceneId, targetEntry);

        // 7. 保存更新后的Chromosome
        boolean saved = sceneService.saveChromosomeToFile(chromosome, sceneId);

        return R.ok("更新成功");


    }

    /**
     * 只更新MachineOption的传入字段，保留原有字段值
     */
    private void updateMachineOptionFields(MachineOption machineOption, Map<String, Object> data) {
        // 处理runtime字段
        if (data.containsKey("runtime")) {
            Object runtimeObj = data.get("runtime");
            if (runtimeObj instanceof Integer) {
                machineOption.setRuntime(new BigDecimal((Integer) runtimeObj));
            } else if (runtimeObj instanceof Long) {
                machineOption.setRuntime(new BigDecimal((Long) runtimeObj));
            } else if (runtimeObj instanceof Double) {
                machineOption.setRuntime(new BigDecimal((Double) runtimeObj));
            } else if (runtimeObj instanceof String) {
                machineOption.setRuntime(new BigDecimal((String) runtimeObj));
            }
        }

        // 处理singleOut字段
        if (data.containsKey("singleOut")) {
            Object singleOutObj = data.get("singleOut");
            if (singleOutObj instanceof Integer) {
                machineOption.setSingleOut(new BigDecimal((Integer) singleOutObj));
            } else if (singleOutObj instanceof Long) {
                machineOption.setSingleOut(new BigDecimal((Long) singleOutObj));
            } else if (singleOutObj instanceof Double) {
                machineOption.setSingleOut(new BigDecimal((Double) singleOutObj));
            } else if (singleOutObj instanceof String) {
                machineOption.setSingleOut(new BigDecimal((String) singleOutObj));
            }
        }

        // 处理processingTime字段 - 修改为：时间(runtime) ÷ 数量(singleOut)
        if (data.containsKey("processingTime") || data.containsKey("singleOut") || data.containsKey("runtime")) {
            // 1. 获取singleOut值
            BigDecimal singleOut = machineOption.getSingleOut();
            if (data.containsKey("singleOut")) {
                Object singleOutObj = data.get("singleOut");
                if (singleOutObj instanceof Integer) {
                    singleOut = new BigDecimal((Integer) singleOutObj);
                } else if (singleOutObj instanceof Long) {
                    singleOut = new BigDecimal((Long) singleOutObj);
                } else if (singleOutObj instanceof Double) {
                    singleOut = new BigDecimal((Double) singleOutObj);
                } else if (singleOutObj instanceof String) {
                    singleOut = new BigDecimal((String) singleOutObj);
                } else if (singleOutObj instanceof BigDecimal) {
                    singleOut = (BigDecimal) singleOutObj;
                }
            }

            // 2. 获取runtime值
            BigDecimal runtime = machineOption.getRuntime();
            if (data.containsKey("runtime")) {
                Object runtimeObj = data.get("runtime");
                if (runtimeObj instanceof Integer) {
                    runtime = new BigDecimal((Integer) runtimeObj);
                } else if (runtimeObj instanceof Long) {
                    runtime = new BigDecimal((Long) runtimeObj);
                } else if (runtimeObj instanceof Double) {
                    runtime = new BigDecimal((Double) runtimeObj);
                } else if (runtimeObj instanceof String) {
                    runtime = new BigDecimal((String) runtimeObj);
                } else if (runtimeObj instanceof BigDecimal) {
                    runtime = (BigDecimal) runtimeObj;
                }
            }

            // 3. 计算processingTime = runtime ÷ singleOut（时间 ÷ 数量）
            double processingTime = 0.0;
            if (singleOut != null && runtime != null && runtime.compareTo(BigDecimal.ZERO) != 0) {
                // 考虑runtime单位转换：如果runtime是毫秒，转换为秒
                BigDecimal runtimeSeconds = runtime.divide(new BigDecimal(1000), 6, RoundingMode.HALF_UP);
                // 关键修改：时间（秒） ÷ 数量，保留2位小数
                processingTime = runtimeSeconds.divide(singleOut, 2, RoundingMode.HALF_UP).doubleValue();
            }

            // 4. 设置计算后的processingTime
            machineOption.setProcessingTime(processingTime);
        }

    }

    /**
     * 从 SqlOrder 中提取 sceneId
     * @param sqlOrder SqlOrder 对象
     * @return sceneId，如果没有则返回 null
     */
    private String extractSceneIdFromSqlOrder(SqlOrder sqlOrder) {
        try {
            if (sqlOrder.getData() != null) {
                @SuppressWarnings("unchecked")
                Map<String, Object> dataMap = objectMapper.convertValue(sqlOrder.getData(), Map.class);
                if (dataMap != null && dataMap.get("conditions") != null) {
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> conditions = (List<Map<String, Object>>) dataMap.get("conditions");
                    if (conditions != null) {
                        for (Map<String, Object> condition : conditions) {
                            if ("sceneId".equalsIgnoreCase((String) condition.get("fieldName"))) {
                                return (String) condition.get("fieldValue");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("从 SqlOrder 中提取 sceneId 失败", e);
        }
        return null;
    }

    /**
     * 执行批量查询操作（report接口）
     * @param sqlOrders SqlOrder列表
     * @return 查询结果Map
     */
    public Map<String, Object> executeSqlOrderReport(List<SqlOrder> sqlOrders) {
        HashMap<String, Object> map = new HashMap<>();

        if (sqlOrders != null && sqlOrders.size() > 0) {
            sqlOrders.forEach(s -> {
                try {
                    String resultName = (s.getName() != null && !s.getName().isEmpty())
                            ? s.getName()
                            : s.getTable();

                    String sceneId = extractSceneIdFromSqlOrder(s);

                    try {
                        String type = s.getType() != null ? s.getType().toLowerCase() : "";
                        Object value = null;

                        if ("page".equals(type)) {
                            Paged paged = objectMapper.convertValue(s.getData(), Paged.class);
                            value = queryChromosomeDataWithConditions(sceneId, s.getTable(), paged);
                        } else if ("list".equals(type)) {
                            Paged paged = objectMapper.convertValue(s.getData(), Paged.class);
                            value = queryChromosomeDataList(sceneId, s.getTable(), paged);
                        } else if ("get".equals(type)) {
                            @SuppressWarnings("unchecked")
                            Map<String, Object> dataMap = objectMapper.convertValue(s.getData(), Map.class);
                            String id = dataMap != null && dataMap.get("id") != null ? dataMap.get("id").toString() : null;
                            if (id != null) {
                                value = queryChromosomeDataById(sceneId, s.getTable(), id);
                            } else {
                                value = "get操作需要提供id参数";
                            }
                        } else {
                            value = "只支持查询操作（page/list/get）";
                        }

                        map.put(resultName, value);
                    } catch (Exception e) {
                        log.error("执行SqlOrder失败: type={}, table={}", s.getType(), s.getTable(), e);
                        map.put(resultName, "执行失败: " + e.getMessage());
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }

        return map;
    }

    /**
     * 执行批量修改操作（commit接口）
     * @param sqlOrders SqlOrder列表
     * @return 执行结果Map
     */
    public Map<String, Object> executeSqlOrderCommit(List<SqlOrder> sqlOrders) {
        HashMap<String, Object> map = new HashMap<>();

        if (sqlOrders != null && sqlOrders.size() > 0) {
            sqlOrders.forEach(s -> {
                try {
                    String resultName = (s.getName() != null && !s.getName().isEmpty())
                            ? s.getName()
                            : s.getTable();

                    String sceneId = extractSceneIdFromSqlOrder(s);

                    try {
                        String type = s.getType() != null ? s.getType().toLowerCase() : "";
                        Object value = null;

                        if ("update".equals(type)) {
                            @SuppressWarnings("unchecked")
                            Map<String, Object> data = objectMapper.convertValue(s.getData(), Map.class);
                            boolean success = updateChromosomeData(sceneId, s.getTable(), data);
                            value = success ? "更新成功" : "更新失败";
                        } else if ("delete".equals(type)) {
                            value = "删除功能待实现";
                        } else if ("insert".equals(type)) {
                            value = "插入功能待实现";
                        } else {
                            value = "不支持的操作类型: " + type;
                        }

                        map.put(resultName, value);
                    } catch (Exception e) {
                        log.error("执行SqlOrder失败: type={}, table={}", s.getType(), s.getTable(), e);
                        map.put(resultName, "执行失败: " + e.getMessage());
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }

        return map;
    }

}
