package cn.hnthyy.thmz.common.scheduled;

import cn.hnthyy.thmz.Utils.DateUtil;
import cn.hnthyy.thmz.common.Constants;
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.his.ZyDayclosingRecordService;
import cn.hnthyy.thmz.service.thmz.MzmxsrService;
import cn.hnthyy.thmz.service.thmz.TokenService;
import cn.hnthyy.thmz.vo.ThmzmxsrParamsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

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

/**
 * 定时任务类
 */
@Slf4j
//1.主要用于标记配置类，兼备Component的效果。
@Configuration
// 2.开启定时任务
@EnableScheduling
public class ScheduledService {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ChargeFeeVoService chargeFeeVoService;
    @Autowired
    private ZyDayclosingRecordService zyDayclosingRecordService;
    @Autowired
    private MzmxsrService mzmxsrService;
    /**
     * 每20分钟执行一次
     */
    @Scheduled(cron = "0 0/20 * * * ?")
    public void refreshTokenCache() {
        tokenService.refreshTokenCache();
    }



    /**
     * 每天凌晨零点五分运行一次
     */
    @Scheduled(cron = "5 0 0 * * *")
    public void scheduled() {
        processMzsrmx(DateUtil.getPrevDayFirstSecond(),DateUtil.getFirstSecond());
    }

    /**
     * 每天23时58分将自助收费做日结
     */
    @Scheduled(cron = "0 58 23 * * *")
    public void scheduledFull() {
        processZzRj();
    }


//
//    /**
//     * 处理入库数据
//     *
//     */
//    private void process() {
//        List<MzyRequest> requests = mzyRequestService.queryMzyRequestByRequestDay(DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
//        //此时排班表数据没有同步过来，需要手动同步，以后排班系统重做后需要移除此功能
//        if(requests==null || requests.size()==0){
//            mzyRequestService.synchronizationRequest();
//        }
//    }



    /**
     * 定时处理自助缴费日结
     *
     */
    private void processZzRj() {
       try {
           Integer count = chargeFeeVoService.queryCountCanDaily(Constants.BRZZJF_CODE);
           if (count == null || count == 0) {
               log.warn("99999 费用结算失败，无可结算费用");
               return;
           }
           count = chargeFeeVoService.queryTFWDFPCount(Constants.BRZZJF_CODE);
           if (count > 0) {
               log.warn("99999 存在退费后发票未重打的发票信息，请 处理后再结账！");
               return;
           }
           chargeFeeVoService.dcountCharge(Constants.BRZZJF_CODE);
       }catch (Exception e){
           log.error("门诊自助日结出错。");
       }

        try{
            zyDayclosingRecordService.dayclosing();
        }catch (Exception e){
            log.error("住院自助日结出错。");
        }
    }



//    @Scheduled(cron = "30 01 11 22 * *")
//    public void scheduledFullMzsrmx() {
//        ProcessYpCountThread ypCountThread_2012=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2012);
//        new Thread(ypCountThread_2012).start();
//        ProcessYpCountThread ypCountThread_2013=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2013);
//        new Thread(ypCountThread_2013).start();
//        ProcessYpCountThread ypCountThread_2014=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2014);
//        new Thread(ypCountThread_2014).start();
//        ProcessYpCountThread ypCountThread_2015=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2015);
//        new Thread(ypCountThread_2015).start();
//        ProcessYpCountThread ypCountThread_2016=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2016);
//        new Thread(ypCountThread_2016).start();
//        ProcessYpCountThread ypCountThread_2017=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2017);
//        new Thread(ypCountThread_2017).start();
//        ProcessYpCountThread ypCountThread_2018=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2018);
//        new Thread(ypCountThread_2018).start();
//        ProcessYpCountThread ypCountThread_2019=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2019);
//        new Thread(ypCountThread_2019).start();
//        ProcessYpCountThread ypCountThread_2020=new ProcessYpCountThread(chargeFeeVoService,mzmxsrService,2020);
//        new Thread(ypCountThread_2020).start();
//    }







    /**
     * 处理入库数据
     *
     * @param beginTime 查询开始时间
     * @param endTime   查询结束时间
     */
    private void processMzsrmx(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 -> {
            if("497189-4".equals(mzmxsr.getPatientId())){
                System.out.println(mzmxsr.getPatientId());
            }
            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);
            }
        }
    }
}
