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.role.Level2Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.util.JsonDateValueProcessor;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
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.11.
 * 签约费用统计 到达量
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中，但是这时有空闲的线程，那么马上又会执行，这样一来就会存在同一job被并行执行
public class AllSignExpenseStatusJob implements Job{
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private Level2Role level2Role;
    @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){
            e.printStackTrace();
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }

    /**
     * 计算指标
     */
    private void computequota()throws Exception {
        try {
            deleteData();
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //从缓存中取数据到已经缴费的数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(date);
            List<SignFamily> signFamilies_1=cacheModel.getSignFamilies();
            //抽取第二种条件的语句
            String sql=" select code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"' and (expenses_status !=1 or expenses_status is null)";
            String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2  and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"'and (expenses_status !=1 or expenses_status is null)  ";
            List<SignFamily> signFamilies_2= dbExtract.extractByPage(SignFamily.class,sql,sqlCount,true);
            //抽取的语句
            sql="select code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.apply_date< '"+date+ Constant.quota_date_last+"'";
            signFamilies_2.addAll(signFamilies_1);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(signFamilies_2, SignDataFilter.level2Expenses,sql,date);
            //统计数据
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> level2Data= level2Role.elt(returnDatas);
            //数据转换
            dbStorage.saveByLevel2(level2Data,date,wlyyQuota,2,4,0);
            //保存日志
            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='" + 14 + "'");
    }

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

}
