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

import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.role.PatientAgeRole;
import com.yihu.wlyy.statistics.etl.role.PatientGroupRole;
import com.yihu.wlyy.statistics.etl.role.PatientSexRole;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
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.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.json.JSONArray;
import org.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
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.*;

/**
 * 签约的指标执行类
 */
@Component
public class SignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private PatientAgeRole patientAgeRole;
    @Autowired
    private PatientGroupRole patientGroupRole;
    @Autowired
    private PatientSexRole patientSexRole;
    @Autowired
    private DBStorage dbStorage;

    String yesterday;
    String now;

    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        //初始化参数
        JobDataMap map = context.getJobDetail().getJobDataMap();
        wlyyQuota = (WlyyQuotaVO) map.get("quota");
        wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");
        now = StringUtils.isEmpty(map.get("now")) ? SignJob.getDayString(0) : map.get("now").toString();
        yesterday = StringUtils.isEmpty(map.get("yesterday")) ? SignJob.getDayString(-1) : map.get("yesterday").toString();
        String level1 = wlyyQuota.getLevel1();//得到一级维度
        String level2 = wlyyQuota.getLevel2();//得到二级维度
        //如果一级维度为空 不进行统计
        if (!StringUtils.isEmpty(level1)) {
            if (StringUtils.isEmpty(level2)) {
                //線刪除今天的数据
                //2级维度是空按照一级的机构唯独计算指标
                computequota();
            } else {
                switch (level2) {
                    case "1": {
                        //線刪除今天的数据
                        //患者性别
                        computequotaByPatientSex();
                        break;
                    }
                    case "2": {
                        //患者分组
                        computequotaByPatientGroup();
                        break;
                    }
                    case "3": {
                        //患者年龄
                        computequotaByPatientAge();
                        break;
                    }
                }
            }
        }
    }

    /**
     * 机构维度下患者性别维度计算指标
     */
    @Transactional
    private void computequotaByPatientSex() {

        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 6 + "'");
        try{
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //查找出系统全部的团队
            List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
            Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
            for (AdminTeam adminTeam : adminTeams) {
                adminTeamMap.put(adminTeam.getId()+"", adminTeam);
            }
            //查找出系统全部的机构
            List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
            Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
            for (Hospital hospital : hospitals) {
                hospitalsMap.put(hospital.getCode(), hospital);
            }
            //查找出厦门市全部的区
            List<Town> towns = townDao.findByCityCode(Constant.city);
            Map<String, Town> townsMap = new HashMap<String, Town>();
            for (Town town : towns) {
                townsMap.put(town.getCode(), town);
            }
            //找出今天的签约信息
            List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday, now);

            Long cityCount = new Long(0L); //统计到市的数目
            Long townCount = new Long(0L); //统计到所有区的数目
            Long orgCount =new Long(0L);//统计到所有机构的数目
            Long adminCount = new Long(0L);//统计到所有团队的数目
            Long errorCount=new Long(0L);//脏数据
            Boolean isAll=true;//是否统计失败
            StringBuffer errorContent=new StringBuffer();
            //统计有已改簽的
            List<ETLModel> etlModels=new ArrayList<ETLModel>();
            //数据过滤清洗出脏数据  -----------start
            for(SignFamily signFamily:signFamilys){
                ETLModel etlModel=new ETLModel();
                String orgCode = signFamily.getHospital();
                if(StringUtils.isEmpty(orgCode)) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String orgCodeTemp="";
                if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                    //站
                    orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                }else{
                    //社区
                    orgCodeTemp=orgCode;
                }
                //判断社区有没有值
                Hospital hospital=hospitalsMap.get(orgCodeTemp);
                if(hospital == null) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Long adminId=signFamily.getAdminTeamId();
                if(adminId == null||adminId<=0) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
                if(adminTeam == null) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String idCard=signFamily.getIdcard();
                if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String town =hospital.getTown();
                if(StringUtils.isEmpty(town)) {
                    errorContent.append("签约code："+signFamily.getCode()+",机构表的中的town为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Town townObj =townsMap.get(town);
                if(townObj==null) {
                    errorContent.append("签约code："+signFamily.getCode()+",机构表的中的town不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModel.setIdcard(signFamily.getIdcard());
                etlModels.add(etlModel);
                //统计数目+1
                cityCount++;
                townCount++;
                orgCount++;
                adminCount++;
            }
            //数据过滤清洗出脏数据  -----------end
            try{
                //统计数据
                List<Map<String, List<ETLModel>>>  returnData1s= levelRole.elt(etlModels);
                List<Map<String, Map<String, List<ETLModel>>>> patientSexRoleData= patientSexRole.elt(returnData1s);
                //保存数据
                dbStorage.saveByLevel2(patientSexRoleData,yesterday,wlyyQuota,3,1);
            }catch (Exception e){
                e.printStackTrace();
                errorContent.append("统计失败:"+e.getMessage());
            }
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
            quartzJobLog.setJobType(isAll?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 机构维度患者分组维度计算指标
     */
    @Transactional
    private void computequotaByPatientGroup() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 7 + "'");

        try {
            //数组里面第一个是健康人群 第二个是慢病人群 第三个是65岁以上人群
            Map<String, Map<String, Long>> cityGroupMap = new HashMap<String, Map<String, Long>>();//key是市行政代码 目前只有厦门市
            cityGroupMap.put(Constant.city, new HashMap<String, Long>());
            Map<String, Map<String, Long>> townGroupMap = new HashMap<String, Map<String, Long>>();//key是区行政代码
            Map<String, Map<String, Long>> orgGroupMap = new HashMap<String, Map<String, Long>>();//key是机构代码
            //新建任务日志对象
            QuartzJobLog QuartzJobLog = new QuartzJobLog();
            QuartzJobLog.setJobStartTime(new Date());
            QuartzJobLog.setJobId(wlyyJobConfig.getId());
            QuartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //查找出系统全部的团队
            List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
            Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
            for (AdminTeam adminTeam : adminTeams) {
                adminTeamMap.put(adminTeam.getId()+"", adminTeam);
            }
            //查找出系统全部的机构
            List<Hospital> hospitals = hospitalDao.findHospital2();
            Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
            for (Hospital hospital : hospitals) {
                hospitalsMap.put(hospital.getCode(), hospital);
                Map<String, Long> one = new HashMap<String, Long>();
                one.put("1", 0L);
                one.put("2", 0L);
                one.put("3", 0L);
                one.put("4", 0L);
                one.put("5", 0L);
                one.put("6", 0L);
                orgGroupMap.put(hospital.getCode(), one);
            }
            //查找出厦门市全部的区
            List<Town> towns = townDao.findByCityCode(Constant.city);
            Map<String, Town> townsMap = new HashMap<String, Town>();
            for (Town town : towns) {
                townsMap.put(town.getCode(), town);
                Map<String, Long> one = new HashMap<String, Long>();
                one.put("1", 0L);
                one.put("2", 0L);
                one.put("3", 0L);
                one.put("4", 0L);
                one.put("5", 0L);
                one.put("6", 0L);
                townGroupMap.put(town.getCode(), one);
            }

            //找出今天的签约信息
            List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday, now);
            Long cityCount = 0L; //统计到市的数目
            Long townCount = 0L; //统计到所有区的数目
            Long orgCount = 0L;//统计到所有机构的数目
            Long qkCount = 0L;//统计到所有全科医生的数目
            Long errorCount=0L;//错误数目
            boolean isAll=true;//是否统计失败
            StringBuffer errorContent=new StringBuffer();
            //统计有签约的
            for (SignFamily signFamily : signFamilys) {
                String patient = signFamily.getPatient();
                //设置查看病人所在分组
                List<DoctorPatientGroupInfo> dctorPatientGroupInfo = doctorPatientGroupInfoDao.findByMorenPatient(patient);
                String group ="";//得到该签约病人的所在分组 1 普通 2 慢病 3是 65岁以上人群  4是 高血压 5是糖尿病 100是高血压和糖尿病
                if (dctorPatientGroupInfo != null && dctorPatientGroupInfo.size() > 0) {
                    group=dctorPatientGroupInfo.get(0).getGroup();
                } else {
                    errorContent.append("签约code："+signFamily.getCode()+",患者未分组");
                    group="1";
                }
                String orgCode = signFamily.getHospital();
                if(StringUtils.isEmpty(orgCode)) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String orgCodeTemp="";
                if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                    //站
                    orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                }else{
                    //社区
                    orgCodeTemp=orgCode;
                }
                //判断社区有没有值
                Hospital hospital=hospitalsMap.get(orgCodeTemp);
                if(hospital == null) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Long adminId=signFamily.getAdminTeamId();
                if(adminId == null||adminId<=0) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
                if(adminTeam == null) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String idCard=signFamily.getIdcard();
                if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String town =hospital.getTown();
                if(StringUtils.isEmpty(town)) {
                    errorContent.append("签约code："+signFamily.getCode()+",机构表的中的town为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Town townObj =townsMap.get(town);
                if(townObj==null) {
                    errorContent.append("签约code："+signFamily.getCode()+",机构表的中的town不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                //统计市  现在只有厦门市 默认先写死 后面再改
                compute_level2_2(cityGroupMap, group,Constant.city);
                cityCount++;
                //统计区
                compute_level2_2(townGroupMap, group,town);
                townCount++;
                //统计站
                orgCode=hospital.getCode();
                if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                    //统计站
                   orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                    //统计机构
                   compute_level2_2(orgGroupMap, group,orgCodeTemp);
                } else {
                    //统计机构
                    compute_level2_2(orgGroupMap, group,hospital.getCode());
                }
                orgCount++;
                boolean hasGXY = false;//有高血压
                boolean hasTNB = false;//有糖尿病
                if ("2".equals(group)) {
                    //如果是慢病的 统计高血压的 糖尿病  1高血压，2糖尿病
                    String jsonString = redisTemplate.opsForValue().get("disease:" + patient);
                    if (StringUtils.isEmpty(jsonString)) {
                        continue;
                    }
                    //排除数据 只留下高血压和糖尿病
                    List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
                    JSONArray redisValues = new JSONArray(jsonString);
                    for (Object obj : redisValues) {
                        JSONObject redisValue = (JSONObject)(obj);
                        if(!redisValue.has("signType")){
                            continue;
                        }
                        //排除掉三师签约
                        if ("1".equals(redisValue.get("signType").toString())) {
                            continue;
                        }
                        String disease =  redisValue.getString("disease");
                        if ("1".equals(disease)) {
                            jsonObjects.add(redisValue);
                            hasGXY = true;//设置有高血压
                        }
                        if ("2".equals(disease)) {
                            jsonObjects.add(redisValue);
                            hasTNB = true;//设置有糖尿病
                        }
                    }
                    if(jsonObjects.size()==0){
                        continue;//如果没有高血压和糖尿病 不统计
                    }
                    if (hasGXY && hasTNB) {
                        group = "100";//有高血压又有糖尿病
                    } else if(hasGXY){
                        group = 4 + "";//4高血压，5糖尿病
                    }else if(hasTNB){
                        group = 5 + "";//4高血压，5糖尿病
                    }
                    //统计市  现在只有厦门市 默认先写死 后面再改
                    compute_level2_2(cityGroupMap, group,Constant.city);
                    //统计区
                    compute_level2_2(townGroupMap, group,town);
                    //统计站
                    orgCode=hospital.getCode();
                    if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                        //统计站
                        orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                        //统计机构
                        compute_level2_2(orgGroupMap, group,orgCodeTemp);
                    } else {
                        //统计机构
                        compute_level2_2(orgGroupMap, group,hospital.getCode());
                    }

                }
            }

            //保存统计数据
            //保存市的统计数据
            for (Map.Entry<String, Map<String, Long>> entry : cityGroupMap.entrySet()) {
                //保存健康人群
                Map<String, Long> oneMap=entry.getValue();
                for(Map.Entry<String, Long> entryCh: oneMap.entrySet()){
                    String city=entry.getKey();
                    String cityName=Constant.cityName;
                    String town="";
                    String townName="";
                    String org="";
                    String orgName="";
                    String level="4";
                    String key=entryCh.getKey();
                    save_level2_2(oneMap, city, cityName, town, townName, org, orgName, level, key);
                }
            }
            //保存区级
            //保存区的统计数据
            for (Map.Entry<String, Town> townEntry : townsMap.entrySet()) {
                //判断该区是否有统计数据
                Map<String, Long> oneTownGroupMap = townGroupMap.get(townEntry.getKey());//得到当个区的统计数据
                Town townObj = townEntry.getValue();//得到区级信息
                for(Map.Entry<String, Long> entryCh: oneTownGroupMap.entrySet()){
                    String city=entryCh.getKey();
                    String cityName=Constant.cityName;
                    String town=townObj.getCode();
                    String townName=townObj.getName();
                    String org="";
                    String orgName="";
                    String level="3";
                    String key=entryCh.getKey();
                    save_level2_2(oneTownGroupMap, city, cityName, town, townName, org, orgName, level, key);
                }
            }
            //保存机构
            for (Map.Entry<String, Hospital> hospitalEntry : hospitalsMap.entrySet()) {
                //判断该机构是否有统计数据
                Map<String, Long> oneOrgGroupMap = orgGroupMap.get(hospitalEntry.getKey());//得到当个机构的统计数据
                Hospital hospital = hospitalEntry.getValue();//得到区级信息
                for(Map.Entry<String, Long> entryCh: oneOrgGroupMap.entrySet()){
                    Hospital hospital1=hospitalEntry.getValue();
                    if(hospital1==null)continue;
                    String city=entryCh.getKey();
                    String cityName=Constant.cityName;
                    String town=hospital.getTown();
                    String townName=hospital.getTownName();
                    String org=hospital.getCode();
                    String orgName=hospital.getName();
                    String level="2";
                    String key=entryCh.getKey();
                    save_level2_2(oneOrgGroupMap, city, cityName, town, townName, org, orgName, level, key);
                }
            }

            QuartzJobLog.setJobEndTime(new Date());
            QuartzJobLog.setJobContent(saveContent(signFamilys,qkCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
            QuartzJobLog.setJobType(isAll?"1":"0");
            quartzJobLogDao.save(QuartzJobLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void save_level2_2(Map<String, Long> oneMap, String city, String cityName, String town, String townName, String org, String orgName, String level, String key) {
        WlyyQuotaResult wlyyQuotaResult = new WlyyQuotaResult();
        wlyyQuotaResult.setDel("1");
        wlyyQuotaResult.setCity(city);
        wlyyQuotaResult.setCityName(cityName);
        wlyyQuotaResult.setTown(town);
        wlyyQuotaResult.setTownName(townName);
        wlyyQuotaResult.setOrgCode(org);
        wlyyQuotaResult.setOrgName(orgName);
        wlyyQuotaResult.setQuatoCode(wlyyQuota.getId());
        wlyyQuotaResult.setQuatoName(wlyyQuota.getName());
        wlyyQuotaResult.setQuotaDate(getYesterday());
        wlyyQuotaResult.setCreateTime(new Date());
        wlyyQuotaResult.setLevel1Type(level);//市级
        wlyyQuotaResult.setLevel2Type(key);
        wlyyQuotaResult.setLevel2TypeName(Constant.getLevelGroupName(key));
        if (oneMap != null && oneMap.containsKey(key)) {
            wlyyQuotaResult.setResult(oneMap.get(key) + "");
        } else {
            wlyyQuotaResult.setResult("0");
        }
        wlyyQuotaResultDao.save(wlyyQuotaResult);
    }

    private void compute_level2_2(Map<String, Map<String, Long>> cityGroupMap, String group,String key) {
        if (cityGroupMap.containsKey(key)) {
            Map<String, Long> groupMapTemp = cityGroupMap.get(key);
            groupMapTemp.put(group, (groupMapTemp.get(group) == null ? 0l : groupMapTemp.get(group)) + 1);
            cityGroupMap.put(key, groupMapTemp);
        } else {
            Map<String, Long> groupMapTemp = new HashMap<String, Long>();
            groupMapTemp.put(group, 1L);
            cityGroupMap.put(key, groupMapTemp);
        }
    }

    /**
     * 机构维度患者年龄维度计算指标
     */
    @Transactional
    private void computequotaByPatientAge() {
        try {
            jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 8 + "'");
            //新建任务日志对象
            QuartzJobLog quartzJobLog = new QuartzJobLog();
            quartzJobLog.setJobStartTime(new Date());
            quartzJobLog.setJobId(wlyyJobConfig.getId());
            quartzJobLog.setJobName(wlyyJobConfig.getJobName());
            //查找出系统全部的团队
            List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
            Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
            for (AdminTeam adminTeam : adminTeams) {
                adminTeamMap.put(adminTeam.getId()+"", adminTeam);
            }
            //查找出系统全部的机构
            List<Hospital> hospitals = hospitalDao.findHospital2();
            Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
            for (Hospital hospital : hospitals) {
                hospitalsMap.put(hospital.getCode(), hospital);
            }
            //查找出厦门市全部的区
            List<Town> towns = townDao.findByCityCode(Constant.city);
            Map<String, Town> townsMap = new HashMap<String, Town>();
            for (Town town : towns) {
                townsMap.put(town.getCode(), town);
            }
            //找出今天的签约信息
            List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday, now);
            Long cityCount = new Long(0L); //统计到市的数目
            Long townCount = new Long(0L); //统计到所有区的数目
            Long orgCount =new Long(0L);//统计到所有机构的数目
            Long adminCount = new Long(0L);//统计到所有团队的数目
            Long errorCount=new Long(0L);//脏数据
            Boolean isAll=true;//是否统计失败
            StringBuffer errorContent=new StringBuffer();
            //统计有已改簽的
            List<ETLModel> etlModels=new ArrayList<ETLModel>();
            //数据过滤清洗出脏数据  -----------start
            for(SignFamily signFamily:signFamilys){
                ETLModel etlModel=new ETLModel();
                String orgCode = signFamily.getHospital();
                if(StringUtils.isEmpty(orgCode)) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String orgCodeTemp="";
                if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                    //站
                    orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                }else{
                    //社区
                    orgCodeTemp=orgCode;
                }
                //判断社区有没有值
                Hospital hospital=hospitalsMap.get(orgCodeTemp);
                if(hospital == null) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Long adminId=signFamily.getAdminTeamId();
                if(adminId == null||adminId<=0) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
                if(adminTeam == null) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String idCard=signFamily.getIdcard();
                if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                    errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                String town =hospital.getTown();
                if(StringUtils.isEmpty(town)) {
                    errorContent.append("签约code："+signFamily.getCode()+",机构表的中的town为空");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                Town townObj =townsMap.get(town);
                if(townObj==null) {
                    errorContent.append("签约code："+signFamily.getCode()+",机构表的中的town不存在");
                    isAll=false;
                    errorCount++;
                    continue;
                }
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModel.setIdcard(signFamily.getIdcard());
                etlModels.add(etlModel);
                //统计数目+1
                cityCount++;
                townCount++;
                orgCount++;
                adminCount++;
            }
            //数据过滤清洗出脏数据  -----------end
            try{
                //统计数据
                List<Map<String, List<ETLModel>>>  returnData1s= levelRole.elt(etlModels);
                List<Map<String, Map<String, List<ETLModel>>>> patientAgeRoleData= patientAgeRole.elt(returnData1s);
                //保存数据
                dbStorage.saveByLevel2(patientAgeRoleData,yesterday,wlyyQuota,6,2);
            }catch (Exception e){
                e.printStackTrace();
                errorContent.append("统计失败:"+e.getMessage());
            }
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
            quartzJobLog.setJobType(isAll?"1":"0");
            quartzJobLogDao.save(quartzJobLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 机构维度计算指标
     */
    @Transactional
    private void computequota() {

        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='" + yesterday + "' and quato_code='" + 1 + "'");
        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());

        //查找出系统全部的团队
        List<AdminTeam> adminTeams=doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId()+"", adminTeam);
        }
        //查找出系统全部的机构
        List<Hospital> hospitals = hospitalDao.findHospitalzxFWZ();
        Map<String, Hospital> hospitalsMap = new HashMap<String, Hospital>();
        for (Hospital hospital : hospitals) {
            hospitalsMap.put(hospital.getCode(), hospital);
        }
        //查找出厦门市全部的区
        List<Town> towns = townDao.findByCityCode(Constant.city);
        Map<String, Town> townsMap = new HashMap<String, Town>();
        for (Town town : towns) {
            townsMap.put(town.getCode(), town);
        }
        //找出今天的签约信息 yesterday,now
        List<SignFamily> signFamilys = signFamilyDao.findByJiatingSignYesterdayExpensesStatus(yesterday, now);

        Long cityCount = new Long(0L); //统计到市的数目
        Long townCount = new Long(0L); //统计到所有区的数目
        Long orgCount =new Long(0L);//统计到所有机构的数目
        Long adminCount = new Long(0L);//统计到所有团队的数目
        Long errorCount=new Long(0L);//脏数据
        Boolean isAll=true;//是否统计失败
        StringBuffer errorContent=new StringBuffer();
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        //数据过滤清洗出脏数据  -----------start
        for(SignFamily signFamily:signFamilys){
            ETLModel etlModel=new ETLModel();
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //站
                orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
            }else{
                //社区
                orgCodeTemp=orgCode;
            }
            //判断社区有没有值
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的hospital数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            Long adminId=signFamily.getAdminTeamId();
            if(adminId == null||adminId<=0) {
                errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据为空");
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId()+"");
            if(adminTeam == null) {
                errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的Admin_Team_Id数据不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorContent.append("签约code："+signFamily.getCode()+",签约表中(wlyy_sign_family)中的idCard数据异常");
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("签约code："+signFamily.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("签约code："+signFamily.getCode()+",机构表的中的town不存在");
                isAll=false;
                errorCount++;
                continue;
            }
            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setIdcard(signFamily.getIdcard());
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        //数据过滤清洗出脏数据  -----------end
        try{
            //统计数据
            List<Map<String, List<ETLModel>>>  returnDatas= levelRole.elt(etlModels);
            //保存数据
            dbStorage.saveByLevel1(returnDatas,yesterday,wlyyQuota);
        }catch (Exception e){
            e.printStackTrace();
            errorContent.append("统计失败:"+e.getMessage());
        }
        //保存日志
        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent(saveContent(signFamilys,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    /*
    得到昨天的日期字符串  yyyy-MM-dd
     */
    public String getYesterday() {
        return yesterday;
    }

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

    private String saveContent(List<SignFamily> signFamilys, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的签约数据完成 ,数据库查询到签约数目:"+signFamilys.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();
    }

}
