package com.yihu.wlyy.job;

import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.job.QuartzJobLog;
import com.yihu.wlyy.entity.patient.PatientHealthGuidance;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.job.elt.base.ETLModel;
import com.yihu.wlyy.job.elt.role.Level1Role;
import com.yihu.wlyy.job.elt.storage.DBStorage;
import com.yihu.wlyy.repository.address.TownDao;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamDao;
import com.yihu.wlyy.repository.job.QuartzJobLogDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
import com.yihu.wlyy.repository.patient.PatientHealthGuidanceDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.repository.statistics.WlyyQuotaResultDao;
import com.yihu.wlyy.web.quota.WlyyJobConfigVO;
import com.yihu.wlyy.web.quota.WlyyQuotaVO;
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.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.util.*;

/**
 * 健康指导的指标执行类
 */
@Component
public class HealthGuideJob 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 PatientHealthGuidanceDao patientHealthGuidanceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @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();
        //计算指标
        computequota();
    }

    @Transactional
    private void computequota() {
        jdbcTemplate.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+3+"'");

        //新建任务日志对象
        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<PatientHealthGuidance> patientHealthGuidances = patientHealthGuidanceDao.findByCzrqyYesterday(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(PatientHealthGuidance patientHealthGuidance:patientHealthGuidances){
            ETLModel etlModel=new ETLModel();
            String patient=patientHealthGuidance.getPatient();
            SignFamily signFamily= signFamilyDao.findByPatientAndType(patient,2);//只统计家庭签约
            if(signFamily == null) {
                errorContent.append("健康咨询id："+patientHealthGuidance.getId()+",患者code:"+patient+",家庭签约不存在");
                isAll=false;
                continue;
            }
            String adminId=signFamily.getAdminTeamId()+"";//得到团队ID
            if(StringUtils.isEmpty(adminId)){
                errorContent.append("健康咨询id："+patientHealthGuidance.getId()+",签约code："+signFamily.getCode()+",咨询的家庭签约的团队AdminTeamCode为空");
                isAll=false;
                continue;
            }
            AdminTeam adminTeam = adminTeamMap.get(adminId);
            if(adminTeam==null){
                errorContent.append("健康咨询id："+patientHealthGuidance.getId()+",签约code："+signFamily.getCode()+",咨询的家庭签约的团队不存在");
                isAll=false;
                continue;
            }
            String orgCode=signFamily.getHospital();//得到机构id
            if(StringUtils.isEmpty(orgCode)){
                errorContent.append("健康咨询id："+patientHealthGuidance.getId()+",签约code："+signFamily.getCode()+",咨询的家庭签约的机构Hospital不存在");
                isAll=false;
                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) {
                errorContent.append("健康咨询id："+patientHealthGuidance.getId()+",机构code："+orgCodeTemp+",健康咨询的医生所属的机构不存在");
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("健康咨询id："+patientHealthGuidance.getId()+",机构code："+hospital.getCode()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("健康咨询id："+patientHealthGuidance.getId()+",机构code："+hospital.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(patientHealthGuidances,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }
    private String saveContent(List<PatientHealthGuidance> patientHealthGuidances, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent, Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的健康指导数据完成 ,数据库查询到健康指导数目:"+patientHealthGuidances.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();
    }

    public String getYesterday() {
        return yesterday;
    }
}
