package com.aps.controller;

import com.aps.common.util.R;
import com.aps.entity.*;
import com.aps.entity.Gantt.PlanResourceTaskGanttVO;
import com.aps.entity.Gantt.SimpleEquipinfo;
import com.aps.service.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
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.RestController;

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

@RestController
@RequestMapping("/ganttest")
@Tag(name = "甘特图", description = "甘特图相关接口")
public class ScheduleResultController {

    @Autowired
    private ScheduleService schedulerService;

    @Autowired
    private MpsplannedorderService orderService;

    @Autowired
    private RoutingHeaderService processService;

    @Autowired
    private RoutingDetailService operationService;

    @Autowired
    private RoutingDetailEquipService operationEquipService;

    @Autowired
    private EquipinfoService equipmentService;
    
    @Operation(summary = "资源甘特图", description = "资源甘特图")
    @GetMapping("/resource")
    public R<PlanResourceTaskGanttVO> runScheduling() {
        try {
            // 获取routingid为'SY1102507-0056202车间-21号线'和'SY1102507-0060202车间-21号线'的待调度工单
            List<Mpsplannedorder> orders = orderService.lambdaQuery()
                    .in(Mpsplannedorder::getRoutingid, "SY1102507-0056202车间-21号线", "SY1102507-0060202车间-21号线")
                    .list();

            if (orders.isEmpty()) {
                // 当没有订单时，返回空的甘特图VO
                PlanResourceTaskGanttVO ganttVO = new PlanResourceTaskGanttVO()
                        .setTasks(new ArrayList<>())
                        .setResources(new ArrayList<>())
                        .setEarliestTaskStartTime(LocalDateTime.of(2025, 6, 1, 0, 0, 0))
                        .setLastTaskAssignmentTime(LocalDateTime.of(2025, 12, 1, 0, 0, 0));
                return R.ok(ganttVO);
            }

            // 提取所需的工艺ID列表
            Set<String> routingIds = orders.stream()
                    .map(Mpsplannedorder::getRoutingid)
                    .collect(Collectors.toSet());

            // 根据工单获取相关工艺
            List<RoutingHeader> processes = processService.lambdaQuery()
                    .in(RoutingHeader::getCode, routingIds)
                    .list();

            if (processes.isEmpty()) {
                return R.failed("未找到相关工艺信息");
            }

            // 提取工艺ID用于后续查询
            Set<Integer> processIds = processes.stream()
                    .map(RoutingHeader::getId)
                    .collect(Collectors.toSet());

            // 根据工艺获取相关工序
            List<RoutingDetail> operations = operationService.lambdaQuery()
                    .in(RoutingDetail::getRoutingHeaderId, processIds)
                    .orderByAsc(RoutingDetail::getTaskSeq)
                    .list();

            if (operations.isEmpty()) {
                return R.failed("未找到相关工序信息");
            }

            // 提取工序ID用于后续查询
            Set<Integer> operationIds = operations.stream()
                    .map(RoutingDetail::getId)
                    .collect(Collectors.toSet());

            // 获取相关工序设备关系
            List<RoutingDetailEquip> operationEquipments = operationEquipService.lambdaQuery()
                    .in(RoutingDetailEquip::getRoutingDetailId, operationIds)
                    .list();

            if (operationEquipments.isEmpty()) {
                return R.failed("未找到工序设备关系信息");
            }

            // 提取设备ID用于后续查询
            Set<Integer> equipmentIds = operationEquipments.stream()
                    .map(RoutingDetailEquip::getEquipId)
                    .collect(Collectors.toSet());

            // 获取相关设备
            List<Equipinfo> equipments = equipmentService.lambdaQuery()
                    .in(Equipinfo::getId, equipmentIds)
                    .list();

            // 添加空值检查
            if (orders == null || processes == null || operations == null || operationEquipments == null || equipments == null) {
                return R.failed("获取调度数据失败，存在空数据");
            }

            List<ScheduledTask> result = schedulerService.scheduleOrders(
                    orders, processes, operations, operationEquipments, equipments);

            // 转换设备信息为简要信息，并关联相关任务
            List<SimpleEquipinfo> simpleEquipinfos = equipments.stream()
                    .map(equip -> {
                        // 查找与该设备关联的任务
                        List<ScheduledTask> equipTasks = result.stream()
                                .filter(task -> task.getEquipId() != null && task.getEquipId().equals(equip.getId()))
                                .collect(Collectors.toList());
                        
                        return new SimpleEquipinfo()
                                .setId(equip.getId())
                                .setEquipId(equip.getEquipId())
                                .setEquipName(equip.getEquipName())
                                .setTasks(equipTasks);
                    })
                    .collect(Collectors.toList());

            // 设置甘特图VO的最早时间为2025年6月1日，最晚时间为2025年12月1日
            PlanResourceTaskGanttVO ganttVO = new PlanResourceTaskGanttVO()
                    .setTasks(result)
                    .setResources(simpleEquipinfos)
                    .setEarliestTaskStartTime(LocalDateTime.of(2025, 6, 1, 0, 0, 0))
                    .setLastTaskAssignmentTime(LocalDateTime.of(2025, 12, 1, 0, 0, 0));

            return R.ok(ganttVO);
        } catch (Exception e) {
            return R.failed("调度执行失败: " + e.getMessage());
        }
    }
}