package com.ruoyi.ems.controller;

import com.huashe.common.domain.AjaxResult;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;

import com.ruoyi.ems.domain.InspectionReport;
import com.ruoyi.ems.task.InspectionScheduler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 巡检调度器管理Controller
 *
 * 提供调度器状态查询、手动触发、刷新配置等功能
 * 仅在 EMS 主模块可用
 */
@RestController
@RequestMapping("/inspection/scheduler")
@Api(value = "InspectionSchedulerController", description = "巡检调度器管理")
public class InspectionSchedulerController extends BaseController {

    @Autowired
    private InspectionScheduler inspectionScheduler;

    /**
     * 获取调度器状态
     */
    @RequiresPermissions("ems:inspection:plan:query")
    @GetMapping("/status")
    @ApiOperation("获取调度器状态")
    public AjaxResult getStatus() {
        Map<String, Object> status = inspectionScheduler.getStatus();
        return success(status);
    }

    /**
     * 重新加载所有巡检计划
     */
    @RequiresPermissions("ems:inspection:plan:edit")
    @Log(title = "重载巡检计划", businessType = BusinessType.OTHER)
    @PostMapping("/reload")
    @ApiOperation("重新加载所有巡检计划")
    public AjaxResult reload() {
        try {
            inspectionScheduler.loadEnabledPlans();
            return success("巡检计划重新加载完成，当前注册数量: " + inspectionScheduler.getRegisteredCount());
        } catch (Exception e) {
            return error("重新加载失败: " + e.getMessage());
        }
    }

    /**
     * 刷新指定巡检计划
     */
    @RequiresPermissions("ems:inspection:plan:edit")
    @Log(title = "刷新巡检计划", businessType = BusinessType.OTHER)
    @PostMapping("/refresh/{planCode}")
    @ApiOperation("刷新指定巡检计划")
    public AjaxResult refresh(@PathVariable("planCode") String planCode) {
        try {
            inspectionScheduler.refreshPlan(planCode);
            boolean isRegistered = inspectionScheduler.isRegistered(planCode);
            return success(isRegistered
                ? "计划刷新成功，已重新注册"
                : "计划已注销（可能未配置cron或非自动巡检类型）");
        } catch (Exception e) {
            return error("刷新失败: " + e.getMessage());
        }
    }

    /**
     * 注册指定巡检计划
     */
    @RequiresPermissions("ems:inspection:plan:edit")
    @Log(title = "注册巡检计划", businessType = BusinessType.OTHER)
    @PostMapping("/register/{planCode}")
    @ApiOperation("注册指定巡检计划到调度器")
    public AjaxResult register(@PathVariable("planCode") String planCode) {
        try {
            inspectionScheduler.registerPlan(planCode);
            return success("计划已注册到调度器");
        } catch (Exception e) {
            return error("注册失败: " + e.getMessage());
        }
    }

    /**
     * 注销指定巡检计划
     */
    @RequiresPermissions("ems:inspection:plan:edit")
    @Log(title = "注销巡检计划", businessType = BusinessType.OTHER)
    @PostMapping("/unregister/{planCode}")
    @ApiOperation("注销指定巡检计划的定时任务")
    public AjaxResult unregister(@PathVariable("planCode") String planCode) {
        try {
            inspectionScheduler.unregisterPlan(planCode);
            return success("计划已从调度器注销");
        } catch (Exception e) {
            return error("注销失败: " + e.getMessage());
        }
    }

    /**
     * 手动触发一次巡检（用于测试）
     */
    @RequiresPermissions("ems:inspection:plan:execute")
    @Log(title = "手动触发巡检", businessType = BusinessType.OTHER)
    @PostMapping("/trigger/{planCode}")
    @ApiOperation("手动触发一次巡检执行")
    public AjaxResult trigger(@PathVariable("planCode") String planCode) {
        try {
            // 检查是否正在执行
            if (inspectionScheduler.isExecuting(planCode)) {
                return error("该计划正在执行中，请稍后再试");
            }

            InspectionReport report = inspectionScheduler.triggerInspection(planCode);
            return success(report);
        } catch (Exception e) {
            return error("触发执行失败: " + e.getMessage());
        }
    }

    /**
     * 检查计划是否已注册
     */
    @RequiresPermissions("ems:inspection:plan:query")
    @GetMapping("/registered/{planCode}")
    @ApiOperation("检查计划是否已注册")
    public AjaxResult isRegistered(@PathVariable("planCode") String planCode) {
        boolean registered = inspectionScheduler.isRegistered(planCode);
        return success(registered);
    }

    /**
     * 检查计划是否正在执行
     */
    @RequiresPermissions("ems:inspection:plan:query")
    @GetMapping("/executing/{planCode}")
    @ApiOperation("检查计划是否正在执行")
    public AjaxResult isExecuting(@PathVariable("planCode") String planCode) {
        boolean executing = inspectionScheduler.isExecuting(planCode);
        return success(executing);
    }
}