package com.aps.service.plan;

import com.aps.common.util.JsonFileReader;
import com.aps.entity.Schedule.GenVO;
import com.aps.entity.Schedule.MachineVO;
import com.aps.entity.Schedule.PlanResourceTaskGanttVO;
import com.aps.entity.basic.*;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PlanSchedulerService {
    private final LocalDateTime baseTime = LocalDateTime.of(2025, 10, 1, 0, 0, 0);

    public List<PlanResourceTaskGanttVO> execute() {
        try {
            // 1. 读取数据
            List<Machine> machines = JsonFileReader.readListFromResources("machines.json", Machine.class);
            List<Product> products = JsonFileReader.readListFromResources("products.json", Product.class);
            List<Order> orders = JsonFileReader.readListFromResources("orders.json", Order.class);

            // 2. 创建节假日
            List<Holiday> holidays = Arrays.asList(
                    new Holiday(LocalDateTime.of(2025, 10, 1, 0, 0),
                            LocalDateTime.of(2025, 10, 7, 23, 59))
            );

            // 3. 创建调度服务
            MachineSchedulerService machineScheduler = new MachineSchedulerService(
                    holidays, LocalDateTime.of(2025, 10, 1, 0, 0, 0));

            // 4. 初始化机器时间线
            for (Machine machine : machines) {
                MachineTimeline timeline = machineScheduler.getOrCreateTimeline(machine);
                machine.setAvailability(timeline.getSegments());
            }

            // 5. 执行调度算法
            AlgorithmScheduler6 scheduler = new AlgorithmScheduler6(products, machines, orders, machineScheduler);
            List<ScheduleChromosome> scheduleChromosomes = scheduler.RunAll();
            List<PlanResourceTaskGanttVO> ganttlist = new ArrayList<>();
            long sceneId = 1L;


            for (ScheduleChromosome chromosome : scheduleChromosomes
                 ) {

                // 转换基因列表和设备列表
                List<GenVO> genVOS = convertGeneListToGenVO(chromosome.getGenes(), baseTime);
                List<MachineVO> machineVOS = machines.stream()
                        .map(this::convertToVO)
                        .collect(Collectors.toList());

// 按设备ID分组任务
                Map<Integer, List<GenVO>> taskMap = genVOS.stream()
                        .collect(Collectors.groupingBy(GenVO::getEquipId));

// 为每个设备设置任务
                for (MachineVO machine : machineVOS) {
                    Integer equipId = Integer.valueOf(machine.getEquipId());
                    List<GenVO> tasks = taskMap.get(equipId);

                    if (tasks != null) {
                        // 按开始时间排序
                        tasks.sort(Comparator.comparing(GenVO::getStartTime));
                        machine.setTasks(tasks);
                    } else {
                        machine.setTasks(new ArrayList<>()); // 如果没有任务，设置为空列表
                    }
                }

// 现在machineVOS中的每个MachineVO都包含了对应的任务列表
                PlanResourceTaskGanttVO ganttVO = new PlanResourceTaskGanttVO()
                        .setResources(machineVOS)
                        .setEarliestTaskStartTime(LocalDateTime.of(2025, 9, 1, 0, 0, 0))
                        .setLastTaskAssignmentTime(LocalDateTime.of(2025, 12, 1, 0, 0, 0))
                        .setSceneId(sceneId);
                sceneId++;
                ganttlist.add(ganttVO);
            }




            return ganttlist;

        } catch (Exception e) {
            throw new RuntimeException("调度执行失败", e);
        }
    }

    public GenVO convertGeneToGenVO(Gene gene, LocalDateTime baseTime) {
        GenVO genVO = new GenVO();
        genVO.setOrderId(String.valueOf(gene.getOrderId()));
        genVO.setOperationId(gene.getOperationId());
        genVO.setEquipId(gene.getMachineId());
        genVO.setQuantity(BigDecimal.valueOf(gene.getBatchSize()));
        genVO.setStartTime(baseTime.plusMinutes(gene.getStartTime()));
        genVO.setEndTime(baseTime.plusMinutes(gene.getEndTime()));
        genVO.setOperationName(""); // 从其他数据源获取
        genVO.setEquipName(""); // 从其他数据源获取
        return genVO;
    }

    // 批量转换
    public List<GenVO> convertGeneListToGenVO(List<Gene> geneList, LocalDateTime baseTime) {
        return geneList.stream()
                .map(gene -> convertGeneToGenVO(gene, baseTime))
                .collect(Collectors.toList());
    }
    private MachineVO convertToVO(Machine machine) {
        MachineVO machineVO = new MachineVO();
        machineVO.setId(machine.getId());
        machineVO.setEquipId(String.valueOf(machine.getId()));
        machineVO.setEquipName(machine.getName());
        return machineVO;
    }
}