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

import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.ConsultDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.FollowUpDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.HealthGuideDataFilter;
import com.yihu.wlyy.statistics.etl.dataFilter.SignDataFilter;
import com.yihu.wlyy.statistics.etl.extract.DBExtract;
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.RedisStorage;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.label.SignPatientLabelInfo;
import com.yihu.wlyy.statistics.model.patient.Patient;
import com.yihu.wlyy.statistics.model.patient.PatientHealthGuidance;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.util.SpringUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;


import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 实时统计今天的数据
 */
@Component
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中，但是这时有空闲的线程，那么马上又会执行，这样一来就会存在同一job被并行执行
public class CurrentDayAllQuotaJob implements Job {
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private ConsultDataFilter consultDataFilter;
    @Autowired
    private HealthGuideDataFilter healthGuideDataFilter;
    @Autowired
    private FollowUpDataFilter followUpDataFilter;

    private org.apache.tomcat.jdbc.pool.DataSource fvdataSource = new org.apache.tomcat.jdbc.pool.DataSource();//随访数据源

    private JdbcTemplate fv_jdbcTemplate = new JdbcTemplate();

    List<Town> towns = null;//厦门市全部的区
    List<Hospital> hospitals = null;//系统全部的机构
    List<AdminTeam> adminTeams=null;//系统全部的团队
    Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
    Map<String, Town> townsMap = new HashMap<String, Town>();
    Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();

    private String now = getDayString(-1)+ Constant.quota_date_last;

    private String tomorrow = getDayString(1);


    private StringBuffer allContent=new StringBuffer();//日志内容

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${fv.jdbc.driver}")
    String fv_jdbc_driver;
    @Value("${fv.jdbc.url}")
    String fv_jdbc_url;
    @Value("${fv.jdbc.username}")
    String fv_jdbc_username;
    @Value("${fv.jdbc.password}")
    String fv_jdbc_password;
    @Value("${redis.quota.current.expire}")
    String currentExpire="2";


    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            fvdataSource.setDriverClassName(fv_jdbc_driver);
            fvdataSource.setUrl(fv_jdbc_url);
            fvdataSource.setUsername(fv_jdbc_username);
            fvdataSource.setPassword(fv_jdbc_password);

