package com.jeequan.jeepay.bill.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.jeequan.jeepay.bill.service.ReconciliationRestockService;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.db.entity.PayInterfaceDefine;
import com.jeequan.jeepay.service.impl.PayInterfaceDefineService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 对账失败的批次  重新跑批  定时任务
 *
 * @author zx
 * @date 2022/9/9 9:40
 */
@Slf4j
@Component
public class ReconciliationRestockTask {

    @Autowired private PayInterfaceDefineService payInterfaceDefineService;
    @Autowired private ReconciliationRestockService reconciliationRestockService;

    @XxlJob("reconciliationStockTaskHandler")
    public void reconciliationStockTask() {
        log.info("执行补充对账,开始...");

        // 对账日期
        Date billDate = DateUtil.beginOfDay(DateUtil.yesterday());
        // Date billDate = DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), -3));
        log.info("补充对账日期：{}", DateUtil.formatDate(billDate));

        // 查询所有支持分账、开启分账的支付接口
        List<PayInterfaceDefine> defineList = payInterfaceDefineService.list(PayInterfaceDefine.gw()
                .eq(PayInterfaceDefine::getIsSupportCheckBill, CS.YES)
                .eq(PayInterfaceDefine::getIsOpenCheckBill, CS.YES)
        );
        if (CollUtil.isEmpty(defineList)) {
            log.info("执行补充对账结束。无支付接口支持对账");
            return;
        }

        //  遍历支付接口查询渠道对账数据 --> 对账 --> 差异入库
        for (PayInterfaceDefine payInterfaceDefine : defineList) {
            reconciliationRestockService.queryChannelBillAndCheck(payInterfaceDefine, billDate);
        }

        // 处理差异账单（处理  对账日期前三天内的、本地多帐和渠道多帐情况）
        reconciliationRestockService.processCheckDiffBills(billDate);

        log.info("执行补充对账,结束。");
    }

}
