package com.aps.controller.gantt;


import com.aps.entity.Gantt.ProductGanttVO;
import com.aps.entity.Gantt.ResourceGanttVO;
import com.aps.entity.Gantt.TaskVO;
import com.aps.entity.Schedule.MachineVO;
import com.aps.entity.basic.*;
import com.aps.service.plan.PlanResultService;
import com.aps.service.plan.PlanSchedulerService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/Gantt")
@Tag(name = "甘特图管理", description = "甘特图管理")
public class ResourceGanttController {

    @Autowired
    private PlanSchedulerService schedulingService;
    
    @Autowired
    private PlanResultService planResultService;

    @GetMapping("/resourceGantt")
    @Operation(summary = "获取资源甘特图数据", description = "获取资源甘特图数据")
    public List<ResourceGanttVO> getResourceGantt(@RequestParam(required = false, defaultValue = "1") Long sceneId) {
        // 从PlanResultService获取ScheduleChromosome列表
        List<ScheduleChromosome> scheduleChromosomes = planResultService.execute();
        
        // 根据sceneId查找对应的ScheduleChromosome
        ScheduleChromosome targetChromosome = null;
        for (ScheduleChromosome chromosome : scheduleChromosomes) {
            if (chromosome.getSceneId() == sceneId) {
                targetChromosome = chromosome;
                break;
            }
        }
        
        // 如果找不到对应的场景，返回空列表
        if (targetChromosome == null) {
            return new ArrayList<>();
        }
        
        // 转换为 ResourceGanttVO 格式
        List<ResourceGanttVO> resourceGanttVOList = new ArrayList<>();
        List<ResourceGanttVO> resourceGanttVOs = convertToResourceGanttVO(targetChromosome);
        resourceGanttVOList.addAll(resourceGanttVOs);
        
        return resourceGanttVOList;
    }
    
    @GetMapping("/productGantt")
    @Operation(summary = "获取产品甘特图数据", description = "获取产品甘特图数据")
    public List<ProductGanttVO> getProductGantt(@RequestParam(required = false, defaultValue = "1") Long sceneId) {
        // 从PlanResultService获取ScheduleChromosome列表
        List<ScheduleChromosome> scheduleChromosomes = planResultService.execute();
        
        // 根据sceneId查找对应的ScheduleChromosome
        ScheduleChromosome targetChromosome = null;
        for (ScheduleChromosome chromosome : scheduleChromosomes) {
            if (chromosome.getSceneId() == sceneId) {
                targetChromosome = chromosome;
                break;
            }
        }
        
        // 如果找不到对应的场景，返回空列表
        if (targetChromosome == null) {
            return new ArrayList<>();
        }
        
        // 转换为 ProductGanttVO 格式
        List<ProductGanttVO> productGanttVOList = new ArrayList<>();
        List<ProductGanttVO> productGanttVOs = convertToProductGanttVO(targetChromosome);
        productGanttVOList.addAll(productGanttVOs);
        
        return productGanttVOList;
    }
    
    @GetMapping("/sceneIds")
    @Operation(summary = "获取所有场景ID", description = "获取所有场景ID")
    public List<Long> getSceneIds() {
        // 调用 PlanResultService 获取 ScheduleChromosome 列表
        List<ScheduleChromosome> scheduleChromosomes = planResultService.execute();
        
        // 提取所有场景ID
        return scheduleChromosomes.stream()
                .map(ScheduleChromosome::getSceneId)
                .collect(Collectors.toList());
    }
    
