package com.aps.service.Algorithm;

import com.aps.entity.Algorithm.OperationSequencingWeight;
import com.aps.entity.basic.Entry;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 作者：佟礼
 * 时间：2025-11-21
 */
public class CommonCalculator {
    public static List<OperationSequencingWeight> getOsw(List<Integer> os, List<Entry> allOperations) {
        // 计算最大优先级并加1
        double maxPriority = allOperations.stream()
                .mapToDouble(Entry::getPriority)
                .max()
                .orElse(0) + 1;

        // 为每个工序分配权重
        List<OperationSequencingWeight> weightedOs = new ArrayList<>();
        for (int idx = 0; idx < os.size(); idx++) {
            int groupId = os.get(idx);
            // 查找对应groupId的第一个操作
            Entry entry = allOperations.stream()
                    .filter(o -> o.getGroupId() == groupId)
                    .findFirst()
                    .orElse(null);
            OperationSequencingWeight osw = new OperationSequencingWeight();
            osw.setIndex(idx);
            osw.setOsValue(groupId);
            osw.setWeight(maxPriority - entry.getPriority());
            weightedOs.add(osw);
        }

        return weightedOs;
    }
    public static int getOsIndex(List<OperationSequencingWeight> indexWeights) {
        Random rnd = new Random();
        double totalWeight = indexWeights.stream()
                .mapToDouble(OperationSequencingWeight::getWeight)
                .sum();
        int randomWeight = rnd.nextInt((int)totalWeight);
        int cumulativeWeight = 0;
        for (OperationSequencingWeight w : indexWeights) {
            cumulativeWeight += w.getWeight();
            if (cumulativeWeight >= randomWeight) {
                return w.getIndex();
            }
        }
        return 0;
    }
    public static int getOsIndex2(List<OperationSequencingWeight> weightedOs) {
        Random rnd = new Random();
        double totalWeight = weightedOs.stream()
                .mapToDouble(OperationSequencingWeight::getWeight)
                .sum();
        int randomWeight = rnd.nextInt((int)totalWeight);
        int cumulativeWeight = 0;
        int selectedIndex = -1;
        for (int i = 0; i < weightedOs.size(); i++) {
            cumulativeWeight += weightedOs.get(i).getWeight();
            if (cumulativeWeight >= randomWeight) {
                selectedIndex = i;
                break;
            }
        }
        return 0;
    }
}
