package com.ssj.quartz.web;

import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.quartz.domian.JobEntity;
import com.ssj.quartz.service.JobEntityService;
import com.ssj.service.kmt.arrange.service.KmtArrangeTemplateService;
import com.ssj.util.WxTemplateCacheUtils;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 */
@RestController
@RequestMapping("/job")
public class JobController{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    private JobEntityService jobService;


    //初始化启动所有的Job
    @PostConstruct
    public void initialize() {
        try {
            reStartAllJobs();
            logger.info("INIT SUCCESS");
        } catch (Exception e) {
            logger.info("INIT EXCEPTION : " + e.getMessage());
            e.printStackTrace();
        }
    }


    //刷新全量模板到redis
    @RequestMapping("/refresh/wxall")
    public String refreshWxAll() {
        String result;
        try {
        	WxTemplateCacheUtils.init();
            result = "SUCCESS";
        } catch (Exception e) {
            result = "EXCEPTION : " + e.getMessage();
        }
        return "refresh all jobs : " + result;
    }
    
  
    /**
     *  手动更新下一个月的日历表的最少人数，指定活泼数，生成饱和量
     *  activeNum ： 活泼数
     */
    @RequestMapping("/refresh/active/{activeNum}")
    public String refreshActive(@PathVariable Integer activeNum) {
        String result;
        try {
    	    KmtArrangeTemplateService kmtArrangeTemplateService = SystemResourceLocator.getBean(KmtArrangeTemplateService.class);
    	    try {
    	        logger.info("手动更新下一个月的日历表的最少人数，指定活泼数，生成饱和量.开始");
    	        kmtArrangeTemplateService.updateKmtArrangeDetailByNextMonth(activeNum);
    	    } catch (Exception e) {
    	        logger.error("手动更新下一个月的日历表的最少人数，指定活泼数，生成饱和量.-->"+e.getMessage());
    	    }finally{
    	        logger.info("手动更新下一个月的日历表的最少人数，指定活泼数，生成饱和量.结束");
    	    }
            result = "SUCCESS";
        } catch (Exception e) {
            result = "EXCEPTION : " + e.getMessage();
        }
        return "refresh all jobs : " + result;
    }
    
    
    
  
    

    //根据ID重启某个Job
    @RequestMapping("/refresh/{id}")
    public String refresh(@PathVariable Integer id) {
        String result;
        JobEntity entity = jobService.getJobEntityById(id);
        if (entity == null) return "error: id is not exist ";
        TriggerKey triggerKey = new TriggerKey(entity.getName(), entity.getGroup());
        JobKey jobKey = jobService.getJobKey(entity);
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        try {
            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(jobKey);
            JobDataMap map = jobService.getJobDataMap(entity);
            JobDetail jobDetail = jobService.geJobDetail(jobKey, entity.getDescription(), map);
            if (entity.getStatus().equals("OPEN")) {
                scheduler.scheduleJob(jobDetail, jobService.getTrigger(entity));
                result = "Refresh Job : " + entity.getName() + "\t jarPath: " + entity.getJarPath() + " success !";
            } else {
                result = "Refresh Job : " + entity.getName() + "\t jarPath: " + entity.getJarPath() + " failed ! , " +
                        "Because the Job status is " + entity.getStatus();
            }
        } catch (Exception e) {
            result = "Error while Refresh " + e.getMessage();
        }
        return result;
    }


    //重启数据库中所有的Job
    @RequestMapping("/refresh/all")
    public String refreshAll() {
        String result;
        try {
            reStartAllJobs();
            result = "SUCCESS";
        } catch (Exception e) {
            result = "EXCEPTION : " + e.getMessage();
        }
        return "refresh all jobs : " + result;
    }

    /**
     * 重新启动所有的job
     */
    private void reStartAllJobs() throws SchedulerException {

            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            Set<JobKey> set = scheduler.getJobKeys(GroupMatcher.anyGroup());
            for (JobKey jobKey : set) {
                scheduler.deleteJob(jobKey);
            }
            for (JobEntity job : jobService.loadJobs()) {
                try {
                    logger.info("Job register name : {} , group : {} , cron : {}", job.getName(), job.getGroup(), job.getCron());
                    JobDataMap map = jobService.getJobDataMap(job);
                    JobKey jobKey = jobService.getJobKey(job);
                    JobDetail jobDetail = jobService.geJobDetail(jobKey, job.getDescription(), map);
                    if (job.getStatus().equals("OPEN")) {
                        scheduler.scheduleJob(jobDetail, jobService.getTrigger(job));
                    }else{
                        logger.info("Job jump name : {} , Because {} status is {}", job.getName(), job.getName(), job.getStatus());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

    }
    
    
    @RequestMapping("/list")
	 public ResponseEntity list(
	    		@RequestParam(required = false, defaultValue = "10") int pageSize,
				@RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
		 ResponseEntity responseEntity = new ResponseEntity();
	    Map<String, Object> data = new HashMap<String, Object>();
		responseEntity.success(data, "获取成功");
        return responseEntity;
	 }


}
