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

import org.springframework.jdbc.core.JdbcTemplate;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

public class DataSourceJobRunner {
	private static String cronFieldName="cron_expression";
	public static void init(JdbcTemplate jdbcTemplate) {
		String queryDsSql="select * from tbl_data_source where status=0 and enable_job='Y' and job_class_path !='' ";
		List<Map<String, Object>> dsList = jdbcTemplate.queryForList(queryDsSql);
		for (int i = 0; i < dsList.size(); i++) {
			Map<String,Object> dsMap=dsList.get(i);
			String tableName=String.valueOf(dsMap.get("ds_table_name"));
			String querySql="SHOW FULL COLUMNS FROM `"+tableName+"` WHERE FIELD='"+cronFieldName+"'";
			List<Map<String, Object>> colList=jdbcTemplate.queryForList(querySql);
			if(colList.size()==0){
				System.out.println(dsMap.get("ds_name")+" 数据源启用任务失败，原因是 "+tableName+" 表结构未创建 "+cronFieldName+" 字段");
				continue;
			}
			String jobClassPath=String.valueOf(dsMap.get("job_class_path"));
			executeJobAllByMethodName(jobClassPath,jdbcTemplate,dsMap,"startAll");
		}
	}

	public static void executeJobAllByMethodName(String jobClassPath, JdbcTemplate jdbcTemplate, Map<String, Object> dsMap,String methodName) {
		try {
			// 1. 加载类
			Class<?> jobClass = Class.forName(jobClassPath);

			// 2. 创建类的实例
			Object jobInstance = jobClass.getDeclaredConstructor().newInstance();

			// 3. 获取 `methodName` 方法（带有 JdbcTemplate 和 Map<String, Object> 参数）
			Method initMethod = jobClass.getMethod(methodName, JdbcTemplate.class, Map.class);

			// 4. 调用 `methodName` 方法
			initMethod.invoke(jobInstance, jdbcTemplate, dsMap);

		} catch (ClassNotFoundException e) {
			System.err.println("类路径错误，未找到类: " + jobClassPath);
		} catch (NoSuchMethodException e) {
			System.err.println("找不到 "+methodName+" 方法，请确保该方法存在并且参数正确。");
		} catch (Exception e) {
			System.err.println("调用 "+methodName+" 方法时发生错误: " + e.getMessage());
		}
	}

}
