package com.jeequan.jeepay.bizcommons.manage.bill;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.interfaces.bill.IReconciliationService;
import com.jeequan.jeepay.core.interfaces.paychannel.IBillDownloadService;
import com.jeequan.jeepay.core.model.bill.ChannelBill;
import com.jeequan.jeepay.core.model.bill.ChannelBillRQ;
import com.jeequan.jeepay.core.model.bill.ChannelBillRS;
import com.jeequan.jeepay.core.model.bill.LocalBill;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.config.dynamic.DataSourceSwitch;
import com.jeequan.jeepay.db.config.dynamic.DynamicDataSource;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/***
* 对账接口
*
* @author zx
* @date 2022/3/12 14:54
*/
@Service
@Slf4j
public class ReconciliationService implements IReconciliationService {

    private static final long CHECK_PAGE_SIZE = 1; // 本地订单对账分页数量

    @Autowired private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired private IConfigContextQueryService configContextQueryService;
    @Autowired private CheckBatchService checkBatchService;
    @Autowired private CheckChannelBillService channelBillService;
    @Autowired private CheckChannelBillService checkChannelBillService;
    @Autowired private CheckDiffService checkDiffService;
    @Autowired private PayOrderService payOrderService;
    @Autowired private RefundOrderService refundOrderService;

    /**
     * 对账规则：ifCode_channelMchNo_billDate为一个批次，一批一批的对账，即相当于根据 channelMchNo 对账，channelMchNo来自于 PayInterfaceConfig
     * 每个PayInterfaceConfig 对应着一个 商户应用/服务商 和一个channelMchNo，但它们是多对一的关系，多个商户应用可能配置相同的channelMchNo
     * 根据channelMchNo查询渠道账单，确保了渠道账单只查询一次，不会出现重复
     * 根据商户应用查询本地订单会有漏洞：只查询了某一个商户应用的订单，所以使用去重的channelMchNo对账会出现漏掉本地订单的情况
     * 解决漏洞：匹配到 channelMchNo 对应的所有 商户应用，查询本地订单时使用
     * */
    @Override
    public void queryChannelBillAndCheck(String ifCode, Date billDate) {

        IBillDownloadService billDownloadService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(ifCode) + "BillDownloadService", IBillDownloadService.class);
        if (billDownloadService == null) {
            log.info("支付接口：{}，暂不支持对账！", ifCode);
            return;
        }

        // 查询去重的渠道商户号 和 本地支付配置
        List<ChannelBillRQ> channelBillRQList = buildDistinctIfParams(ifCode);
        if(CollUtil.isEmpty(channelBillRQList)){
            log.info("支付接口：{}，无支付参数配置！", ifCode);
            return;
        }

