package com.yihu.wlyy.job;

import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.job.QuartzJobLog;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.statistics.WlyyQuotaResult;
import com.yihu.wlyy.repository.address.TownDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.job.QuartzJobLogDao;
import com.yihu.wlyy.repository.organization.HospitalDao;
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.text.SimpleDateFormat;
import java.util.*;

/**
 * 已改簽的指标执行类
 */
@Component
public class ChangeSignJob implements Job {
    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private TownDao townDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    String yesterday;
    String now;

    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='"+10+"'");

        //新建任务日志对象
        QuartzJobLog quartzJobLog = new QuartzJobLog();
        quartzJobLog.setJobStartTime(new Date());
        quartzJobLog.setJobId(wlyyJobConfig.getId());
        quartzJobLog.setJobName(wlyyJobConfig.getJobName());

        //查找出系统全部的全科医生
        List<Doctor> doctors = doctorDao.findAllQKDoctot();
        Map<String, Doctor> doctorsMap = new HashMap<String, Doctor>();
        for (Doctor doctor : doctors) {
            doctorsMap.put(doctor.getCode(), doctor);
        }
        //查找出系统全部的机构
        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<SignFamily> signFamilys = signFamilyDao.findByJiatingChaangeSignYesterday(yesterday,now);

        Map<String, Long> tjTownMap = new HashMap<String, Long>();//区级的统计map key 是区行政区划350200
        Map<String, Long> tjOrgMap = new HashMap<String, Long>();//机构的统计map key 是机构的code
        Map<String, Long> tjQkdoctorMap = new HashMap<String, Long>();//团队级的统计map 目前没有团队 先用全科医生统一  key doctorCode
        Long cityCount = 0L;
        //统计有已改簽的
        String orgCodeTemp="";
        for (SignFamily signFamily : signFamilys) {
            String doctorCode = signFamily.getDoctor();//得到已改簽中全科医生的code
            //统计团队
            compute(tjQkdoctorMap, doctorCode);
            //判断医生属于哪个机构
            Doctor doctor = doctorsMap.get(doctorCode);
            String orgCode = doctor.getHospital();
            //统计机构
            if(!"00".equals(orgCode.substring(orgCode.length()-2,orgCode.length()))){
                //统计站
                 orgCodeTemp=orgCode.substring(0,orgCode.length()-2)+"00";
                compute(tjOrgMap, orgCodeTemp);
            }else{
                //统计社区

                orgCodeTemp=orgCode;
                compute(tjOrgMap, orgCode);
            }
            Hospital hospital=hospitalsMap.get(orgCodeTemp);
            String townCode = hospital.getTown();
            //统计区
            compute(tjTownMap, townCode);
            //统计市
            cityCount++;
        }
        //保存统计的结果
        //保存全科医生的已改簽统计
        //保存全科医生的改签统计
        for (Map.Entry<String, Doctor> entry : doctorsMap.entrySet()) {
            Doctor doctor = doctorsMap.get(entry.getKey());//得到全科医生
            orgCodeTemp=getOrg(doctor.getHospital());
            Hospital hospital = hospitalsMap.get(orgCodeTemp);//得到全科医生的机构
            String city=Constant.city;
            String cityName=Constant.cityName;
            String town=hospital.getTown();
            String townName=hospital.getTownName();
            String org=hospital.getCode();
            if(!"00".equals(hospital.getCode().substring(hospital.getCode().length()-2,hospital.getCode().length()))){
                //统计站
                org=hospital.getCode().substring(0,hospital.getCode().length()-2)+"00";
            }
            String orgName=hospital.getName();
            String doctorCode=doctor.getCode();
            String doctorName=doctor.getName();
            String doctorJob=doctor.getJob();
            String level="1";
            String key=doctor.getCode();
            save(tjQkdoctorMap, key, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level);
        }
        //保存机构的改签统计
        for (Map.Entry<String, Hospital> entry : hospitalsMap.entrySet()) {
            Hospital hospital = hospitalsMap.get(entry.getKey());//得到全科医生
            String city=Constant.city;
            String cityName=Constant.cityName;
            String town=hospital.getTown();
            String townName=hospital.getTownName();
            String org=hospital.getCode();
            String orgName=hospital.getName();
            String doctorCode="";
            String doctorName="";
            String doctorJob="";
            String level="2";
            String key=hospital.getCode();
            save(tjOrgMap, key, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level);
        }
        //保存区级的改签统计
        for (Map.Entry<String, Town> entry : townsMap.entrySet()) {
            Town townObj = townsMap.get(entry.getKey());//得到全科医生
            String city=Constant.city;
            String cityName=Constant.cityName;
            String town=townObj.getCode();
            String townName=townObj.getName();
            String org="";
            String orgName="";
            String doctorCode="";
            String doctorName="";
            String doctorJob="";
            String level="3";
            String key=townObj.getCode();
            save(tjTownMap, key, city, cityName, town, townName, org, orgName, doctorCode, doctorName, doctorJob, level);
        }
        //保存市级的统计
        {
            WlyyQuotaResult wlyyQuotaResult = new WlyyQuotaResult();
            wlyyQuotaResult.setDel("1");
            wlyyQuotaResult.setCity(Constant.city);
            wlyyQuotaResult.setCityName(Constant.cityName);
            wlyyQuotaResult.setQuatoCode(wlyyQuota.getId());
            wlyyQuotaResult.setQuatoName(wlyyQuota.getName());
            wlyyQuotaResult.setQuotaDate(getYesterday());
            wlyyQuotaResult.setCreateTime(new Date());
            wlyyQuotaResult.setLevel1Type("4");
            //判断全科医生是否有改签量
            if (cityCount > 0) {
                wlyyQuotaResult.setResult(cityCount + "");
            } else {
                wlyyQuotaResult.setResult("0");
            }
            wlyyQuotaResultDao.save(wlyyQuotaResult);
        }

