package com.ruoyi.notification.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.notification.domain.ScheduledTask;
import com.ruoyi.notification.service.IScheduledTaskService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 定时任务Controller
 * 
 * @author ruoyi
 * @date 2025-12-19
 */
@RestController
@RequestMapping("/notification/scheduledTask")
public class ScheduledTaskController extends BaseController
{
    @Autowired
    private IScheduledTaskService scheduledTaskService;

    /**
     * 查询定时任务列表
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScheduledTask scheduledTask)
    {
        startPage();
        List<ScheduledTask> list = scheduledTaskService.selectScheduledTaskList(scheduledTask);
        return getDataTable(list);
    }

    /**
     * 导出定时任务列表
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:export')")
    @Log(title = "定时任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScheduledTask scheduledTask)
    {
        List<ScheduledTask> list = scheduledTaskService.selectScheduledTaskList(scheduledTask);
        ExcelUtil<ScheduledTask> util = new ExcelUtil<ScheduledTask>(ScheduledTask.class);
        util.exportExcel(response, list, "定时任务数据");
    }

    /**
     * 获取定时任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:query')")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") Long taskId)
    {
        return success(scheduledTaskService.selectScheduledTaskByTaskId(taskId));
    }

    /**
     * 新增定时任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:add')")
    @Log(title = "定时任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScheduledTask scheduledTask)
    {
        return toAjax(scheduledTaskService.insertScheduledTask(scheduledTask));
    }

    /**
     * 修改定时任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:edit')")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScheduledTask scheduledTask)
    {
        return toAjax(scheduledTaskService.updateScheduledTask(scheduledTask));
    }

    /**
     * 删除定时任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:remove')")
    @Log(title = "定时任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskIds}")
    public AjaxResult remove(@PathVariable Long[] taskIds)
    {
        return toAjax(scheduledTaskService.deleteScheduledTaskByTaskIds(taskIds));
    }

    /**
     * 启动定时任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:start')")
    @Log(title = "启动定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/{taskId}/start")
    public AjaxResult start(@PathVariable Long taskId)
    {
        boolean result = scheduledTaskService.startTask(taskId);
        return result ? success("启动成功") : error("启动失败");
    }

    /**
     * 停止定时任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:stop')")
    @Log(title = "停止定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/{taskId}/stop")
    public AjaxResult stop(@PathVariable Long taskId)
    {
        boolean result = scheduledTaskService.stopTask(taskId);
        return result ? success("停止成功") : error("停止失败");
    }

    /**
     * 暂停定时任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:pause')")
    @Log(title = "暂停定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/{taskId}/pause")
    public AjaxResult pause(@PathVariable Long taskId)
    {
        boolean result = scheduledTaskService.pauseTask(taskId);
        return result ? success("暂停成功") : error("暂停失败");
    }

    /**
     * 恢复定时任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:resume')")
    @Log(title = "恢复定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/{taskId}/resume")
    public AjaxResult resume(@PathVariable Long taskId)
    {
        boolean result = scheduledTaskService.resumeTask(taskId);
        return result ? success("恢复成功") : error("恢复失败");
    }

    /**
     * 立即执行定时任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:run')")
    @Log(title = "立即执行定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/{taskId}/run")
    public AjaxResult run(@PathVariable Long taskId)
    {
        boolean result = scheduledTaskService.runTaskNow(taskId);
        return result ? success("执行成功") : error("执行失败");
    }

    /**
     * 创建合同到期提醒任务
     */
    @PreAuthorize("@ss.hasPermi('notification:scheduledTask:add')")
    @Log(title = "创建合同到期提醒任务", businessType = BusinessType.INSERT)
    @PostMapping("/contract-expiry-reminder")
    public AjaxResult createContractExpiryReminder(@RequestBody ScheduledTask scheduledTask)
    {
        // 从请求参数中获取合同ID和提醒天数
        String[] params = scheduledTask.getMethodParams().split(",");
        if (params.length < 2) {
            return error("参数格式错误，应为：合同ID,提醒天数");
        }
        
        try {
            Long contractId = Long.parseLong(params[0]);
            int reminderDays = Integer.parseInt(params[1]);
            
            boolean result = scheduledTaskService.createContractExpiryReminderTask(contractId, reminderDays);
            return result ? success("创建成功") : error("创建失败");
        } catch (NumberFormatException e) {
            return error("参数格式错误：" + e.getMessage());
        }
    }
}