package com.yihu.wlyy.statistics.job.business;

import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
import com.yihu.wlyy.statistics.etl.model.CacheModel;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.json.JSONObject;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;

/**
 * Created by Administrator on 2016.10.10.
 * 每天的签约到达量统计
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中，但是这时有空闲的线程，那么马上又会执行，这样一来就会存在同一job被并行执行
public class AllSignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private DBExtract dbExtract;
    @Autowired
    private SignDataFilter signDataFilter;
    @Autowired
    private CachePool cachePool;

    String date; //起始时间

    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");

            date= StringUtils.isEmpty(map.get("yesterday"))?SignJob.getDayString(-1):map.get("yesterday").toString();
            //计算指标
            computequota();
        }catch (Exception e){
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }

    /**
     * 计算指标
     */
    private void computequota() {
        try{
            deleteData();
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(date);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),cacheModel.getSql(),date);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnData= levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnData,date,wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            dbStorage.saveLog(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Transactional
    private void deleteData() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+date+"' and quato_code='"+13+"'");
    }


    public String getYesterday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }

}
