package com.aps.service.Algorithm;

import com.aps.common.util.FileHelper;
import com.aps.common.util.GlobalCacheUtil;
import com.aps.common.util.ProductionDeepCopyUtil;
import com.aps.entity.Algorithm.*;
import com.aps.entity.Algorithm.IDAndChildID.GroupResult;
import com.aps.entity.basic.*;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * 爬山法算法
 */
public class HillClimbing {
    private final Random rnd = new Random();

    private List<Entry> allOperations;

    private  List<Order> orders;
    private  TreeMap<String, Material> materials;

    private  List<GroupResult> _entryRel;

    //按优先级分组工序
    private Map<Double, List<Entry>> priorityGroups;

    // 按优先级从高到低处理
    private List<Double> sortedPriorities ;

    // 从List转为Map op.getGroupId() + "_" + op.getSequence(); 做主键
    private Map<String, Entry> entrys;

    private FitnessCalculator fitnessCalculator;

    public HillClimbing(List<Entry> allOperations, List<Order> orders,
                        TreeMap<String, Material> materials,List<GroupResult> entryRel,   FitnessCalculator _fitnessCalculator) {

        this.allOperations = allOperations;
        this.orders = orders;
        this.materials = materials;

        _entryRel=entryRel;
        fitnessCalculator=_fitnessCalculator;
        // 按优先级分组工序
        priorityGroups = groupOperationsByPriority();

        // 按优先级从高到低处理
        sortedPriorities= new ArrayList<>(priorityGroups.keySet());
        Collections.sort(sortedPriorities);
        entrys = buildEntryKey();
    }

    public Chromosome BatchSearchAll(List<Chromosome> population, List<Machine> machines,  GeneticDecoder decoder) {
        List<Chromosome>  optimizedPopulation=new ArrayList<>();
        for (Chromosome chromosome : population) {
            Chromosome optimized = searchAll(chromosome,machines, decoder);
            optimizedPopulation.add(optimized);
        }
        int bestidx= Getbest(optimizedPopulation,null);
        if(bestidx>-1) {
            return optimizedPopulation.get(bestidx);
        }
        return  null;
    }

    /**
     * 穷举搜索
     */
    public Chromosome searchAll(Chromosome chromosome, List<Machine> machines, GeneticDecoder decoder) {
        Chromosome current = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);

