package com.yihu.wlyy.statistics.etl.dataFilter;

import com.yihu.wlyy.statistics.dao.DoctorAdminTeamDao;
import com.yihu.wlyy.statistics.dao.HospitalDao;
import com.yihu.wlyy.statistics.dao.TownDao;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.ErrorModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
import com.yihu.wlyy.statistics.etl.model.LogModel;
import com.yihu.wlyy.statistics.etl.mycache.CachePool;
import com.yihu.wlyy.statistics.job.business.Constant;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Created by Administrator on 2016.10.16.
 * 签约数据的过滤
 */
@Component
@Scope("prototype")
public class SignDataFilter {

    public static String level2Sex="1";//性别
    public static String level2Age="2";//年龄
    public static String level2Group="3";//分组
    public static String level2Expenses="4";//费用
    public static String level2Health="5";//健康服务分布
    public static String level2Age2="6";//年龄
    public static String level2AgeDisease="7";//年龄疾病

    public static String level3Disease="1";//疾病分组

    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private CachePool cachePool;

    List<ErrorModel> errorModels=new ArrayList<ErrorModel>();
    private int count=0;
    /**
     * 过滤数据
     * @param signFamilies 签约列表
     * @return
     */
    public FilterModel filter(List<SignFamily> signFamilies,String sql){
        return filterCommon(signFamilies,null,null,sql,null);
    }
    /**
     * 过滤数据
     * @param signFamilies 签约列表
     * @param filterDate 不传默认是但在的时间
     * @return
     */
    public FilterModel filter(List<SignFamily> signFamilies,String sql,String filterDate){
        return filterCommon(signFamilies,null,null,sql,filterDate);
    }
    /**
     * 过滤数据
     * @param signFamilies 签约列表
     * @param level2Key 二级维度的key
     * @param filterDate 过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    public FilterModel filter(List<SignFamily> signFamilies,String level2Key,String sql,String filterDate){
        return filterCommon(signFamilies,level2Key,null,sql,filterDate);
    }
    /**
     * 过滤数据
     * @param signFamilies 签约列表
     * @param level2Key 二级维度的key
     * @param level3Key 三级维度的key
     * @param filterDate 过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    public FilterModel filter(List<SignFamily> signFamilies,String level2Key,String level3Key,String sql,String filterDate){
        return filterCommon(signFamilies,level2Key,level3Key,sql,filterDate);
    }

    /**
     * 公共的抽取方法
     *  @param signFamilies 签约列表
     * @param level2Key 二级维度的key
     * @param level3Key 三级维度的key
     * @param filterDate 过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    private FilterModel filterCommon(List<SignFamily> signFamilies ,String level2Key,String level3Key,String sql,String filterDate) {
        //查找出系统全部的全科医生
        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<ETLModel> etlModelList=new ArrayList<>();//返回的ETL數據

        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;//是否统计失败
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();
        for (int i=0;i<signFamilies.size();i++){
            SignFamily signFamily=signFamilies.get(i);
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_null));
                isAll=false;
                errorCount++;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_isTest));
                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) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_town_null));
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_town_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
           Long adminId=signFamily.getAdminTeamCode();
            if(adminId == null||adminId<=0) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_adminTeam_null));
                isAll=false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(adminId+"");
            if(adminTeam == null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_adminTeam_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error));
                isAll=false;
                errorCount++;
                continue;
            }
            //设置二级维度的Key
            String returnLevel2Key=getLevel2Key(level2Key,signFamily);
            String returnLevel3Key=getLevel3Key(level3Key,signFamily);
            if(StringUtils.isEmpty(returnLevel2Key)){
                //没有二级维度
                ETLModel etlModel=new ETLModel();
                etlModel.setAdminTeam(adminTeam.getId()+"");
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModelList.add(etlModel);
            }else{
                String[] level2Keys=returnLevel2Key.split(",");
                for(int j=0;j<level2Keys.length;j++){
                    ETLModel etlModel=new ETLModel();
                    etlModel.setLevel2Key(level2Keys[j]);
                    etlModel.setLevel3Key(returnLevel3Key);
                    etlModel.setAdminTeam(adminTeam.getId()+"");
                    etlModel.setHospital(orgCodeTemp);
                    etlModel.setTown(hospital.getTown());
                    etlModel.setCity(Constant.city);
                    etlModelList.add(etlModel);
                }
            }
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setSuccess(isAll);
        logModel.setAllNum(signFamilies.size());
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
        //String message=saveContent(signFamilies.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModelList,isAll);
    }

    private String getLevel3Key(String level3Key, SignFamily signFamily) {
        String returnLevel3Key=null;
        if(!StringUtils.isEmpty(level3Key)){
            switch (level3Key){
                //疾病
                case "1" :{
                    returnLevel3Key = getDisease(signFamily);
                    break;
                }
            }
        }
        return returnLevel3Key;
    }

    /**
     * 根据签约表的患者code从缓存得到疾病标签
     * @param signFamily
     * @return
     */
    private String getDisease(SignFamily signFamily) {
        boolean hasGXY = false;//有高血压
        boolean hasTNB = false;//有糖尿病
        //如果是慢病的 统计高血压的 糖尿病  1高血压，2糖尿病  3 糖尿病和高血压 4健康人群数
        String diseaseType="4";
        //得到患者的疾病标签
        List<String> diseaseList=  cachePool.getDiseaseGroup(signFamily.getPatient());
        if(diseaseList!=null&&diseaseList.size()>0){
            for (String diseaseCode:diseaseList){
                if("1".equals(diseaseCode)){//判斷是否有高血壓
                    diseaseType="1";
                    hasGXY=true;
                }
                if("2".equals(diseaseCode)){//判斷是否有糖尿病
                    diseaseType="2";
                    hasTNB=true;
                }
            }
        }
        if (hasTNB&&hasGXY){
            diseaseType="3";
        }
        return diseaseType;
    }