            fv_jdbcTemplate.setDataSource(fvdataSource);//初始化随访的数据源
            towns = townDao.findByCityCode(Constant.city); //查找出厦门市全部的区
            hospitals = hospitalDao.findHospitalzxFWZ(); //查找出系统全部的机构
            adminTeams=doctorAdminTeamDao.findAllTeam();//查找出系统全部的全科医生
            for (Hospital hospital : hospitals) {
                hospitalsMap.put(hospital.getCode(), hospital);
            }
            for (Town town : towns) {
                townsMap.put(town.getCode(), town);
            }
            for (AdminTeam adminTeam : adminTeams) {
                adminTeamMap.put(adminTeam.getId()+"", adminTeam);
            }
            //清空缓存
            CachePool.cleanAllCache();
            //计算指标
            computequota();
        }catch (Exception e){
            //延迟上一次key的生命周期
            if(CachePool.getKeys()!=null&&CachePool.getKeys().size()>0){
                for (String key :CachePool.getKeys()){
                    redisTemplate.expire(key, Integer.valueOf(currentExpire), TimeUnit.HOURS);//2小时过期
                }
            }
            //如果出錯立即重新執行
            JobExecutionException e2 =new JobExecutionException(e);
            e2.setRefireImmediately(true);
            e.printStackTrace();
        }
    }

    //统计
    private void computequota() throws Exception {

        RedisStorage.timeKey=new Date().getTime()+"";

        QuartzJobLog quartzJobLog =new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        allContent=new StringBuffer();
        //找出今天的签约信息 yesterday,now
        String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status,patient from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
        String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and status in (1,2) and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";

        //抽取數據
        List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
        computequota_1(sql,signFamilies,null); //统计今天的签约
        computequota_2(); //统计今天的解约
        computequota_3(); //统计今天的健康咨询量
        computequota_4(); //统计今天的随访量
        computequota_5(); //统计今天的健康指导
        computequota_6(sql,signFamilies,null); //统计今天的签约患者性别
        computequota_7(sql,signFamilies,null);//统计今天的签约患者分组
        computequota_8(sql,signFamilies,null);//统计今天的签约患者年龄
        computequota_9();//统计今天的待签约
        computequota_10();//统计今天的改签
        computequota_12(sql,signFamilies,null);//统计今天的签约下按年龄分组后再
        computequota_13(sql,signFamilies,null);//统计今天的签约量
        computequota_16_1(sql,signFamilies,null);//统计今天的签约数的扣费钱 1
        computequota_15(sql,signFamilies,null);//统计今天的健康分布统计
        //computequota_16_0(sql,signFamilies,null);//统计今天的签约数的未扣费 0
        computequota_17(sql,signFamilies,null);//统计今天的年龄疾病
        computequota_20();//统计今天的已经签约患者绑定设备
        computequota_21();//统计今天的已经签约微信关注人数

        quartzJobLog.setJobContent(allContent.toString());
        quartzJobLog.setJobName("实时统计");
        quartzJobLog.setJobId("11");
        quartzJobLog.setJobType("1");
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLogDao.save(quartzJobLog);

        initCurrentExpire();//初始化生命周期

        for (String key :RedisStorage.keys){
            redisTemplate.expire(key, Integer.valueOf(currentExpire), TimeUnit.HOURS);//2小时过期
        }
        CachePool.addKeys(RedisStorage.keys);//缓存key
        RedisStorage.keys.clear();//清空Key

        //更新统计时间
        redisTemplate.opsForValue().set("quota:date",DateUtil.dateToStrLong(new Date()));
        //更新时间key
        redisTemplate.opsForValue().set("quota:timeKey",RedisStorage.timeKey);
    }

    private void computequota_21() {
        try{
            //找出今天的签约信息 yesterday,now
            String sql=" SELECT " +
                    "  sf. CODE, " +
                    "  sf.idcard, " +
                    "  sf.hospital, " +
                    "  sf.admin_team_code " +
                    " FROM " +
                    "  wlyy_patient p, " +
                    "  wlyy_sign_family sf " +
                    " WHERE " +
                    "   p.idcard = sf.idcard " +
                    " AND sf.expenses_status = 1 " +
                    " AND sf.type = 2 " +
                    " AND sf. STATUS IN (1, 2) " +
                    " AND p.openid is not null  " +
                    " AND p.openid_time <'" +tomorrow+"' ";
            //抽取數據
            List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,"now");
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,"21");
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------1----------");
    }

    private void computequota_20() {
        try{
            String sql=" SELECT " +
                    "  sf. CODE, " +
                    "  sf.idcard, " +
                    "  sf.hospital, " +
                    "  sf.admin_team_code " +
                    " FROM " +
                    "  wlyy_patient_device pd, " +
                    "  wlyy_sign_family sf " +
                    " WHERE " +
                    "  pd.user_idcard = sf.idcard " +
                    " AND sf.expenses_status = 1 " +
                    " AND sf.type = 2 " +
                    " AND sf. STATUS IN (1, 2) " +
                    " AND pd.czrq <' "+tomorrow+"' ";
            //抽取數據
            List<SignFamily> signFamilies=  SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,"now");
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
            SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,"20");
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------1----------");
    }

    private void initCurrentExpire() {
        try{
            if(StringUtils.isEmpty(currentExpire)){
                currentExpire="2";//默认是2小时
            }
            if(!org.apache.commons.lang.StringUtils.isNumeric(currentExpire)){
                currentExpire="2";//默认是2小时
            }else{
                Integer cout =Integer.valueOf(currentExpire);
                if(cout<=0){
                    currentExpire="2";//默认是2小时
                }
            }
        }catch (Exception e){
            currentExpire="2";//默认是2小时
        }
    }

    private void computequota_17(String sql, List<SignFamily> signFamilies, Object o) {
        String quotaId="17";
        try{
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2AgeDisease,sql,null);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存数据 1 表示：从1开始循环 6表示：循环6次 3表示 2级维度是 3
            SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,3,7,1);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------17----------");
    }

    private void computequota_16_1(String sql,List<SignFamily> signFamilies_1,List<SignFamily> deleteSignFamilies) {
        String quotaId="16";
        try{
            sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and (expenses_status !=1 or expenses_status is null) and status in (1,2) and    a.apply_date< '"+tomorrow+"' ";
            String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and (expenses_status !=1 or expenses_status is null) and status in (1,2) and  a.apply_date< '"+tomorrow+"' ";
            List<SignFamily> signFamilies_2= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
            signFamilies_2.addAll(signFamilies_1);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies_2, SignDataFilter.level2Expenses,sql,null);
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存redis
            SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,2,6,0);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------16-1----------");
    }

    private void computequota_13(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) {
        //找出今天的签约信息 yesterday,now
        try{
           //抽取數據 分页抽取
           //List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
           //清洗數據
           FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,null);
           //统计数据
           List<Map<String, List<ETLModel>>>  returnData= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnData,null,"13");
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------13----------");
    }

    private void computequota_16_0(String sql,List<SignFamily> signFamilies_1,List<SignFamily> deleteSignFamilies) {
        String quotaId="16";
        //找出今天的签约信息
        try{
            //抽取第二种条件的语句 找出未缴费的
            sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and (expenses_status =0 or expenses_status is null) and    a.apply_date< '"+tomorrow+"' ";
            String sqlCount=" select count(id) from wlyy_sign_family a where  a.type =2 and (expenses_status =0 or expenses_status is null)  and  a.apply_date< '"+tomorrow+"' ";
            List<SignFamily> signFamilies_2= SpringUtil.getBean(DBExtract.class).extractByPage(SignFamily.class,sql,sqlCount,true);
             //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies_2, SignDataFilter.level2Expenses,sql,null);
            //统计数据
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存数据
            SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,0,4,0);

            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------16-0----------");
    }

    private void computequota_15(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) {
        String quotaId="15";
        //找出今天的签约信息
        //String sql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
       try{
           //抽取數據
          // List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
           //清洗數據
           FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies, SignDataFilter.level2Health,sql,null);
           //统计数据 一级维度
           List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
           //统计数据 二级维度
           List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel2(patientSexRoleData,null,quotaId,4,5,0);
           allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
           allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------15----------");
    }

    private void computequota_12(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) throws Exception{
        String quotaId="12";
        //找出今天的签约信息
        //String sql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
        //String deleteSql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and  a.czrq>= '"+now+"' and  a.czrq< '"+tomorrow+"' and a.expenses_status=3  ";

        try{
             //抽取數據
           // List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2Age,SignDataFilter.level3Disease,sql,null);
            //统计数据 一级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //统计数据 三级维度
            List<Map<String, Map<String, Map<String, List<ETLModel>>>>> returnD= SpringUtil.getBean(Level3Role.class).elt(patientSexRoleData);
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel3(returnD,null,quotaId,6,4,2,1,1,1);
        }catch (Exception e){

        }
        allContent.append("-----------12----------");
    }
    private void compute(Map<String, Map<String, Map>> rootMap, String rootKey, String ageCode, String diseaseType) {
        if (rootMap.containsKey(rootKey)) {
            //得到市下面的所有的年龄map
            Map<String, Map> groupMapTemp = rootMap.get(rootKey);
            if(groupMapTemp.containsKey(ageCode)){
                //得到这个年龄下的患者map
                Map<String,Long> mape= groupMapTemp.get(ageCode);
                if(mape.containsKey(diseaseType)){
                    mape.put(diseaseType,mape.get(diseaseType)+1L);
                }else{
                    mape.put(diseaseType,1L);
                }
            }else{
                //新增疾病的统计map
                Map<String, Long> groupMapTemp1 = new HashMap<String, Long>();
                groupMapTemp1.put(diseaseType, 1L);
                groupMapTemp.put(ageCode,groupMapTemp1);
            }
        } else {
            //没有就新建统计数据  新增疾病的统计map
            Map<String, Long> groupMapTemp = new HashMap<String, Long>();
            groupMapTemp.put(diseaseType, 1L);
            //把统计疾病的map放入对应的年龄组map中
            Map<String, Map> groupMapTemp2 = new HashMap<String, Map>();
            groupMapTemp2.put(ageCode,groupMapTemp);
            //把年龄组map放入市的map里面
            rootMap.put(rootKey, groupMapTemp2);
        }
    }
    private void computequota_1(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) {
        try{
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,"now");
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,"1");
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------1----------");
    }


    private void computequota_2() {
        String quotaId="2";
        try{
            //找出今天的解约信息
            String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and a.status in(-3,-4) and  a.apply_unsign_date< '"+tomorrow+"' ";
            //抽取數據
            List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
         allContent.append("----------2-----------");
    }

    private void computequota_3() {
        String quotaId="3";
        try{
            //找出今天的咨询信息
            String sql=" select * from wlyy_consult_team a where  a.czrq>= '"+now+"'and a.czrq< '"+tomorrow+"'";
            //抽取數據
            List<ConsultTeam> consultTeams= SpringUtil.getBean(DBExtract.class).extract(ConsultTeam.class,sql);
            //過濾數據
            FilterModel etlModels= consultDataFilter.filter(consultTeams,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
         allContent.append("----------3-----------");
    }

    private void computequota_4() {
        String quotaId="4";
        try{
            //找出今天的随访信息
            String sql=" select * from fv_plan a where  a.update_time< '"+tomorrow+"' and a.update_time>= '"+now+"' ";

            //找出今天的随访信息
            List<Map<String, Object>> plans = fv_jdbcTemplate.queryForList(sql);

            FilterModel etlModels = followUpDataFilter.filter(plans, sql, null);
            // 统计数据
            List<Map<String, List<ETLModel>>> returnDatas = SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }allContent.append("-----------4----------");
    }

    private void computequota_5() {
        String quotaId="5";

        String sql="SELECT * FROM wlyy_patient_health_guidance a WHERE a.czrq< '"+tomorrow+"' and a.czrq>= '"+now+"'";
        try{
            //抽取數據
            List<PatientHealthGuidance> consultTeams= SpringUtil.getBean(DBExtract.class).extract(PatientHealthGuidance.class,sql);
            //過濾數據
            FilterModel etlModels= healthGuideDataFilter.filter(consultTeams,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------5----------");
    }

    private void computequota_6(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) throws Exception {
        String quotaId="6";
        //找出今天的签约信息
      //  String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
       try{
           //抽取數據
           //List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
           //清洗數據
           FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2Sex,sql,null);
           //统计数据 1级维度
           List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
           //统计数据 二级维度
           List<Map<String, Map<String, List<ETLModel>>>>  level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);;
            //保存数据
            SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,3,1);
           allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
           allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------6----------");
    }

    private void computequota_7(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies) {
        String quotaId="7";
        try{
          //  String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2 and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
            //抽取數據
            //List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2Group,sql,null);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);
            //保存数据 1 表示：从1开始循环 6表示：循环6次 3表示 2级维度是 3
             SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,7,3,-1);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("----------7-----------");
    }

    private void computequota_8(String sql,List<SignFamily> signFamilies,List<SignFamily> deleteSignFamilies)throws Exception {
        String quotaId="8";
        try{
            //找出今天的签约信息
           // String sql=" select id,code,idcard,hospital,admin_team_code,expenses_status from wlyy_sign_family a where  a.type =2  and  a.expenses_time>= '"+now+"' and  a.expenses_time< '"+tomorrow+"' and a.expenses_status=1 ";
            //抽取數據
           // List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,SignDataFilter.level2Age,sql,null);
            //统计数据 1级维度
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //统计数据 二级维度
            List<Map<String, Map<String, List<ETLModel>>>>  level2Data= SpringUtil.getBean(Level2Role.class).elt(returnDatas);;
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel2(level2Data,null,quotaId,6,2);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("----------8-----------");
    }

    private void computequota_9() {
        String quotaId="9";
        //找出今天的待签约信息
        String sql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where   a.type =2  and a.status=0 and  a.patient_apply_date< '"+tomorrow+"'  ";
        try{
            //抽取數據
            List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
            allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
            allContent.append("统计失败:"+e.getMessage());
        }
         allContent.append("----------9-----------");
    }

    private void computequota_10() {
        String quotaId="10";
       try{
            //找出今天的已改簽信息
            String sql=" select id,code,idcard,hospital,admin_team_code from wlyy_sign_family a where  a.type =2 and a.status =100 and   a.patient_apply_date< '"+tomorrow+"' and a.expenses_status=1 ";
            //抽取數據
            List<SignFamily> signFamilies= SpringUtil.getBean(DBExtract.class).extract(SignFamily.class,sql);
            //清洗數據
            FilterModel etlModels= SpringUtil.getBean(SignDataFilter.class).filter(signFamilies,sql,null);
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= SpringUtil.getBean(Level1Role.class).elt(etlModels.getEtlModelList());
            //保存数据
             SpringUtil.getBean(RedisStorage.class).saveByLevel1(returnDatas,null,quotaId);
           allContent.append(JsonUtil.objToStr(etlModels.getLogModel()));
        }catch (Exception e){
            e.printStackTrace();
           allContent.append("统计失败:"+e.getMessage());
        }
        allContent.append("-----------10----------");
    }



    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;
    }

    /**
     * 根据年龄得到对应的code
     * @param age
     * @return
     */
    public String getAgeCode(int 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;
        }
    }

    private String saveContent(String id,Integer size, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计 quotaid:"+id+" 的数据完成 ,数据库查询到签约数目:"+size);
        string.append(",过滤的脏数据数目:"+errorCount);
        string.append(",统计到市的数据总数:"+cityCount);
        string.append(",统计到区的数据总数:"+townCount);
        string.append(",统计到机构的数据总数:"+orgCount);
        string.append(",统计到团队的数据总数:"+qkCount);
        string.append("，是否统计成功:"+isAll);
        if(!isAll){
            string.append(",失败原因:"+errorContent);
        }
        return string.toString();
    }
}
