package com.zehong.web.controller.equipment;

import com.zehong.system.task.DeviceCommJob.TestEmptyJob;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Date;
/**
 * @author lenovo
 * @date 2025/9/25
 * @description TODO
 */

@RestController
@RequestMapping("/test/quartz")
public class QuartzTestController {

    private static final Logger log = LoggerFactory.getLogger(QuartzTestController.class);
    @Resource
    private Scheduler scheduler;

    @GetMapping("/runEmptyJob")
    public String runEmptyJob() {
        try {
            // 1. 定义JobKey和TriggerKey（确保唯一，避免冲突）
            String jobId = "TEST_EMPTY_JOB_" + System.currentTimeMillis();
            String triggerId = "TEST_EMPTY_TRIGGER_" + System.currentTimeMillis();
            JobKey jobKey = new JobKey(jobId, "TEST_GROUP");
            TriggerKey triggerKey = new TriggerKey(triggerId, "TEST_GROUP");

            // 2. 创建无依赖的JobDetail（不传递任何参数）
            JobDetail jobDetail = JobBuilder.newJob(TestEmptyJob.class)
                    .withIdentity(jobKey)
                    .storeDurably(false) // 非持久化，执行完可删除
                    .build();

            // 3. 创建Trigger（延迟10秒执行，仅1次）
            Date triggerTime = Date.from(Instant.now().plus(2, java.time.temporal.ChronoUnit.SECONDS));
            SimpleTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(triggerKey)
                    .forJob(jobKey)
                    .startAt(triggerTime)
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                            .withRepeatCount(0)
                            .withMisfireHandlingInstructionFireNow())
                    .build();

            // 4. 提交调度并打印日志
            scheduler.scheduleJob(jobDetail, trigger);
            log.info("最小化测试Job提交成功：jobId={}, triggerId={}, startAt={}",
                    jobId, triggerId, triggerTime);
            return "测试Job提交成功，10秒后执行，查看日志";

        } catch (SchedulerException e) {
            log.error("最小化测试Job提交失败：", e);
            return "测试Job提交失败：" + e.getMessage();
        }
    }

}
