package com.sundot.airport.item.controller;

import com.sundot.airport.common.annotation.Log;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.core.page.TableDataInfo;
import com.sundot.airport.common.dto.DutyScheduleGenerateReq;
import com.sundot.airport.common.enums.BusinessType;
import com.sundot.airport.common.utils.poi.ExcelUtil;
import com.sundot.airport.item.domain.SimpleDutySchedule;
import com.sundot.airport.item.service.ISimpleDutyScheduleService;
import com.sundot.airport.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 值班安排Controller
 *
 * @author wangxx
 * @date 2026-01-14
 */
@RestController
@RequestMapping("/item/simpleDutySchedule")
public class SimpleDutyScheduleController extends BaseController {
    @Autowired
    private ISimpleDutyScheduleService simpleDutyScheduleService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询值班安排列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SimpleDutySchedule simpleDutySchedule) {
        startPage();
        List<SimpleDutySchedule> list = simpleDutyScheduleService.selectSimpleDutyScheduleList(simpleDutySchedule);
        return getDataTable(list);
    }

    /**
     * 导出值班安排列表
     */
    @Log(title = "值班安排", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(SimpleDutySchedule simpleDutySchedule) {
        List<SimpleDutySchedule> list = simpleDutyScheduleService.selectSimpleDutyScheduleList(simpleDutySchedule);
        ExcelUtil<SimpleDutySchedule> util = new ExcelUtil<SimpleDutySchedule>(SimpleDutySchedule.class);
        return util.exportExcel(list, "值班安排数据");
    }


    /**
     * 新增值班安排
     */
    @Log(title = "值班安排", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SimpleDutySchedule simpleDutySchedule) {
        return toAjax(simpleDutyScheduleService.insertSimpleDutySchedule(simpleDutySchedule));
    }

    /**
     * 修改值班安排
     */
    @Log(title = "值班安排", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SimpleDutySchedule simpleDutySchedule) {
        return toAjax(simpleDutyScheduleService.updateSimpleDutySchedule(simpleDutySchedule));
    }

    /**
     * 删除值班安排
     */
    @Log(title = "值班安排", businessType = BusinessType.DELETE)
    @DeleteMapping("/{scheduleIds}")
    public AjaxResult remove(@PathVariable Long[] scheduleIds) {
        return toAjax(simpleDutyScheduleService.deleteSimpleDutyScheduleByIds(scheduleIds));
    }


    /**
     * 生成统一排班计划（支持单班、两班倒、多班倒等模式）
     *
     * @param req 排班计划生成请求参数
     */
    @Log(title = "生成统一排班计划", businessType = BusinessType.INSERT)
    @PostMapping("/generateUnifiedSchedule")
    public AjaxResult generateUnifiedSchedule(@RequestBody DutyScheduleGenerateReq req) {
        // 查询循环部门
        String[] deptParts = req.getDeptIds().split(",");
        List<SysDept> departmentList = new ArrayList<>();
        SysDept startDepartment = new SysDept();
        for (String deptId : deptParts) {
            long id = Long.parseLong(deptId);
            //根据部门id 查询部门信息
            SysDept dept = sysDeptService.selectDeptById(id);
            departmentList.add(dept);
            if (id == req.getStartDeptId()) {
                startDepartment = dept;
            }
        }

        // 解析班次安排字符串，格式："9-17,17-9" 或 "9-9"（跨天）
        String[] shiftPairs = req.getShifts().split(",");
        int[][] shiftsArray = new int[shiftPairs.length][2];

        for (int i = 0; i < shiftPairs.length; i++) {
            String[] times = shiftPairs[i].split("-");
            if (times.length != 2) {
                throw new IllegalArgumentException("班次格式错误，应为 HH-HH 格式，如 9-17");
            }
            shiftsArray[i][0] = Integer.parseInt(times[0]); // 开始时间
            shiftsArray[i][1] = Integer.parseInt(times[1]); // 结束时间
        }

        SysDept stationDepartment = sysDeptService.selectDeptById(req.getStationId());

        List<SimpleDutySchedule> scheduleList = simpleDutyScheduleService.generateUnifiedSchedule(
                req.getStartDate(), startDepartment, departmentList, shiftsArray, req.getDaysToGenerate(), stationDepartment);

        // 批量插入或更新排班安排（如果已存在则覆盖）
        int successCount = 0;
        if (!scheduleList.isEmpty()) {
            successCount = simpleDutyScheduleService.batchInsertOrUpdateSimpleDutySchedule(scheduleList);
        }

        return AjaxResult.success("成功生成 " + successCount + " 条排班安排");
    }
}