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.SignFamilyDao;
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.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.patient.PatientHealthGuidance;
import com.yihu.wlyy.statistics.model.signfamily.SignFamily;
import com.yihu.wlyy.statistics.model.system.Town;
import com.yihu.wlyy.statistics.model.team.AdminTeam;
import com.yihu.wlyy.statistics.util.DateUtil;
import 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.17.
 */
@Component
@Scope("prototype")
public class HealthGuideDataFilter {
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private SignFamilyDao signFamilyDao;

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

    public FilterModel filter(List<PatientHealthGuidance> patientHealthGuidances, 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(PatientHealthGuidance patientHealthGuidance:patientHealthGuidances){
            ETLModel etlModel=new ETLModel();
            String patient=patientHealthGuidance.getPatient();
            SignFamily signFamily= signFamilyDao.findByPatientAndType(patient,2);//只统计家庭签约
            if(signFamily == null) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_sign_noExist));
                isAll=false;
                continue;
            }
            String adminId=signFamily.getAdminTeamCode()+"";//得到团队ID
            if(StringUtils.isEmpty(adminId)){
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_adminTeam_null));
                isAll=false;
                continue;
            }
            AdminTeam adminTeam = adminTeamMap.get(adminId);
            if(adminTeam==null){
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_adminTeam_noExist));
                isAll=false;
                continue;
            }
            String orgCode=signFamily.getHospital();//得到机构id
            if(StringUtils.isEmpty(orgCode)){
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_hospital_null));
                isAll=false;
                continue;
            }
            if(orgCode.length()!=10) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_hospital_isTest));
                isAll=false;
                errorCount++;
                continue;
            }
            String orgCodeTemp="";
            //统计机构 -----------------start---------------------
            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(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_hospital_noExist));
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_town_null));
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorModels.add(ErrorModel.newEM(patientHealthGuidance.getId().toString(),ErrorModel.healthGuidance_town_noExist));
                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++;
        }

        logModel.setDate(filterDate);
        logModel.setEndTime(new Date());
        logModel.setExcuteSql(sql);
        logModel.setSuccess(isAll);
        logModel.setAllNum(patientHealthGuidances.size());
        logModel.setSuccessNum(adminCount.intValue());
        logModel.setModelList(errorModels);
        logModel.setErrorNum(errorCount.intValue());
        //String message=saveContent(patientHealthGuidances.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();
    }
}
