package cn.com.capcloud.core.quartz.config;

import cn.com.capcloud.ccui.core.common.quartz.SchedulerManager;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

/**
 * @Author LiaoJiaHui
 * @Create 2025/3/21
 */
public abstract class DataSourceJob implements Job {

    // 抽象方法，要求子类必须实现
    @Override
    public abstract void execute(JobExecutionContext context) throws JobExecutionException;

    public void startAll(JdbcTemplate jdbcTemplate, Map<String, Object> dsMap) throws SchedulerException, ClassNotFoundException {
        SchedulerManager schedulerManager = new SchedulerManager();
        String groupName = String.valueOf(dsMap.get("ds_code"));
        String tableName = String.valueOf(dsMap.get("ds_table_name"));

        List<Map<String, Object>> dataList = jdbcTemplate.queryForList("select * from "+tableName+" where status=0 and cron_expression!='' ");

        for (int i = 0; i < dataList.size(); i++) {
            Map<String,Object> dataMap=dataList.get(i);
            String jobName = groupName + "_" + dataMap.get("id");
            // 创建任务
            schedulerManager.createScheduledJob(jobName, groupName, String.valueOf(dataMap.get("cron_expression")), this.getClass(), dataMap);
            schedulerManager.startScheduler();
        }
    }

    public void stopAll(JdbcTemplate jdbcTemplate, Map<String, Object> dsMap) throws SchedulerException, ClassNotFoundException {
        SchedulerManager schedulerManager = new SchedulerManager();
        String groupName = String.valueOf(dsMap.get("ds_code"));
        schedulerManager.stopScheduledJobByGroup(groupName);
    }

    public void start(Map<String, Object> dsMap, Map<String, Object> dataMap) throws SchedulerException, ClassNotFoundException {
        SchedulerManager schedulerManager = new SchedulerManager();
        String groupName = String.valueOf(dsMap.get("ds_code"));
        String jobName = groupName + "_" + dataMap.get("id");
        String cronExpression=String.valueOf(dataMap.get("cron_expression"));
        if(!cronExpression.equals("null")&&cronExpression.length()>0){
            // 创建任务
            schedulerManager.createScheduledJob(jobName, groupName, cronExpression, this.getClass(), dataMap);
            schedulerManager.startScheduler();
        }else{
            // 未设置cron则停止任务
            schedulerManager.stopScheduledJob(jobName, groupName);
        }
    }

    public void stop(Map<String, Object> dsMap, Map<String, Object> dataMap) throws SchedulerException, ClassNotFoundException {
        SchedulerManager schedulerManager = new SchedulerManager();
        String groupName = String.valueOf(dsMap.get("ds_code"));
        String jobName = groupName + "_" + dataMap.get("id");
        //停止任务
        schedulerManager.stopScheduledJob(jobName, groupName);
    }
}
