package com.nokia.dingtalk_auto.controller;

import org.springframework.scheduling.support.CronExpression;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.nokia.common.http.R;
import com.nokia.dingtalk_auto.service.TslCronTaskService;
import com.nokia.dingtalk_auto.service.TslTaskService;

/**
 * 投诉率相关数据源入库
 * 
 * 1. 支持定时任务状态查询、修改定时任务表达式、启动或停止定时任务
 * 支持手动重新生成某天的报告或入库
 */
@RequestMapping("/tsl/task")
@RestController
public class TslTaskConroller {

    private final TslTaskService taskService;
    private final TslCronTaskService cronTaskService;

    public TslTaskConroller(TslTaskService taskService, TslCronTaskService cronTaskService) {
        this.taskService = taskService;
        this.cronTaskService = cronTaskService;
    }

    @PostMapping("/send")
    public R send(@RequestBody String day) {
        try {
            taskService.runTask(day);
            return R.ok().message("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message(e.getMessage());
        }
    }

    /**
     * 启动定时任务
     * 
     * @return
     */
    @PostMapping("/cron/start")
    public R startCronTask() {
        cronTaskService.startCronTask();
        return R.ok().message("任务启动成功");
    }

    /**
     * 停止定时任务
     * 
     * @return
     */
    @PostMapping("/cron/stop")
    public R stopCronTask() {
        cronTaskService.stopCronTask();
        return R.ok().message("任务已停止");
    }

    /**
     * 查询定时任务状态
     * 
     * @return
     */
    @PostMapping("/cron/status")
    public R getCronTaskStatus() {
        String cronExpression = cronTaskService.getCronExpression();
        boolean started = cronTaskService.isStarted();
        String status = started ? "启动中" : "已停止";
        return R.ok().message(String.format("任务状态：%s, 定时表达式：%s", status, cronExpression));
    }

    /**
     * 修改定时任务定时表达式
     * 
     * @return
     */
    @PostMapping("/cron/expression")
    public R updateCronTaskExpression(@RequestBody String cronExpression) {
        try {
            CronExpression.parse(cronExpression);
        } catch (IllegalArgumentException e) {
            return R.error().message(String.format("输入的表达式有误, 任务状态不变：%s", e.getMessage()));
        }
        String oldCronExpression = cronTaskService.getCronExpression();
        cronTaskService.updateCronExpression(cronExpression);
        return R.ok().message(String.format("定时表达式更新成功, 新表达式：%s, 原表达式：%s", cronExpression, oldCronExpression));
    }
}