    /**
     * 将 ScheduleChromosome 转换为 ResourceGanttVO 列表
     * @param scheduleChromosome 调度结果
     * @return 转换后的数据
     */
    private List<ResourceGanttVO> convertToResourceGanttVO(ScheduleChromosome scheduleChromosome) {
        List<ResourceGanttVO> resourceGanttVOList = new ArrayList<>();
        
        // 遍历所有机器资源
        if (scheduleChromosome.getMachines() != null) {
            for (int i = 0; i < scheduleChromosome.getMachines().size(); i++) {
                Machine machine = scheduleChromosome.getMachines().get(i);
                
                ResourceGanttVO resourceGanttVO = new ResourceGanttVO();
                resourceGanttVO.setId(machine.getId());
                resourceGanttVO.setName(machine.getName() != null ? machine.getName() : "设备-" + machine.getId());
                resourceGanttVO.setType("设备类型"+machine.getId()); // 需要从原始数据获取
                resourceGanttVO.setChange(0); // 默认值
                resourceGanttVO.setSplit(0); // 默认值
                resourceGanttVO.setDepartmentId(machine.getId()); // 默认值
                resourceGanttVO.setDepartmentName(machine.getId()+"号线"); // 默认值
                resourceGanttVO.setShopName(machine.getId()+"车间"); // 默认值
                resourceGanttVO.setShopId(machine.getId()); // 默认值
                resourceGanttVO.setCode("设备编码-" + machine.getId()); // 默认值
              resourceGanttVO.setShift(convertToVO(machine));
                // 转换任务列表
                List<TaskVO> taskVOList = new ArrayList<>();
                if (scheduleChromosome.getGenes() != null) {
                    // 筛选出属于当前设备的任务
                    List<Gene> machineGenes = scheduleChromosome.getGenes().stream()
                            .filter(gene -> gene.getMachineId()==(machine.getId()))
                            .collect(Collectors.toList());
                    
                    // 按开始时间排序
                    machineGenes.sort((g1, g2) -> Integer.compare(g1.getStartTime(), g2.getStartTime()));
                    
                    for (Gene gene : machineGenes) {
                        TaskVO taskVO = new TaskVO();
                        taskVO.setId(gene.getId()); // 临时处理
                        taskVO.setPlanId(gene.getOrderId()); // 默认值
                        taskVO.setProductType(0); // 默认值
                        taskVO.setProductName("产品"+gene.getProductId());
                        taskVO.setProductId(gene.getProductId()); // 默认值
                        taskVO.setQuantity(gene.getBatchSize());
                        taskVO.setStart(scheduleChromosome.getBaseTime().plusMinutes(gene.getAbsoluteStartTime()));
                        taskVO.setEnd(scheduleChromosome.getBaseTime().plusMinutes(gene.getAbsoluteEndTime()));
                        taskVO.setSetup(gene.getAbsolutePreparationTime()*60); // 默认值
                        taskVO.setTeardown(gene.getAbsoluteTeardownTime()*60); // 默认值
                        taskVO.setEquipChange(gene.getSetupTime()*60); // 默认值
                        taskVO.setEquipCooling(0); // 默认值
                        taskVO.setEquipType(resourceGanttVO.getType());
                        taskVO.setEquipName(resourceGanttVO.getName());
//                        taskVO.setDuration(calculateDuration(
//                                scheduleChromosome.getBaseTime().plusMinutes(gene.getStartTime()),
//                                scheduleChromosome.getBaseTime().plusMinutes(gene.getEndTime()))); // 计算持续时间

                        taskVO.setDuration(0); //
                        taskVO.setEquipId(machine.getId());
                        taskVO.setShopId(machine.getId());
                        taskVO.setShopName(resourceGanttVO.getShopName());
                        taskVO.setStatus(0); // 默认值

                        taskVO.setDetailId((long) gene.getProductId() * 1000 + gene.getOperationId()); // 将productId和operationID组合为detailId
                        taskVO.setHeaderId(gene.getProductId()); // 默认值
                        taskVO.setHeaderName("工艺"+gene.getProductId()); // 默认值
                        taskVO.setSeq(gene.getSequenceId()); // 使用工序ID
                        taskVO.setSeqName( "工序名称"+gene.getSequenceId());
                        taskVO.setProcessingTime(gene.getProcessingTime()*60);
                        taskVO.setAbsoluteStart(scheduleChromosome.getBaseTime().plusMinutes(gene.getStartTime()));
                        taskVO.setAbsoluteEnd(scheduleChromosome.getBaseTime().plusMinutes(gene.getEndTime()));
                        taskVOList.add(taskVO);
                        
                        // 调试：检查machine中的shifts状态
//                        if (machine.getShifts() != null) {
//                            for (Shift shift : machine.getShifts()) {
//                                System.out.println("Before setting shifts - Shift status: " + shift.getStatus());
//                            }
//                        }
                        
                        taskVO.setAbsolutePreparationTime(gene.getTeardownTime());

                        

                    }
                }
                
                resourceGanttVO.setList(taskVOList);
                resourceGanttVOList.add(resourceGanttVO);
            }
        }
        
        return resourceGanttVOList;
    }
    
