package link.at17.mid.tushare.task.job;

import java.lang.reflect.InvocationTargetException;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.InterruptableJob;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.UnableToInterruptJobException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import link.at17.mid.tushare.data.models.UpdatePlan;
import link.at17.mid.tushare.data.service.StockCalendarService;
import link.at17.mid.tushare.service.UpdatePlanService;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Validated
@DisallowConcurrentExecution
public class UpdatePlanJob implements Job, InterruptableJob {

    @Autowired
    private UpdatePlanService updatePlanService;
    
    @Autowired
    private StockCalendarService stockCalendarService;
    
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        UpdatePlan plan = (UpdatePlan) context.getMergedJobDataMap().get("updatePlan");

        if (!plan.getEnabled()) {
            log.info("任务 [{}]{} 未启用，忽略任务", plan.getId(), plan.getName());
            return;
        }
        
        if (!plan.getValid()) {
            log.info("任务 [{}]{} 不合法，忽略任务", plan.getId(), plan.getName());
            return;
        }
        
        // 交易日检查
        if (plan.getOpenDayCheck()) {
            // 如果是交易日检查，要确保交易日历数据都是最新的
            stockCalendarService.updateData();
            
            Boolean todayIsOpen = stockCalendarService.todayIsOpen();
            if (!todayIsOpen) {
                log.info("任务 [{}]{} 开启了交易日检查，当日非交易日，忽略任务", plan.getId(), plan.getName());
                return;
            }
        }
        
        try {
            log.info("任务 [{}]{} 开始执行...", plan.getId(), plan.getName());
            updatePlanService.execute(plan);
            log.info("任务 [{}]{} 执行完毕", plan.getId(), plan.getName());
        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException
                | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void interrupt() throws UnableToInterruptJobException {
        // TODO Auto-generated method stub
        
    }

}
