package com.saye.hospitalgd.scheduler.job;

import com.saye.hospitalgd.commons.log.LogUtil;
import com.saye.hospitalgd.scheduler.jobMethod.MedicalInsuranceReconciliationMethod;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.HashMap;

/**
 * @author yuan
 * @version 1.0
 * @description: 医保对账定时任务
 * @date 2025/10/24
 */
public class MedicalInsuranceReconciliationJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        
        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
        String id = jobDataMap.getString("id");
        String name = jobDataMap.getString("name");
        String trade_date = jobDataMap.getString("trade_date");
        
        // 如果没有指定对账日期，使用前一天的日期（医保对账通常对前一天的数据）
        if (trade_date == null || trade_date.trim().isEmpty()) {
            java.util.Calendar calendar = java.util.Calendar.getInstance();
            calendar.add(java.util.Calendar.DATE, -1); // 前一天
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            trade_date = sdf.format(calendar.getTime());
            LogUtil.info(this.getClass(), "未指定对账日期，自动使用前一天日期：" + trade_date);
        }

        LogUtil.info(this.getClass(), "医保对账定时任务【" + name + "】开始执行，日期：" + trade_date);

        try {
            MedicalInsuranceReconciliationMethod method = new MedicalInsuranceReconciliationMethod();
            HashMap<Object, Object> result = method.executeMedicalInsuranceReconciliation(trade_date);

            String errCode = (String) result.get("errCode");
            if ("0".equals(errCode)) {
                LogUtil.info(this.getClass(), "医保对账定时任务【" + name + "】执行成功");
            } else {
                LogUtil.error(this.getClass(), "医保对账定时任务【" + name + "】执行失败：" + result.get("errMsg"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error(this.getClass(), "医保对账定时任务【" + name + "】执行异常：" + e.getMessage());
            throw new JobExecutionException(e);
        }
    }
}


