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

import org.quartz.CronExpression;
import org.quartz.Scheduler;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.triggers.CronTriggerImpl;
import weaver.conn.RecordSet;
import weaver.formmode.task.TaskService;
import weaver.general.InitServer;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * User: xiaofeng.zhang
 * Date: 2007-10-12
 * Time: 10:05:45
 * To change this template use File | Settings | File Templates.
 */
public class ScheduleManage {

    /**
     * 日志输出
     */
    private static Logger newlog = LoggerFactory.getLogger(ScheduleManage.class);

    /**
     * 任务分组名称
     */
    public static String JOB_GROUP_NAME = "cron";
    /**
     * 触发器分组名称
     */
    public static String TRIGGER_GROUP_NAME = "tgroup1";


    /**
     * 计划任务初始化
     */
    public static void start() {
        try {
            QuartzAPI api = new QuartzAPIImpl();
            //1,清任务
            Scheduler scheduler = api.getScheduler();
            boolean started = scheduler.isStarted();
            newlog.info("LC started:"+started);
            if(true){
                scheduler.clear();
                //2,添加任务
                List l = StaticObj.getServiceIds(CronJob.class);
                RecordSet rs = new RecordSet();
                TaskCenterUtil taskCenterUtil=new TaskCenterUtil();
                String MainControlIP=IpSelectUtil.getMainControlIP();
                String localIp=IpSelectUtil.getLocalIp(); //获取当前节点Ip
                for (int i = 0; i < l.size(); i++) {
                    newlog.error("Schedule Cron Job 缓存（" + l.get(i) + "）");
                    String schedulename = "";
                    try {
                        Object jobObj = StaticObj.getServiceByFullname((String) l.get(i), CronJob.class);
                        if (jobObj == null) {
                            newlog.error("Schedule Cron Job 缓存不存在（" + l.get(i) + "）");
                            continue;
                        }
                        newlog.info("JobObj："+ jobObj.getClass().getName());
                        BaseCronJob job = (BaseCronJob) jobObj;
                        //判断是否集群
                        if(!MainControlIP.equals("")){  //集群部署走下面逻辑
                            String runIp=job.getRunIp();
                            if(runIp.equals("")){
                                if(!localIp.equals(MainControlIP)){
                                    continue;
                                }
                            }else{
                                boolean islocalponit=taskCenterUtil.IsLocalPoint(runIp);
                                if(!islocalponit){  //非当前节点  不进行调用
                                    continue;
                                }
                            }
                        }

                        job.setGroupName(JOB_GROUP_NAME);
                        job.setJobName((String) l.get(i));
                        job.setTriggerGroupName(TRIGGER_GROUP_NAME);
                        String jobStatus = Util.null2String( job.getJobStatus());
                        if (!"1".equals(jobStatus)) {
                            api.startJob(job);
                            newlog.info("（"+l.get(i)+"）启动成功！");
                            rs.executeUpdate("update schedulesetting set runstatus = ? where pointid = ? ","0",job.getJobName().split("\\.")[1]);
                        }
                    } catch (Throwable e1) {
                        newlog.error("Schedule Cron Job 执行异常(" + schedulename + "):", e1);
                    }
                }
                if( "".equals(MainControlIP) || !"".equals(MainControlIP) && InitServer.getRealIp().contains(MainControlIP)){//当前节点是主节点，初始化建模的计划任务
                    newlog.info("初始化建模计划任务...");
                    TaskService service = new TaskService();
                    service.initAllRemind();
                }
                scheduler.start();
                newlog.info("计划任务启动成功！");
                started = scheduler.isStarted();
                newlog.info("LC started:"+started);
            }else {
                newlog.info("LC 计划任务实例已启动，不需要再次启动！！！");
            }
            /*
            if(!isInit()){

            }else {
                newlog.info("LC 计划任务线程已初始化过，不需要再进行初始化！！！");
            }*/
        } catch (Throwable e) {
            e.printStackTrace();
            newlog.error("Schedule start Exception:", e);
        }
    }


    /**
     * 新增任务
     * @param jobName
     * @param time
     */
    public static void addJob(String jobName, String time) {
        try {
            QuartzAPI api = new QuartzAPIImpl();

            JobDetailImpl jobDetail=new JobDetailImpl(jobName,JOB_GROUP_NAME,WeaverJob.class);
            CronTriggerImpl cronTrigger = new CronTriggerImpl(jobName, TRIGGER_GROUP_NAME);
            CronExpression cexp = new CronExpression(time);
            cronTrigger.setCronExpression(cexp);
            api.getScheduler().scheduleJob(jobDetail, cronTrigger);
            newlog.error("addJob 新增任务:"+jobName+"  "+time);
        } catch (Exception e) {
            newlog.error("addJob Exception:", e);
            e.printStackTrace();
        }

    }
    /**
     * 修改已有任务触发时间
     * @param jobName
     * @param time
     */
    public static void modifyJobTime(String jobName, String time) {

    }
    /**
     * 移除一个任务
     * @param jobName
     */
    public static void removeJob(String jobName) {
        try {
            QuartzAPI api = new QuartzAPIImpl();
            api.getScheduler().pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器
            api.getScheduler().unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器
            api.getScheduler().deleteJob(jobName, JOB_GROUP_NAME);// 删除任务
            newlog.error("removeJob 移除一个任务:"+jobName);
        } catch (Exception e) {
            newlog.error("removeJob Exception:", e);
        }
    }

    public static boolean isInit(){
        boolean res=false;
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;
        // 遍历线程组树，获取根线程组
        while ( group != null ) {
            topGroup = group;
            group = group.getParent();
        }
        // 激活的线程数加倍
        int estimatedSize = topGroup.activeCount() * 2;
        Thread[] slackList = new Thread[estimatedSize];
        //获取根线程组的所有线程
        int actualSize = topGroup.enumerate(slackList);
        Thread[] list = new Thread[actualSize];
        newlog.info("LC list:"+list.length);
        System.arraycopy(slackList, 0, list, 0, actualSize);
        for (int i = 0; i < list.length; i++){
            String thName = list[i].getName();
//            newlog.info("LC thName:"+thName);
            if(thName.contains("DefaultQuartzScheduler")){
                res = true;//初始化过了
                break;
            }
        }
        newlog.info("LC res:"+res);
        return res;
    }
}