    /**
     * 得到二级维度的key
     * @param level2Key
     * @return
     */
    private String getLevel2Key(String level2Key,SignFamily signFamily) {
        String returnLevel2Key=null;
        if(!StringUtils.isEmpty(level2Key)){
             switch (level2Key){
                 //性别
                 case "1" :{
                     returnLevel2Key = getSex(signFamily);
                     return returnLevel2Key;
                 }
                 //年龄
                 case "2" :{
                     returnLevel2Key = getAge(signFamily);
                     return returnLevel2Key;
                 }
                 //分组
                 case "3" :{
                     //得到患者的分组标签
                     returnLevel2Key = getGroup(signFamily);
                     return returnLevel2Key;
                 }
                 //费用
                 case "4" :{
                     returnLevel2Key = getExpenses(signFamily);
                     return returnLevel2Key;
                 }
                 //健康服务分布
                 case "5" :{
                     returnLevel2Key = getHealth(signFamily);
                     return returnLevel2Key;
                 }
                 //年龄
                 case "6" :{
                     returnLevel2Key = getAge2(signFamily);
                     return returnLevel2Key;
                 }
                 //年龄疾病
                 case "7" :{
                     returnLevel2Key = getAgeDisease(signFamily);
                     return returnLevel2Key;
                 }
             }
        }
        return returnLevel2Key;
    }

