package com.jiayue.ipfcst.common.data.job;

import com.jiayue.ipfcst.common.data.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 任务继承类
 *
 * @author zzy
 * @version 1.0
 * @since 2018/10/25 16:04
 */
@Slf4j
public abstract class BaseJob implements Job {

	BaseService baseService;

	@Autowired
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}

	@Override
	public void execute(JobExecutionContext context) {

		String method = this.getClass().getName() + ".execute(JobDataMap jobDataMap)";// 执行方法
		log.info("定时任务:" + method + ",执行开始");
		String parameter = "";// 参数
		String errorInfo = "";
		boolean process;// 执行结果
		try {
			// 设置系统用户为job
			Authentication auth = new UsernamePasswordAuthenticationToken("quartzJob", null);
			SecurityContextHolder.getContext().setAuthentication(auth);
			JobDataMap jobDataMap = context.getTrigger().getJobDataMap();
			parameter = JSONArray.fromObject(jobDataMap).toString();
			process = this.execute(jobDataMap);
		} catch (RuntimeException e) {
			errorInfo = "定时任务执行失败" + e.getMessage();
			log.error("定时任务执行失败", e);
			process = false;
		}

		if (log.isDebugEnabled()) {
			log.debug("执行方法：" + method);
			log.debug("参数:" + parameter);
			log.debug("执行结果：" + process);
		}
		if (!process) {// 如果执行失败，进行告警
			// 进行告警
			String name = "定时任务执行失败";
			String describe = "执行类：" + method + "/r/n参数：" + parameter;
			String solution = "请检查定时任务";
			//            this.baseService.saveSysAlarm(AlarmTypeEnum., name, describe,
			//                SysAlarmPritorityEnum.AlarmPritorityMedium.name(), errorInfo, solution);
		}
		log.info("定时任务:" + method + ",执行完成");
	}

	/**
	 * 任务执行方法
	 *
	 * @param jobDataMap 任务参数
	 * @return 任务执行结果是否成功
	 */
	public abstract boolean execute(JobDataMap jobDataMap);
}
