package com.yihu.wlyy.statistics.job.business;

import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.role.Level1Role;
import com.yihu.wlyy.statistics.etl.storage.DBStorage;
import com.yihu.wlyy.statistics.model.hosptial.Hospital;
import com.yihu.wlyy.statistics.model.job.QuartzJobLog;
import com.yihu.wlyy.statistics.model.job.WlyyQuotaResult;
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.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.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.beans.factory.annotation.Value;
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.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 随访的指标执行类
 */
@Component
public class FollowUpJob implements Job {

    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private SignFamilyDao signFamilyDao;

    @Autowired
    private JdbcTemplate jdbcTemplate_wlyy;
    @Autowired
    private DoctorAdminTeamDao doctorAdminTeamDao;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    private org.apache.tomcat.jdbc.pool.DataSource fvdataSource=new org.apache.tomcat.jdbc.pool.DataSource();//随访数据源

    private JdbcTemplate jdbcTemplate = new JdbcTemplate();

    String yesterday;
    String now;
    @Value("fv.jdbc.driver")
    String fv_jdbc_driver;
    @Value("fv.jdbc.url")
    String fv_jdbc_url;
    @Value("fv.jdbc.username")
    String fv_jdbc_username;
    @Value("fv.jdbc.password")
    String fv_jdbc_password;

    @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");

        fvdataSource.setDriverClassName(fv_jdbc_driver);
        fvdataSource.setUrl(fv_jdbc_url);
        fvdataSource.setUsername(fv_jdbc_username);
        fvdataSource.setPassword(fv_jdbc_password);
        //计算指标
        jdbcTemplate.setDataSource(fvdataSource);//初始化随访的数据源
        //線刪除今天的数据
        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_wlyy.execute("delete from wlyy_quota_result where quota_date='"+yesterday+"' and quato_code='"+4+"'");

        //新建任务日志对象
        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<Map<String,Object>> plans = getFvYesterday();

        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(Map<String,Object> plan:plans){
            ETLModel etlModel=new ETLModel();
            Object idCard=plan.get("id_card");//得到隨訪的身份證
            if(StringUtils.isEmpty(idCard)){
                errorContent.append("随访id："+plan.get("id")+",随访(fv_plan)表id_card为空");
                isAll=false;
                continue;
            }
            SignFamily signFamily=signFamilyDao.findByIdcard(idCard.toString());
            if(signFamily==null){
                errorContent.append("随访id："+plan.get("id")+",签约code：,随访中的患者身份证在签约表中找不到数据");
                isAll=false;
                continue;
            }
            Long adminTeamId=signFamily.getAdminTeamId();
            if(adminTeamId==null||adminTeamId<=0){
                errorContent.append("随访id："+plan.get("id")+",签约code:"+signFamily.getCode()+" 中的adminTeamId为空");
                isAll=false;
                continue;
            }
            AdminTeam adminTeam=adminTeamMap.get(signFamily.getAdminTeamId());
            if(adminTeam==null){
                errorContent.append("随访id："+plan.get("id")+",签约code："+signFamily.getCode()+",医生团队不存在");
                isAll=false;
                continue;
            }
            //统计机构------------------start ------------------
            //判断医生属于哪个机构
            String orgCodeTemp="";
            String orgCode=adminTeam.getOrgCode();
            if(StringUtils.isEmpty(orgCode)){
                errorContent.append("随访id："+plan.get("id")+",团队Id："+adminTeam.getId()+",随访的医生所属的团队(wlyy_admin_team)机构为空");
                isAll=false;
                continue;
            }
            //统计机构
            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："+plan.get("id")+",团队Id："+adminTeam.getId()+",随访的医生所属的团队的机构不存在");
                isAll=false;
                continue;
            }
            String town =hospital.getTown();
            if(StringUtils.isEmpty(town)) {
                errorContent.append("随访id："+plan.get("id")+",机构Id："+hospital.getId()+",机构表的中的town为空");
                isAll=false;
                errorCount++;
                continue;
            }
            Town townObj =townsMap.get(town);
            if(townObj==null) {
                errorContent.append("随访id："+plan.get("id")+",机构Id："+hospital.getId()+",机构表的中的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(plans,adminCount,orgCount,townCount,cityCount,isAll,errorContent,errorCount));
        quartzJobLog.setJobType(isAll?"1":"0");
        quartzJobLogDao.save(quartzJobLog);
    }


    private String saveContent(List<Map<String, Object>> plans, Long qkCount, Long orgCount, Long townCount, Long cityCount, boolean isAll, StringBuffer errorContent, Long errorCount) {
        StringBuffer string=new StringBuffer("统计"+yesterday+" 的随访完成 ,数据库查询到随访数目:"+plans.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;
    }

    public List<Map<String,Object>> getFvYesterday() {
        String sql=" select * from fv_plan a where unix_timestamp(a.update_time)>=unix_timestamp('"+yesterday+"') and unix_timestamp(a.update_time)< unix_timestamp('"+now+"')  ";
        return jdbcTemplate.queryForList(sql);
    }
    private void save(Map<String, Long> tjTownMap, String city, String cityName, String town, String townName, String org, String orgName, String doctorCode, String doctorName, String doctorJob, String level, String key) {
        WlyyQuotaResult wlyyQuotaResult = new WlyyQuotaResult();
        wlyyQuotaResult.setDel("1");
        wlyyQuotaResult.setCity(city);
        wlyyQuotaResult.setCityName(cityName);
        wlyyQuotaResult.setTown(town);
        wlyyQuotaResult.setTownName(townName);
        wlyyQuotaResult.setOrgCode(org);
        wlyyQuotaResult.setOrgName(orgName);
        wlyyQuotaResult.setQkdoctorJobName(doctorJob);
        wlyyQuotaResult.setQkdoctorName(doctorName);
        wlyyQuotaResult.setQkdoctorCode(doctorCode);
        wlyyQuotaResult.setQuatoCode(wlyyQuota.getId());
        wlyyQuotaResult.setQuatoName(wlyyQuota.getName());
        wlyyQuotaResult.setQuotaDate(getYesterday());
        wlyyQuotaResult.setCreateTime(new Date());
        wlyyQuotaResult.setLevel1Type(level);
        //判断全科医生是否有随访量
        if (tjTownMap.containsKey(key)) {
            wlyyQuotaResult.setResult(tjTownMap.get(key) + "");
        } else {
            wlyyQuotaResult.setResult("0");
        }
        wlyyQuotaResultDao.save(wlyyQuotaResult);
    }

    private String getOrg(String org){
        if(!"00".equals(org.substring(org.length()-2,org.length()))){
            return org.substring(0,org.length()-2)+"00";
        }else{
            return org;
        }
    }
}
