package com.yihu.wlyy.job;

import com.yihu.wlyy.entity.job.QuartzJobConfig;
import com.yihu.wlyy.entity.statistics.WlyyQuota;
import com.yihu.wlyy.repository.job.JobConfigDao;
import com.yihu.wlyy.repository.statistics.QuotaDao;
import com.yihu.wlyy.web.quota.WlyyJobConfigVO;
import com.yihu.wlyy.web.quota.WlyyQuotaVO;
import org.quartz.Scheduler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/16.
 * 现在用的数据库保存job不需要用这个类
 */
//@Component
public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    private QuotaDao quotaDao;
    @Autowired
    private JobConfigDao jobConfigDao;
    private Scheduler scheduler = null;
    @Autowired
    private QuartzHelper quartzHelper;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            scheduler = schedulerFactoryBean.getScheduler();
            //查询所有需要开始运行的任务的指标
            List<QuartzJobConfig> jobConfigList=jobConfigDao.findByStatus("1");
            for(QuartzJobConfig quartzJobConfig :jobConfigList){
                WlyyQuota wlyyQuota=quotaDao.findOne(quartzJobConfig.getQuotaId());

                WlyyQuotaVO wlyyQuotaVO= new WlyyQuotaVO();
                WlyyJobConfigVO wlyyJobConfigVO=new WlyyJobConfigVO();
                BeanUtils.copyProperties(wlyyQuota,wlyyQuotaVO);
                BeanUtils.copyProperties(quartzJobConfig,wlyyJobConfigVO);

                Map<String,Object> params=new HashMap<String,Object>();
                params.put("quota",wlyyQuotaVO);
                params.put("jobConfig",wlyyJobConfigVO);
                quartzHelper.addJob(Class.forName(quartzJobConfig.getJobClass()), quartzJobConfig.getQuartzCron(), quartzJobConfig.getId(),params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
