/**
 * 
 */
package org.springblade.etl.service;

import java.util.Optional;

import org.springblade.etl.dto.InstanceStatusCount;
import org.springblade.etl.entity.SqlJob;
import org.springblade.etl.enums.InstanceRunType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wookvn
 *
 */
@Slf4j
@Component
public class XxlJobSqlTaskHandler {
	
	@Autowired
	private SqlJobService sqlJobService;
	
	@Autowired
	private SqlJobInstanceService sqlJobInstanceService;

	@XxlJob("sqlJobHandler")
	public boolean sqlJobHandler() {
		String param = Optional.<String>ofNullable(XxlJobHelper.getJobParam()).orElse("0");
		Integer jobId = Integer.valueOf(param);
		if(jobId <= 0) {
			return XxlJobHelper.handleFail("参数无效");
		}
		SqlJob sqlJob = sqlJobService.getById(jobId);
		if(sqlJob == null) {
			log.warn("SQL任务:未找到SQL任务|jobId={}", jobId);
			return XxlJobHelper.handleFail("SQL任务不存在");
		}
		if(sqlJob.getTriggerStatus() == 0) { //未开启任务调度
			log.warn("SQL任务:未开启任务调度|jobId={}", jobId);
			return XxlJobHelper.handleFail("未开启任务调度");
		}
		InstanceStatusCount instanceStatusCount = sqlJobInstanceService.statInstanceStatusByJobId(jobId);
		if(instanceStatusCount.getRunningCnt() > 0 || instanceStatusCount.getWaitingCnt() > 0) {
			return XxlJobHelper.handleFail("该任务有实例正在运行或待运行,结束后才能运行调度");
		}
		sqlJobService.jobRun(jobId, InstanceRunType.AUTO);
		return XxlJobHelper.handleSuccess();
	}
}