        quartzJobLog.setJobEndTime(new Date());
        quartzJobLog.setJobContent("统计"+getYesterday()+" 的已改簽数据完成 ,得到改签数目:"+signFamilys.size());
        quartzJobLog.setJobType("1");
        quartzJobLogDao.save(quartzJobLog);
    }

    /**
     * 统计规则
     * @param tjQkdoctorMap
     * @param doctorCode
     */
    private void compute(Map<String, Long> tjQkdoctorMap, String doctorCode) {
        if (tjQkdoctorMap.containsKey(doctorCode)) {
            tjQkdoctorMap.put(doctorCode, tjQkdoctorMap.get(doctorCode) + 1);
        } else {
            tjQkdoctorMap.put(doctorCode, 1L);
        }
    }

    /**
     * 保存方案
     * @param countMap
     * @param key
     * @param city
     * @param cityName
     * @param town
     * @param townName
     * @param org
     * @param orgName
     * @param doctorCode
     * @param doctorName
     * @param doctorJob
     * @param level
     */
    private void save(Map<String, Long> countMap, String key, String city, String cityName, String town, String townName, String org, String orgName, String doctorCode, String doctorName, String doctorJob, String level) {
        WlyyQuotaResult wlyyQuotaResult = new WlyyQuotaResult();
        wlyyQuotaResult.setDel("1");
        wlyyQuotaResult.setOrgCode(org);
        wlyyQuotaResult.setOrgName(orgName);
        wlyyQuotaResult.setCity(city);
        wlyyQuotaResult.setCityName(cityName);
        wlyyQuotaResult.setQuatoCode(wlyyQuota.getId());
        wlyyQuotaResult.setQuatoName(wlyyQuota.getName());
        wlyyQuotaResult.setQuotaDate(getYesterday());
        wlyyQuotaResult.setCreateTime(new Date());
        wlyyQuotaResult.setQkdoctorJobName(doctorJob);
        wlyyQuotaResult.setQkdoctorName(doctorName);
        wlyyQuotaResult.setQkdoctorCode(doctorCode);
        wlyyQuotaResult.setTown(town);
        wlyyQuotaResult.setTownName(townName);
        wlyyQuotaResult.setLevel1Type(level);
        //判断全科医生是否有改签量
        if (countMap.containsKey(key)) {
            wlyyQuotaResult.setResult(countMap.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;
        }
    }
    public String getYesterday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return yesterday;
    }
}
