/*
 *
 * Copyright (c) 2001-2016 泛微软件.
 * 泛微协同商务系统,版权所有.
 *
 */
package weaver.interfaces.schedule;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.quartz.impl.JobDetailImpl;
import weaver.conn.RecordSet;
import weaver.general.StaticObj;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.integration.util.NodeUtil;

import java.util.ArrayList;

/**
 * Schedule 监听类
 */
public class WeaverJobListener implements JobListener {
	/**
	 * 日志输出
	 */
	private static Logger newlog = LoggerFactory.getLogger(ScheduleManage.class);
	
	/**
	 * 获取监听名称
	 */
    public String getName() {
        return "WeaverJobListener";
    }
    
    /**
     * 任务执行异常
     * @param context
     */
    public void jobExecutionVetoed(JobExecutionContext context) {
        JobDetailImpl jobDetail = (JobDetailImpl) context.getJobDetail();
        String schedulename = jobDetail.getName();
        CronJob job = (CronJob) StaticObj.getServiceByFullname(schedulename, CronJob.class);
		if(null  != job){
			ScheduleManage.modifyJobTime(schedulename, job.getCronExpr());
			newlog.error("Schedule 监听类 ：任务("+schedulename+" "+job.getCronExpr()+")执行异常,进行重载处理。");
		}
    }
    
    /**
	 * 任务执行前
	 * @param context
	 */
    public void jobToBeExecuted(JobExecutionContext context) {
        JobDetailImpl jobDetail = (JobDetailImpl) context.getJobDetail();
        String schedulename = jobDetail.getName();

        String  threadname=Thread.currentThread().getName();
        String  threadid= Util.null2String(Thread.currentThread().getId());


        BaseCronJob job = (BaseCronJob) StaticObj.getServiceByFullname(schedulename, CronJob.class);
        if (job != null) {
            newlog.info("Schedule 监听类 ：任务(" + schedulename + ")开始执行 .线程名称 ："+threadname+" , 线程 ID :"+threadid);
            addRunLog(job);
        }

    }
    
    /**
	 * 任务执行后
	 * @param context
	 * @param excption
	 */
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException excption) {
        JobDetailImpl jobDetail = (JobDetailImpl) context.getJobDetail();
    	String schedulename = jobDetail.getName();
        BaseCronJob job = (BaseCronJob) StaticObj.getServiceByFullname(schedulename, CronJob.class);

        String  threadname=Thread.currentThread().getName();
        String  threadid= Util.null2String(Thread.currentThread().getId());
        if (job != null) {
            if (excption != null) {
                newlog.error("Schedule 监听类 ：任务(" + schedulename + " " + job.getCronExpr() + ")执行异常,进行重载处理。");
            } else {
                updateRunLog(job);
                newlog.info("Schedule 监听类 ：任务(" + schedulename + ")结束执行 .线程名称 ："+threadname+" , 线程 ID :"+threadid);
            }
        }
    }

    private void addRunLog(BaseCronJob cronJob) {
        String Scheduleid = cronJob.getJobName().replace("schedule.","");
        String CronExpress = cronJob.getCronExpr();
        String startDate = TimeUtil.getCurrentDateString();
        String StartTime = TimeUtil.getOnlyCurrentTimeString();
        String CreateDate = startDate;
        String CreateTime = StartTime;
        String serverIp = "";
        String  threadid= Util.null2String(Thread.currentThread().getId());
        ArrayList<String> realIp = NodeUtil.getRealIp();
        if (realIp != null && realIp.size() > 0) {
            serverIp = realIp.get(realIp.size()-1);
        }
        String sql = "INSERT INTO ScheduleRunLog\n" +
                "        ( Scheduleid ,\n" +
                "          CronExpress ,\n" +
                "          ServerIp ,\n" +
                "          StartDate ,\n" +
                "          StartTime ,\n" +
                "          CreateDate ,\n" +
                "          CreateTime,\n" +
                "          threadid\n" +
                "        )\n" +
                "VALUES  ( ? , \n" +
                "          ? , \n" +
                "          ? , \n" +
                "          ? , \n" +
                "          ? , \n" +
                "          ? , \n" +
                "          ? , \n" +
                "          ?  \n" +
                "        )";
        RecordSet rs = new RecordSet();
        rs.executeUpdate(sql, Scheduleid, CronExpress, serverIp, startDate, StartTime, CreateDate, CreateTime,threadid);
    }

    private void updateRunLog(BaseCronJob cronJob) {
        String Scheduleid = cronJob.getJobName().replace("schedule.","");
        String EndDate = TimeUtil.getCurrentDateString();
        String EndTime = TimeUtil.getOnlyCurrentTimeString();
        String  threadid= Util.null2String(Thread.currentThread().getId());
        String sql = "UPDATE ScheduleRunLog SET EndDate=?,EndTime=? WHERE threadid=?  AND EndDate IS NULL AND EndTime IS NULL ";
        RecordSet rs = new RecordSet();
        rs.executeUpdate(sql, EndDate, EndTime, threadid);
    }

}