    /**
     * 将 ScheduleChromosome 转换为 ProductGanttVO 列表
     * @param scheduleChromosome 调度结果
     * @return 转换后的数据
     */
    private List<ProductGanttVO> convertToProductGanttVO(ScheduleChromosome scheduleChromosome) {
        List<ProductGanttVO> productGanttVOList = new ArrayList<>();
        
        // 按产品ID和工单ID分组基因
        if (scheduleChromosome.getGenes() != null) {
            // 按工单ID分组
            scheduleChromosome.getGenes().stream()
                .collect(Collectors.groupingBy(Gene::getOrderId))
                .forEach((orderId, genes) -> {
                    if (!genes.isEmpty()) {
                        ProductGanttVO productGanttVO = new ProductGanttVO();
                        Gene firstGene = genes.get(0);
                        productGanttVO.setId(firstGene.getId());
                        productGanttVO.setProductName("产品"+firstGene.getProductId()); // 默认值，实际应从订单数据获取
                        productGanttVO.setProductType(0);
                        productGanttVO.setProductId(firstGene.getProductId());
                        // 计算总数量（假设同一批次）
                        productGanttVO.setQuantity(firstGene.getBatchSize());
                        productGanttVO.setCode("编号"+firstGene.getProductId()); // 默认值
                        productGanttVO.setShopId(firstGene.getMachineId()); // 默认值
                        productGanttVO.setShopName(firstGene.getMachineId()+"号线"); // 默认值
                        productGanttVO.setStatus("已发布");
                        productGanttVO.setHeaderId(firstGene.getProductId());
                        productGanttVO.setHeaderName("工艺"+firstGene.getProductId()); // 默认值
                        
                        // 计算开始和结束时间
                        int minStartTime = genes.stream()
                            .mapToInt(Gene::getStartTime)
                            .min()
                            .orElse(0);
                        int maxEndTime = genes.stream()
                            .mapToInt(Gene::getEndTime)
                            .max()
                            .orElse(0);
                            
                        productGanttVO.setStartDate(scheduleChromosome.getBaseTime().plusMinutes(minStartTime));
                        productGanttVO.setEndDate(scheduleChromosome.getBaseTime().plusMinutes(maxEndTime));
                        
                        // 转换任务列表
                        List<TaskVO> taskVOList = new ArrayList<>();
                        // 按工序顺序排序
                        genes.sort((g1, g2) -> Integer.compare(g1.getSequenceId(), g2.getSequenceId()));
                        
                        for (int i = 0; i < genes.size(); i++) {
                            Gene gene = genes.get(i);
                            TaskVO taskVO = new TaskVO();
                            taskVO.setId(gene.getId()); // 生成唯一ID
                            taskVO.setPlanId(orderId);
                            taskVO.setProductType(0);
                            taskVO.setProductName("产品"+gene.getProductId());
                            taskVO.setProductId(gene.getProductId());
                            taskVO.setQuantity(gene.getBatchSize());
                            taskVO.setStart(scheduleChromosome.getBaseTime().plusMinutes(gene.getAbsoluteStartTime()));
                            taskVO.setEnd(scheduleChromosome.getBaseTime().plusMinutes(gene.getAbsoluteEndTime()));
                            taskVO.setSetup(gene.getAbsolutePreparationTime()*60); // 默认值
                            taskVO.setTeardown(gene.getAbsoluteTeardownTime()*60); // 默认值
                            taskVO.setEquipChange(gene.getSetupTime()*60); // 默认值
                            taskVO.setEquipCooling(0); // 默认值
//                            taskVO.setEquipType("PTT-" + (i+1) + "-" + gene.getOperationName().toUpperCase().substring(0, Math.min(3, gene.getOperationName().length())));
//                            taskVO.setEquipName(gene.getOperationName());
                            taskVO.setDuration(calculateDuration(
                                    scheduleChromosome.getBaseTime().plusMinutes(gene.getStartTime()), 
                                    scheduleChromosome.getBaseTime().plusMinutes(gene.getEndTime())));
                            taskVO.setEquipId(gene.getMachineId()); // 生成设备ID
                            taskVO.setShopId(gene.getMachineId());
                            taskVO.setShopName(gene.getMachineId()+"车间");
                            taskVO.setStatus(0);
                            taskVO.setDetailId((long) gene.getProductId() * 1000 + gene.getOperationId());
                            taskVO.setHeaderId(gene.getProductId());
                            taskVO.setHeaderName("工艺"+gene.getProductId());
                            taskVO.setSeq(gene.getSequenceId());
                            taskVO.setSeqName("工序名称"+gene.getSequenceId());
                            taskVO.setAbsoluteStart(scheduleChromosome.getBaseTime().plusMinutes(gene.getStartTime()));
                            taskVO.setAbsoluteEnd(scheduleChromosome.getBaseTime().plusMinutes(gene.getEndTime()));

                            taskVOList.add(taskVO);
                        }
                        
                        productGanttVO.setList(taskVOList);
                        productGanttVOList.add(productGanttVO);
                    }
                });
        }
        
        return productGanttVOList;
    }

    /**
     * 计算任务持续时间（分钟）
     * @param start 开始时间
     * @param end 结束时间
     * @return 持续时间（分钟）
     */
    private Integer calculateDuration(LocalDateTime start, LocalDateTime end) {
        if (start == null || end == null) {
            return 0;
        }
        return Math.toIntExact(java.time.Duration.between(start, end).toMinutes());
    }


    private ShiftVO convertToVO(Machine machine) {
        ShiftVO shiftVO= new ShiftVO();
        shiftVO.setId(machine.getId());
        shiftVO.setName(machine.getName());
        shiftVO.setShifts(machine.getShifts());
        shiftVO.setMaintenanceWindows(machine.getMaintenanceWindows());
        // 注意：tasks 字段需要在其他地方设置，因为 Machine 类中没有任务信息
        return shiftVO;
    }
}