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

import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.job.business.QuartzHelper;
import com.yihu.wlyy.statistics.job.business.SignAgeGroupDiseaseJob;
import com.yihu.wlyy.statistics.job.business.SignJob;
import com.yihu.wlyy.statistics.model.job.QuartzJobConfig;
import com.yihu.wlyy.statistics.model.job.WlyyQuota;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import java.util.*;

/**
 * Created by Administrator on 2016.10.11.
 * 判断签约的数据对不对 不对的话 添加任务重新生成签约数据
 */
@Component
@Scope("prototype")
public class CheckSignJob implements Job{
    public static String jobKey="CHECK_SIGN_JOB";
    public static String cron="0 0 12 * * ?";

    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private QuartzHelper quartzHelper;
    @Autowired
    private QuartzJobConfigDao wlyyJobConfigDao;
    @Autowired
    private QuotaDao quotaDao;

    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try{
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //得到需要检验的统计
            List<WlyyQuotaResult> wlyyQuotaResults=getNeedCheckData();
            //检验统计数据和签约数据是否一致  key:yes 是需要 no:是不需要
            Map<String,List<WlyyQuotaResult>> wlyyQuotaResultsMap=checkWlyyQuotaResult(wlyyQuotaResults);
            //更新不需要下一次统计的任务
            upDataNoNeedCheckQuato(wlyyQuotaResultsMap.get("no"));
            //添加需要重新统计的指标
            addNeedCheckQuato(wlyyQuotaResultsMap.get("yes"));
        }catch (Exception e){
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }

    private void addNeedCheckQuato(List<WlyyQuotaResult> yes)throws Exception {
        if(yes.size()>0){
            for(WlyyQuotaResult wlyyQuotaResult:yes){
                QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(wlyyQuotaResult.getId());
                if (quartzJobConfig == null) {
                    throw new Exception("id不存在");
                }
                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);

                String daybefore=getNextDate(wlyyQuotaResult.getQuotaDate());
                String yesterday=wlyyQuotaResult.getQuotaDate();
                //往quartz框架添加任务
                params.put("daybefore", daybefore);
                params.put("yesterday", yesterday);
                String jobKey="checkSignQuartz:"+wlyyQuotaResult.getQuotaDate()+":"+wlyyQuotaResult.getQuatoCode();
                if(!quartzHelper.isExistJob(jobKey)){
                    quartzHelper.startAt(weeHours(new Date(),1),SignJob.class,jobKey,params);
                    //重新生成性别 疾病 扣费 和 年龄的统计
                    startJob("6",yesterday,daybefore);
                    startJob("7",yesterday,daybefore);
                    startJob("8",yesterday,daybefore);
                    startJob("12",yesterday,daybefore);
                }
            }
        }
    }

    private void startJob(String id, String yesterday, String daybefore) throws Exception{
        QuartzJobConfig quartzJobConfig = wlyyJobConfigDao.findById(id);
        if (quartzJobConfig == null) {
            throw new Exception("id不存在");
        }
        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);

        //往quartz框架添加任务
        params.put("daybefore", daybefore);
        params.put("yesterday", yesterday);
        String jobKey="checkSignQuartz:"+yesterday+":"+wlyyQuota.getId();
        if(!quartzHelper.isExistJob(jobKey)){
            quartzHelper.startAt(weeHours(new Date(),1),getClassById(id),jobKey,params);
        }
    }

    private Class getClassById(String id) {
        switch (id){
            case "6":{
                return SignJob.class;
            }
            case "7":{
                return SignJob.class;
            }
            case "8":{
                return SignJob.class;
            }
            case "12":{
                return SignAgeGroupDiseaseJob.class;
            }
        }
        return null;
    }

    /**
     * 更新不需要下一次统计的任务   更新qkdoctorJobName字段为1
     * @param noNeedCheckQuatos
     */
    private void upDataNoNeedCheckQuato(List<WlyyQuotaResult> noNeedCheckQuatos) {
        if(noNeedCheckQuatos.size()>0){
            for(WlyyQuotaResult wlyyQuotaResult:noNeedCheckQuatos){
                wlyyQuotaResult.setQkdoctorJobName("1");
            }
            wlyyQuotaResultDao.save(noNeedCheckQuatos);
        }
    }

    /**
     * 检验统计数据和签约数据是否一致  key:yes 是需要 no:是不需要
     * @param wlyyQuotaResults
     * @return
     */
    private Map<String,List<WlyyQuotaResult>> checkWlyyQuotaResult(List<WlyyQuotaResult> wlyyQuotaResults) {
        Map<String,List<WlyyQuotaResult>> returnMap=new HashMap<String,List<WlyyQuotaResult>>();
        List<WlyyQuotaResult> yes=new ArrayList<WlyyQuotaResult>();//需要重新统计的
        List<WlyyQuotaResult> no=new ArrayList<WlyyQuotaResult>();//不需要重新统计

        for(WlyyQuotaResult wlyyQuotaResult:wlyyQuotaResults){
            String date=  wlyyQuotaResult.getQuotaDate();//格式  2016-10-20
            String nextDate=getNextDate(date);
            List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(date, nextDate);
            if(signFamilys.size()!=Integer.valueOf(wlyyQuotaResult.getResult())){
                //如果数目不相等 说明需要重新统计
                yes.add(wlyyQuotaResult);
            }else{
                //如果数目相等 说明需要不需要重新统计
                no.add(wlyyQuotaResult);
            }
        }

        returnMap.put("yes",yes);
        returnMap.put("no",no);
        return returnMap;
    }

    private String getNextDate(String date) {
        Date dateTime=  DateUtil.strToDateShort(date);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(dateTime);
        calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动
        Date nextDateTime=calendar.getTime();
        return DateUtil.dateToStrShort(nextDateTime);
    }

    /**
     * 得到需要检验的统计
     * @return
     */
    private List<WlyyQuotaResult> getNeedCheckData() {
        List<WlyyQuotaResult> wlyyQuotaResults=wlyyQuotaResultDao.findByLevel1TypeAndQkdoctorJobName("4","1");
        return wlyyQuotaResults;
    }

    /**
     * 获取当前时间所在的凌晨时间
     *  凌晨
     * @param date
     * @flag 0 返回yyyy-MM-dd 00:00:00日期<br>
     *       1 返回yyyy-MM-dd 23:59:59日期
     * @return
     */
    private  Date weeHours(Date date, int flag) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        //时分秒（毫秒数）
        long millisecond = hour*60*60*1000 + minute*60*1000 + second*1000;
        //凌晨00:00:00
        cal.setTimeInMillis(cal.getTimeInMillis()-millisecond);

        if (flag == 0) {
            return cal.getTime();
        } else if (flag == 1) {
            //凌晨23:59:59
            cal.setTimeInMillis(cal.getTimeInMillis()+23*60*60*1000 + 59*60*1000 + 59*1000);
        }
        return cal.getTime();
    }

}
