package cn.hnthyy.thmz.common.scheduled;


import cn.hnthyy.thmz.Utils.DateUtil;
import cn.hnthyy.thmz.entity.thmz.Mzmxsr;
import cn.hnthyy.thmz.enums.YesNoEnum;
import cn.hnthyy.thmz.service.his.ChargeFeeVoService;
import cn.hnthyy.thmz.service.thmz.MzmxsrService;
import cn.hnthyy.thmz.vo.ThmzmxsrParamsVo;
import org.slf4j.Logger;

import java.math.BigDecimal;
import java.util.*;

public class ProcessYpCountThread implements Runnable{
    private ChargeFeeVoService chargeFeeVoService;
    private MzmxsrService mzmxsrService;
    private Integer year;
    private Logger log=org.slf4j.LoggerFactory.getLogger(ProcessYpCountThread.class);
    @Override
    public void run() {
        log.info("=====>>>>{}年任务启动成功", year);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date beginTime = calendar.getTime();
        Date now = DateUtil.getFirstSecond();
        Date Today = DateUtil.pase("2020-09-07 00:00:00","yyyy-MM-dd HH:mm:ss");
        if(year < 2020){
            calendar.add(Calendar.YEAR, 1);
            now=calendar.getTime();
            calendar.add(Calendar.YEAR, -1);
        }
        while (beginTime.before(now)) {
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            Date endTime = calendar.getTime();
            try {
                process(beginTime, endTime);
            }catch (Exception e){
                e.printStackTrace();
                log.error("当前日期没有抓取 beginTime="+beginTime+"----endTime="+endTime);
            }
            log.info("=====>>>>>开始日期{},结束日期{}初始化统计完成", DateUtil.fomart(beginTime, "yyyy-MM-dd HH:mm:ss"), DateUtil.fomart(endTime, "yyyy-MM-dd HH:mm:ss"));
            beginTime = endTime;
            if(beginTime.equals(Today)){
                break;
            }
        }
        log.info("=====>>>>>全部初始化统计完成");
    }

    public ProcessYpCountThread(ChargeFeeVoService chargeFeeVoService,MzmxsrService mzmxsrService,Integer year){
        this.chargeFeeVoService=chargeFeeVoService;
        this.mzmxsrService=mzmxsrService;
        this.year=year;
    }




    /**
     * 处理入库数据
     *
     * @param beginTime 查询开始时间
     * @param endTime   查询结束时间
     */
    private void process(Date beginTime, Date endTime) {
        ThmzmxsrParamsVo thmzmxsrParamsVo = new ThmzmxsrParamsVo();
        thmzmxsrParamsVo.setCaseType(YesNoEnum.NO.code.toString());
        thmzmxsrParamsVo.setBeginDate(beginTime);
        thmzmxsrParamsVo.setEndDate(endTime);
        thmzmxsrParamsVo.setHisData(YesNoEnum.NO);
        List<Mzmxsr> thmzmxsrs = chargeFeeVoService.queryThmzmxsr(thmzmxsrParamsVo);
        thmzmxsrParamsVo.setHisData(YesNoEnum.YES);
        List<Mzmxsr> thmzmxsrsHis = chargeFeeVoService.queryThmzmxsr(thmzmxsrParamsVo);
        fomartThmzmxsr(thmzmxsrs, thmzmxsrsHis);
        List<Map<String,Object>> list=chargeFeeVoService.querySumAmount(thmzmxsrParamsVo);
        Map<String,BigDecimal> sumMap = new HashMap<>();
        if (list!=null && list.size()>0){
            for (Map map :list){
                String patientId = (String) map.get("patient_id");
                Double totalChargeD = (Double) map.get("total_charge");
                BigDecimal totalCharge =BigDecimal.ZERO;
                if(totalChargeD!=null){
                    totalCharge=BigDecimal.valueOf(totalChargeD);
                }
                sumMap.put(patientId,totalCharge);
            }
        }
        Date inputDate = new Date();
        //批量导入入库方式
        List<Mzmxsr> insertList = new ArrayList<>();
        thmzmxsrs.forEach(mzmxsr -> {
            mzmxsr.setInputDate(inputDate);
            BigDecimal totalCharge =sumMap.get(mzmxsr.getPatientId());
            if(totalCharge!=null && totalCharge.compareTo(BigDecimal.ZERO)!=0){
                insertList.add(mzmxsr);
                if (insertList.size() >= 50) {
                    try {
                        mzmxsrService.batchSaveMzmxsr(insertList);
                        insertList.clear();
                    } catch (Exception e) {
                        log.error("统计门诊收入明细信息保存出错，参数列表长度{}，错误信息：{}", thmzmxsrs.size(),e.getMessage());
                    }
                }
            }
        });
        if (insertList.size() > 0) {
            try {
                mzmxsrService.batchSaveMzmxsr(insertList);
                insertList.clear();
            } catch (Exception e) {
                log.error("统计门诊收入明细信息保存出错，参数列表长度{}，错误信息：{}", thmzmxsrs.size(),e.getMessage());
            }
        }
    }

    private void fomartThmzmxsr(List<Mzmxsr> thmzmxsrs, List<Mzmxsr> thmzmxsrsHis) {
        Set<Date> repeatSet = new HashSet<>();
        if (thmzmxsrs != null && thmzmxsrs.size() > 0) {
            for (Mzmxsr mzmxsr : thmzmxsrs) {
                repeatSet.add(mzmxsr.getDcountDate());
            }
        }
        if (thmzmxsrsHis != null && thmzmxsrsHis.size() > 0) {
            for (Mzmxsr mzmxsr : thmzmxsrsHis) {
                if (repeatSet.contains(mzmxsr.getDcountDate())) {
                    continue;
                }
                thmzmxsrs.add(mzmxsr);
            }
        }
    }


}