    private String getAgeDisease(SignFamily signFamily) {
        //得到患者年龄
        StringBuffer returnLevel2KeyBuffer=new StringBuffer("0");
        int age= IdCardUtil.getAgeForIdcard(signFamily.getIdcard());
        if(0==age){
            errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error_age));
        }
        if(age>=65){
            returnLevel2KeyBuffer.append(",3");
        }
        //疾病标签
        String returnLevel2KeyTemp = "";
        boolean hasGXY=false;//有高血压
        boolean hasTNB=false;//糖尿病
        //得到患者的疾病标签
        List<String> diseaseList=  cachePool.getDiseaseGroup(signFamily.getPatient());
        if(diseaseList!=null&&diseaseList.size()>0){
            for (String diseaseCode:diseaseList){
                if("1".equals(diseaseCode)){//判斷是否有高血壓
                    returnLevel2KeyTemp="1";
                    hasGXY=true;
                }
                if("2".equals(diseaseCode)){//判斷是否有糖尿病
                    returnLevel2KeyTemp="2";
                    hasTNB=true;
                }
            }
        }
        if (hasTNB&&hasGXY){
            returnLevel2KeyTemp="1,2";
        }
        if(!StringUtils.isEmpty(returnLevel2KeyTemp)){
            returnLevel2KeyBuffer.append(","+returnLevel2KeyTemp);
        }
        return returnLevel2KeyBuffer.toString();
    }

    private String getAge2(SignFamily signFamily) {
        String returnLevel2Key;
        int age= IdCardUtil.getAgeForIdcard(signFamily.getIdcard());
        if(0==age){
            errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error_age));
        }
        returnLevel2Key=getAgeCode2(age);
        return returnLevel2Key;
    }

    private String getHealth(SignFamily signFamily) {
        String returnLevel2Key="0";//查找每个患者的健康分布标签
        try{
            returnLevel2Key=cachePool.getHealthGroup(signFamily.getPatient());
        }catch (Exception e){
            e.printStackTrace();
            return returnLevel2Key;
        }
        if(StringUtils.isEmpty(returnLevel2Key)){
            return "0";
        }
        return returnLevel2Key;
    }

    private String getExpenses(SignFamily signFamily) {
        if("1".equals(signFamily.getExpensesStatus())){
            count++;
        }
        String returnLevel2Key= signFamily.getExpensesStatus();
        if(StringUtils.isEmpty(returnLevel2Key)){
            returnLevel2Key="0";
        }
        return returnLevel2Key;
    }

    private String getGroup(SignFamily signFamily) {
        String returnLevel2Key="";
        String group=cachePool.getPatientGroup(signFamily.getPatient());
        if(StringUtils.isEmpty(group)){
            group="0";
        }
        StringBuffer returnLevel2KeyBuffer=new StringBuffer(group);
        //如果是慢病组  区分65岁以上还是以下   65岁以上的慢病患者是7  65岁上下是2
        if("2".equals(returnLevel2KeyBuffer.toString())){
             Integer age=IdCardUtil.getAgeForIdcard(signFamily.getIdcard());
            if(age>65){
                returnLevel2KeyBuffer=new StringBuffer("7");
            }
        }
        if("2".equals(returnLevel2KeyBuffer.toString())||"7".equals(returnLevel2KeyBuffer.toString())){
            String returnLevel2KeyTemp="-1";
            boolean hasGXY=false;//有高血压
            boolean hasTNB=false;//糖尿病
            //得到患者的疾病标签
            List<String> diseaseList=  cachePool.getDiseaseGroup(signFamily.getPatient());
            if(diseaseList!=null&&diseaseList.size()>0){
                for (String diseaseCode:diseaseList){
                    if("1".equals(diseaseCode)){//判斷是否有高血壓
                        returnLevel2KeyTemp="4";
                        hasGXY=true;
                    }
                    if("2".equals(diseaseCode)){//判斷是否有糖尿病
                        returnLevel2KeyTemp="5";
                        hasTNB=true;
                    }
                }
            }
            if (hasTNB&&hasGXY){
                returnLevel2KeyTemp="6";
            }
            returnLevel2KeyBuffer.append(","+returnLevel2KeyTemp);
        }
        returnLevel2Key=returnLevel2KeyBuffer.toString();
        return returnLevel2Key;
    }

    private String getAge(SignFamily signFamily) {
        String returnLevel2Key;
        int age= IdCardUtil.getAgeForIdcard(signFamily.getIdcard());
        if(0==age){
            errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error_age));
        }
        returnLevel2Key=getAgeCode(age);
        return returnLevel2Key;
    }

    private String getSex(SignFamily signFamily) {
        String returnLevel2Key;
        try{
            returnLevel2Key= IdCardUtil.getSexForIdcard(signFamily.getIdcard());
        }catch (Exception e){
            //如果解析失败 默认是男 并且纪录解析失败的签约code
            errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error_sex));
            return Constant.level_sex_2;
        }
        return returnLevel2Key;
    }

    private String saveContent(Integer size, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent,Long errorCount,String sql,String filterDate) {
        if(StringUtils.isEmpty(filterDate)){
            filterDate= DateUtil.dateToStrLong(new Date());
        }
        StringBuffer string=new StringBuffer("统计"+filterDate+" 的数据完成 ,数据库查询到数目:"+size);
        string.append(",sql语句:"+sql);
        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();
    }
    /**
     * 根据年龄得到对应的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 FilterModel filterNoTeam(List<SignFamily> signFamilies ,String level2Key,String level3Key, String sql, String filterDate) {

        //查找出系统全部的机构
        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<ETLModel> etlModelList=new ArrayList<>();//返回的ETL數據

        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;//是否统计失败
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();
        for (int i=0;i<signFamilies.size();i++){
            SignFamily signFamily=signFamilies.get(i);
            String orgCode = signFamily.getHospital();
            if(StringUtils.isEmpty(orgCode)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_null));
                isAll=false;
                errorCount++;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_isTest));
                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) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_hospital_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_town_null));
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_town_noExist));
                isAll=false;
                errorCount++;
                continue;
            }
            String idCard=signFamily.getIdcard();
            if(idCard == null||((idCard.length()!=18&&idCard.length()!=15))) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(),ErrorModel.sign_idcard_error));
                isAll=false;
                errorCount++;
                continue;
            }
            //设置二级维度的Key
            String returnLevel2Key=getLevel2Key(level2Key,signFamily);
            String returnLevel3Key=getLevel3Key(level3Key,signFamily);
            if(StringUtils.isEmpty(returnLevel2Key)){
                //没有二级维度
                ETLModel etlModel=new ETLModel();
                etlModel.setHospital(orgCodeTemp);
                etlModel.setTown(hospital.getTown());
                etlModel.setCity(Constant.city);
                etlModelList.add(etlModel);
            }else{
                String[] level2Keys=returnLevel2Key.split(",");
                for(int j=0;j<level2Keys.length;j++){
                    ETLModel etlModel=new ETLModel();
                    etlModel.setLevel2Key(level2Keys[j]);
                    etlModel.setLevel3Key(returnLevel3Key);
                    etlModel.setHospital(orgCodeTemp);
                    etlModel.setTown(hospital.getTown());
                    etlModel.setCity(Constant.city);
                    etlModelList.add(etlModel);
                }
            }
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setSuccess(isAll);
        logModel.setAllNum(signFamilies.size());
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
        //String message=saveContent(signFamilies.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModelList,isAll);
    }
    /**
     * 根据年龄得到对应的code
     *
     * @param age
     * @return
     */
    public String getAgeCode2(Integer age) {
        if (age <= 65) {
            return Constant.level_age2_1;
        } else {
            return Constant.level_age2_2;
        }
    }


}
