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.job.business.Constant;
import com.yihu.wlyy.statistics.model.consult.ConsultTeam;
import com.yihu.wlyy.statistics.model.consult.ConsultTeamDto;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by Administrator on 2016.10.17.
 * 咨询数据清洗
 */
@Component
@Scope("prototype")
public class ConsultDataFilter {

    public static String level2ReplyTime = "1";//回复时间分布

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

    List<ErrorModel> errorModels=new ArrayList<ErrorModel>();//错误信息

    public FilterModel filter(List<ConsultTeam> consultTeams, 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);
        }

        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;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();

        //数据过滤清洗出脏数据  -----------start
        for(ConsultTeam consultTeam:consultTeams){
            ETLModel etlModel=new ETLModel();
            Long adminId=consultTeam.getAdminTeamCode();
            if(adminId == null||adminId<=0) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_adminTeam_null));
                isAll=false;
                continue;
            }
            String teamCode = consultTeam.getAdminTeamCode()+"";//行政的团队的id
            AdminTeam adminTeam=adminTeamMap.get(teamCode);
            if(adminTeam == null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_adminTeam_noExist));
                isAll=false;
                continue;
            }
            String orgCode = adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_hospital_null));
                isAll=false;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_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;
            }
            //统计区 ---------------start--------------
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_hospital_noExist));
                isAll=false;
                continue;
            }
            String town=hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_town_null));
                isAll=false;
                continue;
            }
            Town townObj=townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_town_noExist));
                isAll=false;
                continue;
            }


            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setAllNum(consultTeams.size());
        logModel.setSuccess(isAll);
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
       // String message=saveContent(consultTeams.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModels,isAll);
    }

    /**
     * 添加时间维度计算
     * @param consultTeams
     * @param sql
     * @param filterDate
     * @return
     */
    public FilterModel filter2(List<ConsultTeamDto> consultTeams, String sql, String filterDate,String level2key){
        //查找出系统全部的全科医生
        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);
        }

        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;//是否统计失败
        //统计有已改簽的
        List<ETLModel> etlModels=new ArrayList<ETLModel>();
        LogModel logModel=new LogModel();
        errorModels=new ArrayList<ErrorModel>();

        //数据过滤清洗出脏数据  -----------start
        for(ConsultTeamDto consultTeam:consultTeams){
            ETLModel etlModel=new ETLModel();
            Long adminId=consultTeam.getAdminTeamCode();
            if(adminId == null||adminId<=0) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_adminTeam_null));
                isAll=false;
                continue;
            }
            String teamCode = consultTeam.getAdminTeamCode()+"";//行政的团队的id
            AdminTeam adminTeam=adminTeamMap.get(teamCode);
            if(adminTeam == null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_adminTeam_noExist));
                isAll=false;
                continue;
            }
            String orgCode = adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_hospital_null));
                isAll=false;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_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;
            }
            //统计区 ---------------start--------------
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            if(hospital == null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_hospital_noExist));
                isAll=false;
                continue;
            }
            String town=hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_town_null));
                isAll=false;
                continue;
            }
            Town townObj=townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(consultTeam.getId().toString(),ErrorModel.consult_town_noExist));
                isAll=false;
                continue;
            }

            //设置二级维度的Key
            String returnLevel2Key = getLevel2Key(level2key, consultTeam);

            etlModel.setAdminTeam(adminTeam.getId()+"");
            etlModel.setHospital(orgCodeTemp);
            etlModel.setTown(hospital.getTown());
            etlModel.setCity(Constant.city);
            etlModel.setLevel2Key(returnLevel2Key);
            etlModels.add(etlModel);
            //统计数目+1
            cityCount++;
            townCount++;
            orgCount++;
            adminCount++;
        }
        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setAllNum(consultTeams.size());
        logModel.setSuccess(isAll);
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
        // String message=saveContent(consultTeams.size(),adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount,sql,filterDate);
        return FilterModel.getFiltrerMode(logModel,etlModels,isAll);
    }

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

    public String getLevel2Key(String key,ConsultTeamDto consultTeamDto){
        if(StringUtils.isNotBlank(key)&&"1".equals(key)){
            return paserReplyTime(consultTeamDto);
        }
        return "";
    }

    public String paserReplyTime(ConsultTeamDto consultTeamDto){
        if(consultTeamDto.getReplyTime()!=null){
            Calendar   calendar   =   new   GregorianCalendar();
            calendar.setTime(consultTeamDto.getReplyTime());
            //获取小时
            int hour = calendar.get(calendar.HOUR_OF_DAY);
            if(hour>=0&&hour<8){
                return Constant.level_reply_time_1;
            }else if(hour>=8&&hour<12){
                return Constant.level_reply_time_2;
            }else if(hour>=12&&hour<13){
                return Constant.level_reply_time_3;
            }else if(hour>=13&&hour<18){
                return Constant.level_reply_time_4;
            }else if(hour>=18&&hour<24){
                return Constant.level_reply_time_5;
            }else{
                return "";
            }
        }
        return "";
    }
}
