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.SignFamilyRenew;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.IdCardUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

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

    public static String level2Reson = "1";//续签原因

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

    List<ErrorModel> errorModels = new ArrayList<ErrorModel>();
    private int count = 0;

    /**
     * 过滤数据
     *
     * @param signFamilies 签约列表
     * @return
     */
    public FilterModel filter(List<SignFamilyRenew> signFamilies, String sql) {
        return filterCommon(signFamilies, null, null, sql, null);
    }

    /**
     * 过滤数据
     *
     * @param signFamilies 签约列表
     * @param filterDate   不传默认是但在的时间
     * @return
     */
    public FilterModel filter(List<SignFamilyRenew> signFamilies, String sql, String filterDate) {
        return filterCommon(signFamilies, null, null, sql, filterDate);
    }

    /**
     * 过滤数据
     *
     * @param signFamilies 签约列表
     * @param level2Key    二级维度的key
     *                     1:性别 2:年龄 3:分组 4:费用 5:健康服务分布 6:年龄 7:年龄疾病
     * @param filterDate   过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    public FilterModel filter(List<SignFamilyRenew> signFamilies, String level2Key, String sql, String filterDate) {
        return filterCommon(signFamilies, level2Key, null, sql, filterDate);
    }

    /**
     * 过滤数据
     *
     * @param signFamilies 签约列表
     * @param level2Key    二级维度的key
     *                     1:健康服务分布
     * @param level3Key    三级维度的key
     *                     1.疾病
     * @param filterDate   过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    public FilterModel filter(List<SignFamilyRenew> signFamilies, String level2Key, String level3Key, String sql, String filterDate) {
        return filterCommon(signFamilies, level2Key, level3Key, sql, filterDate);
    }

    /**
     * 公共的抽取方法
     *
     * @param signFamilies 签约列表
     * @param level2Key    二级维度的key
     *                     1:性别 2:年龄 3:分组 4:费用 5:健康服务分布 6:年龄 7:年龄疾病
     * @param level3Key    三级维度的key
     *                     1.疾病
     * @param filterDate   过滤的是哪天的数据 yyyy-MM-dd
     * @return
     */
    private FilterModel filterCommon(List<SignFamilyRenew> 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++) {
            SignFamilyRenew 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.renew_hospital_noExist));
                isAll = false;
                errorCount++;
                continue;
            }
            String town = hospital.getTown();
            if (StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_town_null));
                isAll = false;
                errorCount++;
                continue;
            }
            Town townObj = townsMap.get(town);
            if (townObj == null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_town_noExist));
                isAll = false;
                errorCount++;
                continue;
            }
            Long adminId = signFamily.getAdminTeamId();
            if (adminId == null || adminId <= 0) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_adminTeam_null));
                isAll = false;
                errorCount++;
                continue;
            }
            AdminTeam adminTeam = adminTeamMap.get(adminId + "");
            if (adminTeam == null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_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.renew_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, SignFamilyRenew 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(SignFamilyRenew 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
     * 1:性别 2:年龄 3:分组 4:费用 5:健康服务分布 6:年龄 7:年龄疾病
     *
     * @param level2Key
     * @return
     */
    private String getLevel2Key(String level2Key, SignFamilyRenew signFamily) {
        String returnLevel2Key = null;
        if (!StringUtils.isEmpty(level2Key)) {
            switch (level2Key) {
                //理由
                case "1": {
                    returnLevel2Key = getReason(signFamily);
                    return returnLevel2Key;
                }
            }
        }
        return returnLevel2Key;
    }

    private String getReason(SignFamilyRenew signFamily) {
        return signFamily.getRenewChangeReason();
    }

    public FilterModel filterNoTeam(List<SignFamilyRenew> 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<AdminTeam> adminTeams = doctorAdminTeamDao.findAllTeam();
        Map<String, AdminTeam> adminTeamMap = new HashMap<String, AdminTeam>();
        for (AdminTeam adminTeam : adminTeams) {
            adminTeamMap.put(adminTeam.getId() + "", adminTeam);
        }
        //查找出厦门市全部的区
        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++) {
            SignFamilyRenew signFamily = signFamilies.get(i);
            String orgCode = signFamily.getHospital();
            if (StringUtils.isEmpty(orgCode)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_hospital_null));
                isAll = false;
                errorCount++;
                continue;
            }
            if (orgCode.length() != 10) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_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.renew_hospital_noExist));
                isAll = false;
                errorCount++;
                continue;
            }
            String town = hospital.getTown();
            if (StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_town_null));
                isAll = false;
                errorCount++;
                continue;
            }
            Town townObj = townsMap.get(town);
            if (townObj == null) {
                errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_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.renew_idcard_error));
                isAll = false;
                errorCount++;
                continue;
            }
            Long adminId = signFamily.getAdminTeamId();
            //医生团队列表
            List<Long> adminTeamList = new ArrayList<>();
            if (adminId == null || adminId <= 0) {
                //如果团队是空 把数目给待签约的医生 可能是健康管理师也可以能是全科
                if (!StringUtils.isEmpty(signFamily.getDoctor())) {
                    //找出全科医生所在的团队
                    String sqlD = "select DISTINCT team_id from wlyy_admin_team_member w where w.doctor_code='" + signFamily.getDoctor() + "'";
                    adminTeamList = jdbcTemplate.queryForList(sqlD, Long.class);
                    if (adminTeamList == null && adminTeamList.size() == 0) {
                        errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_adminTeam_null));
                        isAll = false;
                        errorCount++;
                        continue;
                    }
                } else if (!StringUtils.isEmpty(signFamily.getDoctorHealth())) {
                    //找出健康管理师所在的团队
                    String sqlD = "select DISTINCT team_id from wlyy_admin_team_member w where w.doctor_code='" + signFamily.getDoctorHealth() + "'  ";
                    adminTeamList = jdbcTemplate.queryForList(sqlD, Long.class);
                    if (adminTeamList == null && adminTeamList.size() == 0) {
                        errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_adminTeam_null));
                        isAll = false;
                        errorCount++;
                        continue;
                    }
                } else {
                    errorModels.add(ErrorModel.newEM(signFamily.getCode(), ErrorModel.renew_adminTeam_null));
                    isAll = false;
                    errorCount++;
                    continue;
                }
            }
            //设置二级维度的Key
            String returnLevel2Key = getLevel2Key(level2Key, signFamily);
            String returnLevel3Key = getLevel3Key(level3Key, signFamily);
            if (StringUtils.isEmpty(returnLevel2Key)) {
                //没有二级维度
                for (int teamNum = 0; teamNum < adminTeamList.size(); teamNum++) {
                    ETLModel etlModel = new ETLModel();
                    etlModel.setHospital(orgCodeTemp);
                    etlModel.setTown(hospital.getTown());
                    etlModel.setCity(Constant.city);
                    etlModel.setAdminTeam(adminTeamList.get(teamNum) + "");
                    etlModelList.add(etlModel);
                }
            } else {
                String[] level2Keys = returnLevel2Key.split(",");
                for (int j = 0; j < level2Keys.length; j++) {
                    for (int teamNum = 0; teamNum < adminTeamList.size(); teamNum++) {
                        ETLModel etlModel = new ETLModel();
                        etlModel.setLevel2Key(level2Keys[j]);
                        etlModel.setLevel3Key(returnLevel3Key);
                        etlModel.setHospital(orgCodeTemp);
                        etlModel.setTown(hospital.getTown());
                        etlModel.setCity(Constant.city);
                        etlModel.setAdminTeam(teamNum + "");
                        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);
    }

}
