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

import com.yihu.wlyy.statistics.dao.*;
import com.yihu.wlyy.statistics.etl.dataFilter.FollowUpDataFilter;
import com.yihu.wlyy.statistics.etl.model.ETLModel;
import com.yihu.wlyy.statistics.etl.model.FilterModel;
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.util.DateUtil;
import com.yihu.wlyy.statistics.util.JsonUtil;
import com.yihu.wlyy.statistics.vo.WlyyJobConfigVO;
import com.yihu.wlyy.statistics.vo.WlyyQuotaVO;
import org.json.JSONObject;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
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
@Scope("prototype")
@DisallowConcurrentExecution//防止到了执行时间点前一任务还在执行中，但是这时有空闲的线程，那么马上又会执行，这样一来就会存在同一job被并行执行
public class FollowUpJob implements Job {

    private WlyyQuotaVO wlyyQuota;//指标对象
    private WlyyJobConfigVO wlyyJobConfig;//配置对象
    @Autowired
    private WlyyQuotaResultDao wlyyQuotaResultDao;//指标结果Dao
    @Autowired
    private QuartzJobLogDao quartzJobLogDao;//执行日志Dao
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Level1Role levelRole;
    @Autowired
    private DBStorage dbStorage;
    @Autowired
    private FollowUpDataFilter followUpDataFilter;

    String yesterday;
    String daybefore;

    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        try {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            //初始化参数
            JobDataMap map = context.getJobDetail().getJobDataMap();
            wlyyQuota = (WlyyQuotaVO) map.get("quota");
            wlyyJobConfig = (WlyyJobConfigVO) map.get("jobConfig");

            //線刪除今天的数据
            daybefore = StringUtils.isEmpty(map.get("daybefore")) ? SignJob.getDayString(-2) : map.get("daybefore").toString();
            yesterday = StringUtils.isEmpty(map.get("yesterday")) ? SignJob.getDayString(-1) : map.get("yesterday").toString();

            computequota();
        } catch (Exception e) {
            //如果出錯立即重新執行
            JobExecutionException e2 = new JobExecutionException(e);
            e2.setRefireImmediately(true);
        }
    }

    @Transactional
    private void computequota() {
        try {
            jdbcTemplate.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());

            String sql = " select * from wlyy_followup a where  " +
                    " a.status=1 and  " +
                    " a.followup_plan_date>='" + daybefore + Constant.quota_date_last + "' and " +
                    " a.followup_plan_date< '" + yesterday + Constant.quota_date_last + "'  ";
            //找出今天的随访信息
            List<Map<String, Object>> plans = jdbcTemplate.queryForList(sql);
            FilterModel etlModels = followUpDataFilter.filter(plans, sql, yesterday);
            // 统计数据
            List<Map<String, List<ETLModel>>> returnDatas = levelRole.elt(etlModels.getEtlModelList());
            //保存数据
            dbStorage.saveByLevel1(returnDatas, yesterday, wlyyQuota);
            //保存日志
            quartzJobLog.setJobEndTime(new Date());
            quartzJobLog.setJobContent(JsonUtil.objToStr(etlModels.getLogModel()));
            quartzJobLog.setJobType(etlModels.getError() ? "1" : "0");
            quartzJobLogDao.save(quartzJobLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Date getYesterday() {

        return DateUtil.strToDateShort(yesterday);
    }

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