        Chromosome best = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);


        // 构建位置索引映射：groupId_sequence -> position
        Map<String, Integer> positionIndex = buildPositionIndex(current);

        Map<String, Integer> MachinePositionIndex = buildEntryMachinePositionIndex(current);


        // 构建位置到Entry的映射：position -> Entry
        Map<Integer, Entry> entryIndex = buildEntryIndex(current, entrys);
        boolean improved = false;
        for (Double priority : sortedPriorities) {
            decoder.DelOrder(current);
            List<Entry> priorityOps = priorityGroups.get(priority);
            if (priorityOps.isEmpty()) {
                continue;
            }
            // 1. 优先处理有多设备选项的工序（最有可能带来改进）
            List<Entry> multiMachineOps = priorityOps.stream()
                    .filter(op -> op.getMachineOptions().size() > 1)
                    .collect(Collectors.toList());

            if (!multiMachineOps.isEmpty()) {
                for (Entry op : multiMachineOps) {
                    String key = op.getGroupId() + "_" + op.getSequence();
                    Integer maPos = MachinePositionIndex.get(key);

                    if (maPos == null) continue;

                    Chromosome machineChange = generateMachineChange(current, op.getMachineOptions(), maPos);
                    if (machineChange != null) {
                        decode(decoder, machineChange,machines);
                        writeKpi(machineChange);
                        if (isBetter(machineChange, current)) {
                            current = machineChange;
                            if (isBetter(current, best)) {
                                best = current;
                            }
                            improved = true;

                            positionIndex = buildPositionIndex(current);
                            entryIndex = buildEntryIndex(current, entrys);
                            MachinePositionIndex = buildEntryMachinePositionIndex(current);
                           // decoder.DelOrder(current);
                            break;
                        }
                    }
                }
                if (improved) break;
            }



            // 2. 检查是否是单一订单（如果只有一个订单，不需要交换位置
            Set<Integer> groupIds = priorityOps.stream()
                    .map(Entry::getGroupId)
                    .collect(Collectors.toSet());

            if (groupIds.size() <= 1) {
                continue;
            }
            // 根据当前优先级的工序数确定迭代次数和step
            int priorityIterations = Math.max(5, priorityOps.size() / 2);
            // 200/10 =20
            // 1
            int step = Math.max(1, (int) Math.ceil(priorityOps.size() / 10.0));
            // 200/20=10;
            //
            int stepCount = Math.max(1, (int) Math.ceil(priorityOps.size() / step));
            Set<Integer> Groupid = new HashSet<>();
            for (int pi = 0; pi < priorityIterations; pi++) {
                // 随机取该优先级的工序
                Entry randomOp = priorityOps.get(rnd.nextInt(priorityOps.size()));
                if (Groupid.contains(randomOp.getGroupId())) {
                    continue;
                }
                Groupid.add(randomOp.getGroupId());
                // 从索引中快速查找位置（O(1)复杂度）
                String key = randomOp.getGroupId() + "_" + randomOp.getSequence();
                Integer opPos = positionIndex.get(key);
                Integer maPos = MachinePositionIndex.get(key);
                List<MachineOption> MachineOptions = randomOp.getMachineOptions();
                if (opPos == null) {
                    continue;
                }

                List<Integer> os = current.getOperationSequencing();

                // 生成多个候选方案
                List<Chromosome> candidates = new ArrayList<>();
                List<Chromosome> candidates1 = new ArrayList<>();



                // 向左多次移动（step 1, 2, 3...）
                for (int s = 1; s <= stepCount; s++) {

                    Entry leftOp = entryIndex.get(opPos - s * step);
                    if (leftOp != null && randomOp.getGroupId() != leftOp.getGroupId() && Math.abs(leftOp.getPriority() - priority) <= 0.001) {

                        Chromosome newChromosome = swapAtDistance(current, opPos, -s * step);
                        candidates.add(newChromosome);
                        candidates1.add(newChromosome);
                        if (MachineOptions.size() > 1) {
                            Chromosome machineChange = generateMachineChange(newChromosome, MachineOptions, maPos);
                            if (machineChange != null) {
                                candidates.add(machineChange);
                                candidates1.add(machineChange);
                            }
                        }


                    } else {
                        break;
                    }
                    if (candidates1.size() > 5) {
                        batchDecode(decoder, candidates1, machines);
                        candidates1.clear();
                    }
                }

                // 向右多次移动（step 1, 2, 3...）
                for (int s = 1; s <= stepCount; s++) {

                    Entry rightOp = entryIndex.get(opPos + s * step);
                    if (rightOp != null && randomOp.getGroupId() != rightOp.getGroupId() && Math.abs(rightOp.getPriority() - priority) <= 0.001) {
                        Chromosome newChromosome = swapAtDistance(current, opPos, s * step);
                        candidates.add(newChromosome);
                        candidates1.add(newChromosome);
                        if (MachineOptions.size() > 1) {
                            Chromosome machineChange = generateMachineChange(newChromosome, MachineOptions, maPos);
                            if (machineChange != null) {
                                candidates.add(machineChange);
                                candidates1.add(machineChange);
                            }
                        }

                    } else {
                        break;
                    }
                    if (candidates1.size() > 5) {
                        batchDecode(decoder, candidates1, machines);
                        candidates1.clear();
                    }
                }


                // 限制最多5个方案并行

                if (candidates1.size() > 0) {
                    batchDecode(decoder, candidates1, machines);
                }

                if (candidates.size() == 0) {
                    break;
                }

                int bestidx = Getbest(candidates, best);
                if (bestidx > -1) {
                    best = candidates.get(bestidx);
                    current =ProductionDeepCopyUtil.deepCopy(best, Chromosome.class);
                    positionIndex = buildPositionIndex(current);
                    entryIndex = buildEntryIndex(current, entrys);
                    //decoder.DelOrder(current);
                }
            }
        }
        return best;
    }

    public Chromosome search(Chromosome chromosome, GeneticDecoder decoder , List<Machine> machines) {
        Chromosome current = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
        decoder.DelOrder(current);
        Chromosome best = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);


        // 构建位置索引映射：groupId_sequence -> position
        Map<String, Integer> positionIndex = buildPositionIndex(current);

        Map<String, Integer> MachinePositionIndex = buildEntryMachinePositionIndex(current);

        int totalCount = 0;
        int noImproveCount = 0;
        int maxNoImprove = 50; // 连续50次没改进就提前停止
        // 构建位置到Entry的映射：position -> Entry
        Map<Integer, Entry> entryIndex = buildEntryIndex(current, entrys);
        boolean improved = false;
        for (Double priority : sortedPriorities) {
            List<Entry> priorityOps = priorityGroups.get(priority);
            if (priorityOps.isEmpty()) {
                continue;
            }
            // 1. 优先处理有多设备选项的工序（最有可能带来改进）
            List<Entry> multiMachineOps = priorityOps.stream()
                    .filter(op -> op.getMachineOptions().size() > 1)
                    .collect(Collectors.toList());

            if (!multiMachineOps.isEmpty()) {
                for (Entry op : multiMachineOps) {
                    String key = op.getGroupId() + "_" + op.getSequence();
                    Integer maPos = MachinePositionIndex.get(key);

                    if (maPos == null) continue;

                    Chromosome machineChange = generateMachineChange(current, op.getMachineOptions(), maPos);
                    if (machineChange != null) {
                        decode(decoder, machineChange,machines);
                        if (isBetter(machineChange, current)) {
                            current = machineChange;
                            if (isBetter(current, best)) {
                                best = ProductionDeepCopyUtil.deepCopy(current, Chromosome.class);
                            }
                            improved = true;
                            noImproveCount=0;
                            positionIndex = buildPositionIndex(current);
                            entryIndex = buildEntryIndex(current, entrys);
                            MachinePositionIndex = buildEntryMachinePositionIndex(current);
                            break;
                        }
                        decoder.DelOrder(current);
                    }
                }
                if (improved) break;
            }

            if (improved) continue;

            // 2. 检查是否是单一订单（如果只有一个订单，不需要交换位置
            Set<Integer> groupIds = priorityOps.stream()
                    .map(Entry::getGroupId)
                    .collect(Collectors.toSet());

            if (groupIds.size() <= 1) {
                continue;
            }

            // 根据当前优先级的工序数确定迭代次数和step
            int priorityIterations = Math.max(5, priorityOps.size() / 2);

             priorityIterations = Math.min(priorityIterations, priorityOps.size());
            // 200/10 =20
            // 1
            int step = Math.max(1, (int) Math.ceil(priorityOps.size() / 10.0));
            // 200/20=10;
            //
            int stepCount = Math.max(1, (int) Math.ceil(priorityOps.size() / step));
            Set<Integer> processedGroupIds = new HashSet<>();

            for (int pi = 0; pi < priorityIterations; pi++) {
                Entry randomOp = priorityOps.get(rnd.nextInt(priorityOps.size()));
                if (processedGroupIds.contains(randomOp.getGroupId())) {
                    continue;
                }
                processedGroupIds.add(randomOp.getGroupId());

                String key = randomOp.getGroupId() + "_" + randomOp.getSequence();
                Integer opPos = positionIndex.get(key);
                if (opPos == null) {
                    continue;
                }

                boolean foundBetter = false;

                // 向左逐步尝试
                for (int s = 1; s <= stepCount; s++) {
                    int targetPos = opPos - s * step;
                    Entry leftOp = entryIndex.get(targetPos);

                    if (leftOp == null || randomOp.getGroupId() == leftOp.getGroupId()
                            || Math.abs(leftOp.getPriority() - priority) > 0.001) {
                        break;
                    }

                    Chromosome newChromosome = swapAtDistance(current, opPos, -s * step);
                    decode(decoder, newChromosome,machines);

                    if (isBetter(newChromosome, current)) {
                        current = newChromosome;
                        if (isBetter(current, best)) {
                            best = ProductionDeepCopyUtil.deepCopy(current, Chromosome.class);
                        }
                        improved = true;
                        foundBetter = true;
                        noImproveCount=0;
                        positionIndex = buildPositionIndex(current);
                        entryIndex = buildEntryIndex(current, entrys);
                        decoder.DelOrder(current);
                        break;
                    }
                }

                if (foundBetter) break;

                // 向右逐步尝试
                for (int s = 1; s <= stepCount; s++) {
                    int targetPos = opPos + s * step;
                    Entry rightOp = entryIndex.get(targetPos);

                    if (rightOp == null || randomOp.getGroupId() == rightOp.getGroupId()
                            || Math.abs(rightOp.getPriority() - priority) > 0.001) {
                        break;
                    }

                    Chromosome newChromosome = swapAtDistance(current, opPos, s * step);
                    decode(decoder, newChromosome,machines);

                    if (isBetter(newChromosome, current)) {
                        current = newChromosome;
                        if (isBetter(current, best)) {
                            best = ProductionDeepCopyUtil.deepCopy(current, Chromosome.class);
                        }
                        improved = true;
                        foundBetter = true;
                        noImproveCount=0;
                        positionIndex = buildPositionIndex(current);
                        entryIndex = buildEntryIndex(current, entrys);
                        decoder.DelOrder(current);
                        break;
                    }
                }

                if (foundBetter) break;
                noImproveCount++;
                totalCount++;
                if(noImproveCount>maxNoImprove)
                {
                    FileHelper.writeLogFile(String.format("爬山法 - 提前停止：迭代%d次",
                            totalCount));
                    improved=true;
                    break;
                }
            }
            if (improved) break;
        }


        return best;
    }

    private int  Getbest(List<Chromosome> candidates,Chromosome best) {
        // 找出最佳候选方案

        int bestidx = -1;
        if(best==null)
        {
            best=candidates.get(0);
            bestidx=0;
        }
        for (int i = 0; i < candidates.size(); i++) {
            Chromosome candidate = candidates.get(i);
            writeKpi(candidate);
            if (isBetter(candidate, best)) {
                bestidx = i;
            }
        }

        return bestidx;
    }


    private  void  writeKpi(Chromosome chromosome) {
        String fitness = "";
        double[] fitness1 = chromosome.getFitnessLevel();
        for (int i = 0; i < fitness1.length; i++) {

            fitness += fitness1[i] + ",";
        }

        FileHelper.writeLogFile(String.format("爬山法%s - kpi：%s",chromosome.getGeneStr(), fitness));
      if(chromosome.getMakespan()!=0) {
          FileHelper.writeLogFile(String.format("爬山法%s - kpi-Makespan: %f", chromosome.getGeneStr(), chromosome.getMakespan()));
      }
        if(chromosome.getDelayTime()!=0) {
            FileHelper.writeLogFile(String.format("爬山法%s - kpi-DelayTime: %f", chromosome.getGeneStr(), chromosome.getDelayTime()));
        }
        if(chromosome.getTotalChangeoverTime()!=0) {

        FileHelper.writeLogFile(String.format("爬山法%s - kpi-ChangeoverTime: %f",chromosome.getGeneStr(), chromosome.getTotalChangeoverTime()));
        }
        if(chromosome.getMachineLoadStd()!=0) {
            FileHelper.writeLogFile(String.format("爬山法%s - kpi-MachineLoad: %f",chromosome.getGeneStr(), chromosome.getMachineLoadStd()));
        }
        if(chromosome.getTotalFlowTime()!=0) {
        FileHelper.writeLogFile(String.format("爬山法%s - kpi-FlowTime: %f",chromosome.getGeneStr(), chromosome.getTotalFlowTime()));
        }



    }
    /**
     * 构建位置索引：groupId_sequence -> position
     */
    private Map<String, Integer> buildPositionIndex(Chromosome chromosome) {

        writeKpi(chromosome);


        Map<String, Integer> index = new HashMap<>();
        List<Integer> os = chromosome.getOperationSequencing();
        Map<Integer, Integer> orderProcessCounter = new HashMap<>();

        for (int i = 0; i < os.size(); i++) {
            int groupId = os.get(i);
            int count = orderProcessCounter.getOrDefault(groupId, 0) + 1;
            orderProcessCounter.put(groupId, count);

            String key = groupId + "_" + count;
            index.put(key, i);
        }
        return index;
    }

    /**
     * 构建位置索引：groupId_sequence -> Machines position
     */
    private Map<String, Integer> buildEntryMachinePositionIndex(Chromosome chromosome) {
        Map<String, Integer> index = new HashMap<>();
        List<GlobalOperationInfo> globalOpList = chromosome.getGlobalOpList();

        for (int i = 0; i < globalOpList.size(); i++) {
            GlobalOperationInfo globalOp= globalOpList.get(i);
           Entry op= globalOp.getOp();
            int groupId = op.getGroupId();
            int count = op.getSequence();

            String key = groupId + "_" + count;
            index.put(key, i);
        }
        return index;
    }

    /**
     * 构建Entry索引：position -> Entry
     */
    private Map<Integer, Entry> buildEntryIndex(Chromosome chromosome,Map<String, Entry> entrys) {
        Map<Integer, Entry> index = new HashMap<>();
        List<Integer> os = chromosome.getOperationSequencing();

        Map<Integer, Integer> orderProcessCounter = new HashMap<>();

        for (int i = 0; i < os.size(); i++) {
            int groupId = os.get(i);
            int count = orderProcessCounter.getOrDefault(groupId, 0) + 1;
            orderProcessCounter.put(groupId, count);
            String key = groupId + "_" + count;
            Entry op=entrys.get(key);
            if(op!=null)
            {
                index.put(i, op);
            }

        }
        return index;
    }

    /**
     * 构建Entry索引：op.getGroupId() + "_" + op.getSequence() -> Entry
     */
    private Map<String, Entry> buildEntryKey() {
        Map<String, Entry> index = new HashMap<>();

        for (Entry op : allOperations) {
            String key = op.getGroupId() + "_" + op.getSequence();

            index.put(key, op);
        }

        return index;
    }

    /**
     * 按优先级分组工序
     */
    private Map<Double, List<Entry>> groupOperationsByPriority() {
        Map<Double, List<Entry>> groups = new HashMap<>();
        for (Entry op : allOperations) {
            double priority = op.getPriority();
            groups.computeIfAbsent(priority, k -> new ArrayList<>()).add(op);
        }
        // 过滤掉：设备只有一个且只有一个GroupId的优先级组
        Map<Double, List<Entry>> filteredGroups = new HashMap<>();
        for (Map.Entry<Double, List<Entry>> entry : groups.entrySet()) {
            List<Entry> ops = entry.getValue();

            // 检查是否所有工序都只有一个设备选项
            boolean allSingleMachine = ops.stream()
                    .filter(t->t.getMachineOptions()!=null)
                    .allMatch(op -> op.getMachineOptions().size() <= 1);

            // 检查是否只有一个GroupId
            Set<Integer> groupIds = ops.stream()
                    .map(Entry::getGroupId)
                    .collect(Collectors.toSet());

            // 如果两个条件都满足，过滤掉这个优先级组
            if (!(allSingleMachine && groupIds.size() <= 1)) {
                filteredGroups.put(entry.getKey(), ops);
            }
        }

        return filteredGroups;
    }

    /**
     * 将指定位置的工序与间隔distance的工序交换
     * distance为负表示向左，为正表示向右
     */
    private Chromosome swapAtDistance(Chromosome chromosome, int pos, int distance) {
        Chromosome neighbor = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
        CopyOnWriteArrayList<Integer> os = neighbor.getOperationSequencing();
        int targetPos = pos + distance;
        if (targetPos >= 0 && targetPos < os.size() && pos >= 0 && pos < os.size()) {
            java.util.Collections.swap(os, pos, targetPos);
            neighbor.setOperationSequencing(os);
        }
        return neighbor;
    }
    /**
     * 生成机器选择邻域解
     */
    private Chromosome generateMachineChange(Chromosome chromosome, List<MachineOption> MachineOptions, int idx) {
        Chromosome neighbor = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
        CopyOnWriteArrayList<Integer> ms = neighbor.getMachineSelection();
        if (!ms.isEmpty()) {



            if (MachineOptions.size() > 1) {
                int currentMachineSeq = ms.get(idx);
                List<Integer> availableMachines = new ArrayList<>();
                for (int i = 1; i <= MachineOptions.size(); i++) {
                    if (i != currentMachineSeq) {
                        availableMachines.add(i);
                    }
                }

                if (!availableMachines.isEmpty()) {
                    int newMachineSeq = availableMachines.get(rnd.nextInt(availableMachines.size()));
                    ms.set(idx, newMachineSeq);
                    neighbor.setMachineSelection(ms);
                }
            }
            return  null;
        }
        return neighbor;
    }

    private void batchDecode(GeneticDecoder decoder,List<Chromosome> chromosomes, List<Machine> machines )
    {

        for (Chromosome chromosome :chromosomes) {
            chromosome.setResult(new CopyOnWriteArrayList<>());

            // 假设Machine类有拷贝方法，或使用MapStruct等工具进行映射

            chromosome.setMachines(ProductionDeepCopyUtil.deepCopyList(machines,Machine.class)); // 简单拷贝，实际可能需要深拷贝
            chromosome.setOrders(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(orders), Order.class) ); // 简单拷贝，实际可能需要深拷贝
            chromosome.setOperatRel(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(_entryRel), GroupResult.class) ); // 简单拷贝，实际可能需要深拷贝
            chromosome.setMaterials(ProductionDeepCopyUtil.deepCopyTreeMap(materials,String.class,Material.class)); // 简单拷贝，实际可能需要深拷贝

            chromosome.setAllOperations(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(allOperations), Entry.class) ); // 简单拷贝，实际可能需要深拷贝

            // 加载锁定工单到ResultOld
            List<GAScheduleResult> lockedOrders = GlobalCacheUtil.get("locked_orders_" + chromosome.getScenarioID());
            if (lockedOrders != null && !lockedOrders.isEmpty()) {
                chromosome.setResultOld(ProductionDeepCopyUtil.deepCopyList(lockedOrders, GAScheduleResult.class));
                FileHelper.writeLogFile("将 " + lockedOrders.size() + " 个锁定工单加载到初始种群中");
            } else {
                chromosome.setResultOld(new CopyOnWriteArrayList<>());
            }
        }

        // 并行解码所有候选方案
        decoder.Chromosomedecode(chromosomes);
    }

    /**
     * 解码染色体
     */
    private void decode(GeneticDecoder decoder, Chromosome chromosome , List<Machine> machines) {
        chromosome.setResult(new CopyOnWriteArrayList<>());

        // 假设Machine类有拷贝方法，或使用MapStruct等工具进行映射

        chromosome.setMachines(ProductionDeepCopyUtil.deepCopyList(machines,Machine.class)); // 简单拷贝，实际可能需要深拷贝
        chromosome.setOrders(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(orders), Order.class) ); // 简单拷贝，实际可能需要深拷贝
        chromosome.setOperatRel(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(_entryRel), GroupResult.class) ); // 简单拷贝，实际可能需要深拷贝
        chromosome.setMaterials(ProductionDeepCopyUtil.deepCopyTreeMap(materials,String.class,Material.class)); // 简单拷贝，实际可能需要深拷贝

        chromosome.setAllOperations(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(allOperations), Entry.class) ); // 简单拷贝，实际可能需要深拷贝
        //chromosome.setObjectiveWeights(_objectiveWeights);
        //  chromosome.setBaseTime(param.getBaseTime());
        //  chromosome.setInitMachines(ProductionDeepCopyUtil.deepCopyList(machines,Machine.class)); // 简单拷贝，实际可能需要深拷贝
        //   _sceneService.saveChromosomeToFile(chromosome, "12345679");

        // 加载锁定工单到ResultOld
        List<GAScheduleResult> lockedOrders = GlobalCacheUtil.get("locked_orders_" + chromosome.getScenarioID());
        if (lockedOrders != null && !lockedOrders.isEmpty()) {
            chromosome.setResultOld(ProductionDeepCopyUtil.deepCopyList(lockedOrders, GAScheduleResult.class));
            FileHelper.writeLogFile("将 " + lockedOrders.size() + " 个锁定工单加载到初始种群中");
        } else {
            chromosome.setResultOld(new CopyOnWriteArrayList<>());
        }
        decoder.decodeChromosomeWithCache(chromosome,false);

    }


    /**
     * 比较两个染色体的优劣
     */
    public boolean isBetter(Chromosome c1, Chromosome c2) {
        double[] fitness1 = c1.getFitnessLevel();
        double[] fitness2 = c2.getFitnessLevel();

        // 处理null或空数组的情况
        if (fitness1 == null || fitness1.length == 0) {
            return false; // c1没有fitness，认为c2更优
        }
        if (fitness2 == null || fitness2.length == 0) {
            return true; // c2没有fitness，认为c1更优
        }

        // 取两个数组中较小的长度进行比较
        int minLength = Math.min(fitness1.length, fitness2.length);
        for (int i = 0; i < minLength; i++) {
            if (fitness1[i] > fitness2[i]) {
                return true;
            } else if (fitness1[i] < fitness2[i]) {
                return false;
            }
        }

        // 如果前面都相等，长度更长的视为更优（有更多维度）
        return fitness1.length > fitness2.length;
    }
}