        log.info("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 支付接口ifCode={}，开始对账 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓", ifCode);
        checkBills4SingleChannel(billDownloadService, ifCode, billDate, channelBillRQList);
        log.info("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ 支付接口ifCode={}，对账结束 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑", ifCode);
    }

    @Override
    public void reloadBill4Batch(com.jeequan.jeepay.core.entity.CheckBatch checkBatch, String reloadType) {

        String ifCode = checkBatch.getIfCode();

        IBillDownloadService billDownloadService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(ifCode) + "BillDownloadService", IBillDownloadService.class);
        if (billDownloadService == null) {
            log.info("支付接口：{}，暂不支持对账！", ifCode);
            return;
        }

        // 解析失败的批次，无渠道账单，本地对应账单会存入差异表，因此需要清掉差异表相关数据
        if (reloadType.equals("release") && checkBatch.getReleaseState() == CS.NO) {
            checkDiffService.removeDiffByBatchNo(checkBatch.getBatchNo());
        }
        // 解析成功并且处理状态未完成的批次，此时不再下载对账单，应保留渠道账单，需清空差异账单
        else if (reloadType.equals("check") && checkBatch.getReleaseState() == CS.YES && checkBatch.getState() == CS.NO) {
            checkDiffService.removeDiffByBatchNo(checkBatch.getBatchNo());
        }else {
            return;
        }

        List<ChannelBillRQ> channelBillRQList = buildDistinctIfParams(ifCode);
        if (CollUtil.isEmpty(channelBillRQList)) {
            return;
        }
        List<ChannelBillRQ> collect = channelBillRQList.stream().filter(channelBillRQ -> channelBillRQ.getChannelMchNo().equals(checkBatch.getChannelMchNo())).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            return;
        }

        ChannelBillRQ channelBillRQ = collect.get(0);

        checkBills4Batch(billDownloadService, ifCode, checkBatch.getBillDate(), channelBillRQ);
    }

    // 处理差异
    @Override
    public void processCheckDiffBills(Date billDate) {

        // 处理开始时间：对账日期前三天
        Date beginDate = DateUtil.offsetDay(billDate, -3);

        List<CheckDiff> checkDiffList = checkDiffService.list(CheckDiff.gw()
                .in(CheckDiff::getHandleState, Arrays.asList(CheckDiff.HANDLE_STATE_WAITING, CheckDiff.HANDLE_STATE_HANG_UP))
                .in(CheckDiff::getDiffType, Arrays.asList(CheckDiff.DIFF_TYPE_LOCAL, CheckDiff.DIFF_TYPE_CHANNEL))
                .ge(CheckDiff::getBillDate, DateUtil.beginOfDay(beginDate))
                .le(CheckDiff::getBillDate, DateUtil.endOfDay(billDate))
        );

        Map<String, CheckDiff> localDiffMap = new HashMap<>(); // 本地多帐数据
        Map<String, CheckDiff> channelDiffMap = new HashMap<>(); // 渠道多帐数据

        checkDiffList.forEach(checkDiff -> {
            if (CheckDiff.DIFF_TYPE_LOCAL.equals(checkDiff.getDiffType())) {
                localDiffMap.put(checkDiff.getOrderId(), checkDiff);
            }else {
                channelDiffMap.put(checkDiff.getOrderId(), checkDiff);
            }
        });

        // 平账数据
        List<CheckDiff> checkSuccessList = new ArrayList<>();

        // 核对本地多帐和渠道多帐数据，将平账数据取出
        localDiffMap.forEach((key, localCheckDiff) -> {
            if (channelDiffMap.containsKey(key)) {

                CheckDiff channelCheckDiff = channelDiffMap.get(key);
                if (localCheckDiff.getAmount().equals(channelCheckDiff.getChannelAmount()) && localCheckDiff.getFeeAmount().equals(channelCheckDiff.getChannelFeeAmount())) {
                    checkSuccessList.add(localCheckDiff);
                    checkSuccessList.add(channelCheckDiff);
                }
            }
        });

        // 更新平账数据为已处理
        checkDiffService.updateHandleStateSuccess(checkSuccessList);

        // 三天前的差异对账单，状态由挂单改为未处理
        checkDiffService.updateHandleStateHangUp2Waiting(beginDate);

        // 更新三天内的批次统计数据
        checkBatchService.updateUnHandleCountAndState4CheckDiff(checkSuccessList);
    }

    /** 渠道对账 */
    public void checkBills4SingleChannel(IBillDownloadService billDownloadService, String ifCode, Date billDate, List<ChannelBillRQ> channelBillRQList) {
        // 查询渠道对账单 && 入库
        for (ChannelBillRQ channelBillRQ : channelBillRQList) {
            try {
                checkBills4Batch(billDownloadService, ifCode, billDate, channelBillRQ);
            }catch (Exception e) {
                log.error("对账单处理失败，支付接口：{}，渠道商户号：{}，对账日期：{}", ifCode, channelBillRQ.getChannelMchNo(), billDate, e);
            }
        }
    }

    /** 构建全部服务商、商户的渠道商户号与服务商或应用的配置关系 */
    public List<ChannelBillRQ> buildDistinctIfParams(String ifCode) {
        List<ChannelBillRQ> channelBillRQList = payInterfaceConfigService.selectDistinctIsvIfParams(ifCode); // 查询服务商渠道号 与 服务商号及配置参数对应关系
        channelBillRQList.addAll(payInterfaceConfigService.selectDistinctIsvSubMchIfParams(ifCode)); // 查询特约商户 与 商户应用及配置参数对应关系
        channelBillRQList.addAll(payInterfaceConfigService.selectDistinctNormalMchIfParams(ifCode)); // 查询普通商户 与 商户应用及配置参数对应关系
        return channelBillRQList;
    }

    public void checkBills4Batch(IBillDownloadService billDownloadService, String ifCode, Date billDate, ChannelBillRQ channelBillRQ) {

        String channelMchNo = channelBillRQ.getChannelMchNo(); // 渠道商户号
        List<String> infoIdList = channelBillRQ.getInfoIdList(); // channelMchNo 对应的  全部商户应用appId或服务商号集合

        String batchNo = checkBatchService.getBatchNo(ifCode, channelMchNo, billDate);
        log.info("批次对账开始，对账批次号：{}", batchNo);

        // 查询当前批次信息
        CheckBatch dbCheckBatch = checkBatchService.getById(batchNo);

        // 当前批次已解析成功，直接进行对账
        if (dbCheckBatch != null && dbCheckBatch.getReleaseState() == CS.YES) {
            checkBills4Batch(dbCheckBatch, infoIdList, channelBillRQ.getInfoType());
            return;
        }


        // 解析对账单 && 对账
        MchAppConfigContext mchAppConfigContext = null;
        if (ChannelBillRQ.INFO_TYPE_SUB.equals(channelBillRQ.getInfoType()) || ChannelBillRQ.INFO_TYPE_NORMAL.equals(channelBillRQ.getInfoType())) {
            mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(channelBillRQ.getInfoId());
            if (mchAppConfigContext == null) {
                throw new BizException("获取商户应用信息失败");
            }
        }

        // 下载并转为系统的标准对账单
        ChannelBillRS channelBillRes = billDownloadService.convertStandardBill(channelBillRQ, mchAppConfigContext, billDate, ifCode);
        if (channelBillRes == null || channelBillRes.getCheckBatch() == null) {
            throw new BizException("对账失败，对账批次为空！");
        }

        // 保存对账批次，对账批次下载/解析失败的，直接结束
        CheckBatch checkBatch = checkBatchService.saveOrUpdateCheckBatch(channelBillRes.getCheckBatch());
        if (checkBatch.getReleaseState() == CS.NO) {
            throw new BizException(checkBatch.getReleaseErrMsg());
        }

        // 服务商维度、服务商子商户维度，不对账的渠道子商户号集合
        if (StringUtils.equalsAny(channelBillRQ.getInfoType(), ChannelBillRQ.INFO_TYPE_ISV, ChannelBillRQ.INFO_TYPE_SUB)) {
            Set<String> ignoreCheckBillMchNos = channelBillRQ.getIgnoreCheckBillMchNos();
            if (CollUtil.isNotEmpty(ignoreCheckBillMchNos) && CollUtil.isNotEmpty(channelBillRes.getChannelBillList())) {
                List<ChannelBill> filterList = channelBillRes.getChannelBillList().stream().filter(channelBill -> !ignoreCheckBillMchNos.contains(channelBill.getChannelMchNo())).collect(Collectors.toList());
                channelBillRes.setChannelBillList(filterList);
            }
        }

        // 保存渠道对账单
        channelBillService.saveChannelBills(channelBillRes.getChannelBillList());

        // 当前批次对账
        checkBills4Batch(checkBatch, infoIdList, channelBillRQ.getInfoType());
    }

    /** 单个批次对账 */
    public void checkBills4Batch(CheckBatch checkBatch, List<String> infoIdList, String infoType) {

        // 查询当前批次渠道对账单
        List<CheckChannelBill> channelList = channelBillService.selectListByCheckBatchNo(checkBatch.getBatchNo());

        long pageNo = 1; // 页码： 默认第一页
        long[] totalPayOrderPage = { 1 }; // 支付订单总页码
        List<LocalBill> totalLocalDiffBills = new ArrayList<>(); // 所有本地多帐差异
        List<CheckDiff> totalChannelDiffBills = new ArrayList<>(); // 所有渠道多帐差异
        List<CheckDiff> totalOrderDiffBills = new ArrayList<>(); // 所有金额差异

        // 本地账单数据统计
        CheckBatch updateDataRecord = checkBatchService.initLocalCheckBatchData(checkBatch);

        while (true) {
            // 2、处理当前支付接口本地订单数据
            List<LocalBill> localBillList = getLocalOrderBills(pageNo++, totalPayOrderPage, updateDataRecord, infoIdList, infoType);

            // 本地账单为空，渠道也为空，对账结束
            if (CollUtil.isEmpty(localBillList) && CollUtil.isEmpty(channelList)) {
                break;
            }

            // 本地账单为空，渠道不为空，渠道账单记录为差异订单，类型为渠道多帐
            if (CollUtil.isEmpty(localBillList) && CollUtil.isNotEmpty(channelList)) {
                totalChannelDiffBills.addAll(checkDiffService.covertChannelBillToCheckDiff(channelList));
                break;
            }

            // 本地账单不为空，渠道为空，本地账单记录为差异订单，类型为本地多帐，继续循环
            if (CollUtil.isNotEmpty(localBillList) && CollUtil.isEmpty(channelList)) {
                totalLocalDiffBills.addAll(localBillList);
                continue;
            }

            // ↓↓↓↓↓↓↓↓↓↓     本地账单不为空，渠道不为空     ↓↓↓↓↓↓↓↓↓↓↓
            // 3、核对渠道、本地数据，得到差异订单
            checkBills(channelList, localBillList, totalLocalDiffBills, totalOrderDiffBills);
        }

        // 差异订单  存入差异表
        checkDiffService.saveBatchDiffBills(totalLocalDiffBills, totalChannelDiffBills, totalOrderDiffBills, updateDataRecord);
        log.info("批次对账结束，对账批次号：{}，本地多账总数={}，渠道多账总数={}，订单差异总数={}",
                checkBatch.getBatchNo(), totalLocalDiffBills.size(), totalChannelDiffBills.size(), totalOrderDiffBills.size());
    }


    // 对账，差异存入差异表
    private void  checkBills(List<CheckChannelBill> channelBillList, List<LocalBill> localBillList,
                            List<LocalBill> totalLocalDiffBills, List<CheckDiff> totalOrderDiffBills) {

        // 本地账单数据转Map，key -> 商户单号，value：账单对象
        Map<String, LocalBill> localBillMap = localBillList.stream().collect(Collectors.toMap(LocalBill::getOrderId, o -> o));

        // 遍历渠道账单
        Iterator<CheckChannelBill> it = channelBillList.iterator();
        while (it.hasNext()) {
            CheckChannelBill channelBill = it.next(); // 渠道对账单

            // 支付订单有平台订单号，退款也有平台退款商户号的情况，其他情况见了再优化
            if (StringUtils.isNotBlank(channelBill.getOrderId())) {
                if (localBillMap.containsKey(channelBill.getOrderId())) {
                    LocalBill localBill = localBillMap.get(channelBill.getOrderId()); // 本地对账单

                    // 校验订单金额（订单号一致，金额不等，本地、渠道两笔账单记录为订单差异并保存至差异表）
                    // 校验手续费，只有支付订单校验手续费
                    if (!localBill.getAmount().equals(channelBill.getChannelAmount()) ||
                            (CheckChannelBill.BILL_TYPE_PAY.equals(localBill.getBillType()) && !localBill.getFeeAmount().equals(channelBill.getChannelFeeAmount()))) {
                        // 金额不一致，记录为订单差异类型，本地、渠道数据需删除当前账单
                        totalOrderDiffBills.add(checkDiffService.covertToOrderCheckDiff(channelBill, localBill, CheckDiff.DIFF_TYPE_ORDER));
                    }

                    // 金额一致，本地、渠道数据删除当前账单
                    localBillMap.remove(localBill.getOrderId());
                    it.remove();
                }
            }
        }

        // 当前循环本地多帐订单存入总差异列表
        if (CollUtil.isNotEmpty(localBillMap)) {
            totalLocalDiffBills.addAll(new ArrayList<>(localBillMap.values()));
        }
    }

    // 生成本地对账数据
    @DataSourceSwitch(DynamicDataSource.DataSourceTypeEnum.SLAVE)
    private List<LocalBill> getLocalOrderBills(long pageNo, long[] totalPayOrderPage, CheckBatch updateDataRecord, List<String> infoIdList, String infoType) {

        String ifCode = updateDataRecord.getIfCode();
        Date billDate = updateDataRecord.getBillDate();

        if (pageNo <= totalPayOrderPage[0]) {
            // 查询支付成功的，部分退款和全额退款均认为交易成功记录
            IPage<PayOrder> payOrderPage = payOrderService.page(getIPage(pageNo), PayOrder.gw()
                    .select(PayOrder::getPayOrderId, PayOrder::getMchNo, PayOrder::getMchName, PayOrder::getAppId, PayOrder::getMchOrderNo, PayOrder::getAmount,
                            PayOrder::getMchOrderFeeAmount, PayOrder::getRefundAmount, PayOrder::getState, PayOrder::getSuccessTime, PayOrder::getCreatedAt)
                    .and(i -> i.eq(PayOrder::getState, PayOrder.STATE_SUCCESS).or().in(PayOrder::getRefundState, Arrays.asList(PayOrder.REFUND_STATE_SUB, PayOrder.REFUND_STATE_ALL)))
                    .in(ChannelBillRQ.INFO_TYPE_ISV.equals(infoType), PayOrder::getIsvNo, infoIdList)
                    .in(!ChannelBillRQ.INFO_TYPE_ISV.equals(infoType), PayOrder::getAppId, infoIdList)
                    .eq(PayOrder::getIfCode, ifCode)
                    .ge(PayOrder::getCreatedAt, billDate)
                    .le(PayOrder::getCreatedAt, DateUtil.endOfDay(billDate))
            );

            totalPayOrderPage[0] = payOrderPage.getTotal();

            // 当前页码 <= 订单表总页码
            if (CollUtil.isNotEmpty(payOrderPage.getRecords())) {
                return covertPayOrderToLocalBill(payOrderPage.getRecords(), updateDataRecord);
            }
        }


        // 当前页码 > 订单总页码，开始查询退款订单表，退款页码=当前页码 - 支付订单总页码
        long refundPageNo = pageNo - totalPayOrderPage[0];

        IPage<RefundOrder> refundOrderPage = refundOrderService.page(getIPage(refundPageNo), RefundOrder.gw()
                .select(RefundOrder::getRefundOrderId, RefundOrder::getMchNo, RefundOrder::getMchName, RefundOrder::getAppId, RefundOrder::getMchRefundNo,
                        RefundOrder::getPayAmount, RefundOrder::getRefundAmount, RefundOrder::getState, RefundOrder::getSuccessTime, RefundOrder::getCreatedAt)
                .eq(RefundOrder::getState, RefundOrder.STATE_SUCCESS)
                .in(ChannelBillRQ.INFO_TYPE_ISV.equals(infoType), RefundOrder::getIsvNo, infoIdList)
                .in(!ChannelBillRQ.INFO_TYPE_ISV.equals(infoType), RefundOrder::getAppId, infoIdList)
                .eq(RefundOrder::getIfCode, ifCode)
                .ge(RefundOrder::getCreatedAt, billDate)
                .le(RefundOrder::getCreatedAt, DateUtil.endOfDay(billDate))
        );

        return covertRefundOrderToLocalBill(refundOrderPage.getRecords(), updateDataRecord);
    }


    // 支付订单 转换为 本地标准账单
    private List<LocalBill> covertPayOrderToLocalBill(List<PayOrder> payOrderList, CheckBatch updateDataRecord) {
        if (CollUtil.isEmpty(payOrderList)) {
            return null;
        }

        // 统计数组，数据分别为：订单总数  总金额  总手续费
        final long[] totalOrderData = { 0, 0, 0 };

        List<LocalBill> localBillList =  payOrderList.stream().map(payOrder -> {
            LocalBill localOrderBill = new LocalBill();
            localOrderBill.setIfCode(updateDataRecord.getIfCode());
            localOrderBill.setBillDate(updateDataRecord.getBillDate());
            localOrderBill.setChannelMchNo(updateDataRecord.getChannelMchNo());
            localOrderBill.setOrderId(payOrder.getPayOrderId());
            localOrderBill.setBillType(CheckChannelBill.BILL_TYPE_PAY);
            localOrderBill.setMchNo(payOrder.getMchNo());
            localOrderBill.setMchName(payOrder.getMchName());
            localOrderBill.setMchAppId(payOrder.getAppId());
            localOrderBill.setMchOrderNo(payOrder.getMchOrderNo());
            localOrderBill.setAmount(payOrder.getAmount());
            localOrderBill.setFeeAmount(payOrder.getMchOrderFeeAmount());
            localOrderBill.setOrderState(payOrder.getState());
            localOrderBill.setOrderSuccessAt(payOrder.getSuccessTime());
            localOrderBill.setOrderCreateAt(payOrder.getCreatedAt());

            totalOrderData[0]++;
            totalOrderData[1] += payOrder.getAmount();
            totalOrderData[2] += payOrder.getMchOrderFeeAmount();

            return localOrderBill;
        }).collect(Collectors.toList());

        updateDataRecord.setTotalCount(updateDataRecord.getTotalCount() + Math.toIntExact(totalOrderData[0]));
        updateDataRecord.setTotalAmount(updateDataRecord.getTotalAmount() + totalOrderData[1]);
        updateDataRecord.setTotalFee(updateDataRecord.getTotalFee() + totalOrderData[2]);

        return localBillList;
    }

    // 退款订单 转换为 本地标准账单
    private List<LocalBill> covertRefundOrderToLocalBill(List<RefundOrder> refundOrderList, CheckBatch updateDataRecord) {
        if (CollUtil.isEmpty(refundOrderList)) {
            return null;
        }

        // 统计数组，数据分别为：订单总数  总金额  总手续费
        final long[] totalRefundOrderData = { 0, 0, 0 };

        List<LocalBill> localBillList = refundOrderList.stream().map(refundOrder -> {
            LocalBill localOrderBill = new LocalBill();
            localOrderBill.setIfCode(updateDataRecord.getIfCode());
            localOrderBill.setBillDate(updateDataRecord.getBillDate());
            localOrderBill.setChannelMchNo(updateDataRecord.getChannelMchNo());
            localOrderBill.setOrderId(refundOrder.getRefundOrderId());
            localOrderBill.setBillType(CheckChannelBill.BILL_TYPE_REFUND);
            localOrderBill.setMchNo(refundOrder.getMchNo());
            localOrderBill.setMchName(refundOrder.getMchName());
            localOrderBill.setMchAppId(refundOrder.getAppId());
            localOrderBill.setMchOrderNo(refundOrder.getMchRefundNo());
            localOrderBill.setAmount(refundOrder.getRefundAmount());
            localOrderBill.setRefundState(refundOrder.getState());
            localOrderBill.setOrderSuccessAt(refundOrder.getSuccessTime());
            localOrderBill.setOrderCreateAt(refundOrder.getCreatedAt());

            totalRefundOrderData[0]++;
            totalRefundOrderData[1] += refundOrder.getRefundAmount();
            totalRefundOrderData[2] += refundOrder.getRefundFeeAmount();

            return localOrderBill;
        }).collect(Collectors.toList());

        updateDataRecord.setTotalRefundCount(updateDataRecord.getTotalRefundCount() + Math.toIntExact(totalRefundOrderData[0]));
        updateDataRecord.setTotalRefundAmount(updateDataRecord.getTotalRefundAmount() + totalRefundOrderData[1]);
        updateDataRecord.setTotalFee(updateDataRecord.getTotalFee() - totalRefundOrderData[2]);

        return localBillList;
    }

    protected IPage getIPage(long pageIndex){
        return new Page(pageIndex, CHECK_PAGE_SIZE);
    }

}
