package com.zehong.system.task;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * @author lenovo
 * @date 2025/6/25
 * @description 定时调度任务
 */
@Service
public class DeviceTaskScheduler {

    private static final Logger log = LoggerFactory.getLogger(DeviceTaskScheduler.class);
    @Resource
    private Scheduler scheduler;
    /**
     * 创建设备监控任务
     * @param fStoreyId 设备ID
     */
    public void scheduleDeviceMonitoring(Long fStoreyId,String fPowerOutageIp,Integer fPowerOutagePort) throws SchedulerException {

        // 2. 创建每小时通信任务
        createHourlyCommunicationJob(fStoreyId);

        // 3. 创建71小时后执行任务
        createFinalExecutionJob(fStoreyId,fPowerOutageIp,fPowerOutagePort);
    }

    /**
     * 创建每小时通信任务
     */
    private void createHourlyCommunicationJob(Long fStoreyId) throws SchedulerException {
        // 任务标识 = 设备ID + 任务类型
        String jobId = "COMM_" + fStoreyId;

        String fStoreyIdStr = fStoreyId + "";

        JobDetail job = JobBuilder.newJob(DeviceCommunicationJob.class)
                .withIdentity(jobId, "DEVICE_TASKS")
                .usingJobData("fStoreyId", fStoreyIdStr)
                .storeDurably()
                .build();

        // 测试每两分钟 读一次数据
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobId + "_TRIGGER", "DEVICE_TRIGGERS")
//                .withSchedule(CronScheduleBuilder.cronSchedule("0 0 * * * ?")) 每小时执行一次 (0分0秒执行)
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0/2 * * * ?"))
                .build();

        scheduler.scheduleJob(job, trigger);
    }

    /**
     * 创建71小时后执行任务
     */
    private void createFinalExecutionJob(Long fStoreyId,String fPowerOutageIp,Integer fPowerOutagePort) throws SchedulerException {
        String jobId = "FINAL_" + fStoreyId;
        String fStoreyIdStr = fStoreyId.toString();
        String fPowerOutagePortStr = fPowerOutagePort.toString();
        JobDetail job = JobBuilder.newJob(FinalExecutionJob.class)
                .withIdentity(jobId, "DEVICE_TASKS")
                .usingJobData("fStoreyId", fStoreyIdStr)
                .usingJobData("fPowerOutageIp", fPowerOutageIp)
                .usingJobData("fPowerOutagePort", fPowerOutagePortStr)
                .storeDurably()
                .build();

        // 计算71小时后的时间点
//        Date executeTime = Date.from(Instant.now().plus(71, ChronoUnit.HOURS));
        // 测试 先用 10分钟
        Date executeTime = Date.from(Instant.now().plus(10, ChronoUnit.MINUTES));

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobId + "_TRIGGER", "DEVICE_TRIGGERS")
                .startAt(executeTime)
                .build();

        scheduler.scheduleJob(job, trigger);
    }
}
