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

import com.yihu.wlyy.statistics.dao.*;
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.*;
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;

/**
 * 签约下按年龄分组后再按疾病统计
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中，但是这时有空闲的线程，那么马上又会执行，这样一来就会存在同一job被并行执行
public class SignAgeGroupDiseaseJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private Level2Role level2Role;
    @Autowired
    private Level3Role level3Role;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private SignDataFilter signDataFilter;
    @Autowired
    private CachePool cachePool;

    String yesterday;
    String daybefore;

    @Override
    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");
            daybefore = StringUtils.isEmpty(map.get("daybefore")) ? SignAgeGroupDiseaseJob.getDayString(-2) : map.get("daybefore").toString();
            yesterday = StringUtils.isEmpty(map.get("yesterday")) ? SignAgeGroupDiseaseJob.getDayString(-1) : map.get("yesterday").toString();

            computequotaByPatientAge();
        }catch (Exception e){
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }
    /**
     * 机构维度患者年龄维度计算指标
     */
    @Transactional
    private void computequotaByPatientAge() {
        try{
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+12+"'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());

            //从缓存取数据
            CacheModel cacheModel=cachePool.getSignFamilysWithExpenseStatus1ByDate(yesterday);
            //清洗數據
            FilterModel etlModels= signDataFilter.filter(cacheModel.getSignFamilies(),SignDataFilter.level2Age,SignDataFilter.level3Disease,cacheModel.getSql(),yesterday);
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= level2Role.elt(returnDatas);
            //统计数据 三级维度
            List<Map<String, Map<String, Map<String, List<ETLModel>>>>> returnD=level3Role.elt(patientSexRoleData);
            //保存数据
            dbStorage.saveByLevel3(returnD,yesterday,wlyyQuota,6,4,2,1);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError()?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /*
    得到昨天的日期字符串  yyyy-MM-dd
     */
    public String getYesterday() {
        return yesterday;
    }

    /**
     * 根据年龄得到对应的code
     *
     * @param age
     * @return
     */
    public String getAgeCode(Integer age) {
        if (age < 7) {
            return Constant.level_age_1;
        } else if (age >= 7 && age < 18) {
            return Constant.level_age_2;
        } else if (age >= 18 && age < 30) {
            return Constant.level_age_3;
        } else if (age >= 30 && age < 50) {
            return Constant.level_age_4;
        } else if (age >= 50 && age < 65) {
            return Constant.level_age_5;
        } else {
            return Constant.level_age_6;
        }
    }

    public static String getDayString(Integer size) {
        Date date = new Date();//取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, size);//把日期往后增加一天.整数往后推,负数往前移动
        date = calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(date);
        return dateString;
    }
    public static void main(String[] args) {
        getDayString(0);
    }
}
