package cn.myapps.scheduler;

import cn.myapps.common.data.DataPackage;
import cn.myapps.common.model.application.Application;
import cn.myapps.common.model.task.Task;
import cn.myapps.designtime.application.service.ApplicationDesignTimeService;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.designtime.task.service.TaskDesignTimeService;
import cn.myapps.runtime.common.service.RunTimeServiceManager;
import cn.myapps.runtime.scheduler.ejb.TriggerProcess;
import cn.myapps.runtime.scheduler.ejb.TriggerVO;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.*;

public class SchedulerListenerJob {

    /**
     * 查询任务的时间间隔
     */
    private static final long INTERVAL = 60*1000L;

   // @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        System.err.println("SchedulerListenerJob_Start-->" + new Date());
        //JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        // String application = jobDataMap.getString("applicationId");
        try {
            for (String application : getTaskApplications()) {
                TriggerProcess triggerProcess = RunTimeServiceManager.triggerProcess(application);
                Collection<TriggerVO> list = triggerProcess.getStandbyTrigger(INTERVAL);
                for (Iterator<TriggerVO> iterator = list.iterator(); iterator
                        .hasNext(); ) {
                    TriggerVO trigger = iterator.next();
                    if (SchedulerLock.isLock(trigger)) {
                        System.out.println("isLock = [" + SchedulerLock.isLock(trigger) + "]");
                        continue;
                    }
                    if (TriggerVO.STATE_STOP.equals(trigger.getState())) {
                        continue;
                    }
                    String jobName = trigger.getId();
                    String jobGroupName = trigger.getApplicationId();
                    String triggerName = trigger.getId();
                    ;
                    //String triggerGroupName = "";
                    //不可以为空字符串
                    String triggerGroupName = trigger.getApplicationId();
                    //只执行一次，但是时间不确定，所以设定好执行时间
                    Date startTime = new Date(trigger.getDeadline());
                    Map<String, Object> map = new HashMap();
                    map.put("triggervo", trigger);
                    map.put("application", trigger.getApplicationId());
                    System.out.println("jobName = [" + jobName + "]" + startTime);
                    SchedulerUtil.triggerJobOnce(jobName, jobGroupName, triggerName, triggerGroupName, TriggerExecutor.class, map, startTime);
                    SchedulerLock.lock(trigger);
                }
            }
            System.err.println("SchedulerListenerJob_end-->" + new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<String> getTaskApplications(){
        List<String> applicationids = new ArrayList<>();
        try {
            ApplicationDesignTimeService service = DesignTimeServiceManager.applicationDesignTimeService();
            List<Application> apps = service.list("","");
            Map<String,Application> appMap = new HashMap<>();
            for (Application application:apps){
                if(application.getType()!=2){
                    appMap.put(application.getId(),application);
                }
            }
            TaskDesignTimeService taskDesignTimeService  = DesignTimeServiceManager.taskDesignTimeService();
            DataPackage<Task> data = taskDesignTimeService.queryByNameOrDescript("", "", 1, Integer.MAX_VALUE);
            List<Task> taskList = (List<Task>) data.datas;
            for(Task task:taskList){
                if(!applicationids.contains(task.getApplicationid())){
                    Application application = appMap.get(task.getApplicationid());
                    Boolean isRight = application.testDB();
                    if(isRight){
                        applicationids.add(task.getApplicationid());
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return applicationids;
    }
}
