package com.jeequan.jeepay.pay.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.interfaces.paychannel.IChannelAccountService;
import com.jeequan.jeepay.core.model.cashout.CashoutRetMsg;
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.entity.ChannelAccountCashoutRecord;
import com.jeequan.jeepay.pay.service.MchChannelCashoutService;
import com.jeequan.jeepay.service.impl.ChannelAccountCashoutRecordService;
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;

/*
* 提现补单定时任务
*
* @author zx
*
* @date 2021/6/8 17:47
*/
@Slf4j
@Component
public class MchChannelCashOutReissueTask {

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

    @Autowired private ChannelAccountCashoutRecordService channelAccountCashoutRecordService;
    @Autowired private MchChannelCashoutService mchChannelCashoutService;
    @Autowired private IConfigContextQueryService configContextQueryService;

    @XxlJob("mchChannelCashOutReissueTaskHandler")
    public void start() {

        //当前时间 减去1天。
        Date offsetDate = DateUtil.offsetDay(new Date(), -1);

        // 查询条件： 提现中的订单  &&  一天内的
        LambdaQueryWrapper<ChannelAccountCashoutRecord> lambdaQueryWrapper = ChannelAccountCashoutRecord.gw()
                .eq(ChannelAccountCashoutRecord::getState, ChannelAccountCashoutRecord.CASHOUT_STATE_ING)
                .ge(ChannelAccountCashoutRecord::getCreatedAt, offsetDate);

        int currentPageIndex = 1; //当前页码
        while(true){

            try {
                IPage<ChannelAccountCashoutRecord> payOrderIPage = channelAccountCashoutRecordService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper);
                if(payOrderIPage == null || payOrderIPage.getRecords().isEmpty()){ //本次查询无结果, 不再继续查询;
                    break;
                }
                currentPageIndex++;

                for(ChannelAccountCashoutRecord cashoutRecord: payOrderIPage.getRecords()){
                    queryCashoutResult(cashoutRecord);
                }

                //已经到达页码最大量，无需再次查询
                if(payOrderIPage.getPages() < currentPageIndex){
                    break;
                }
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
    }

    private void queryCashoutResult(ChannelAccountCashoutRecord cashoutRecord) {

        try {
            // 提现查询接口是否存在
            IChannelAccountService channelAccountService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(cashoutRecord.getIfCode()) + "ChannelAccountService", IChannelAccountService.class);
            // 提现查询接口实现不存在
            if(channelAccountService == null){
                throw new BizException(cashoutRecord.getIfCode() + "提现查询接口实现不存在");
            }

            MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfoV2(cashoutRecord.getMchNo(), cashoutRecord.getAppId(),cashoutRecord.getMchExtNo());

            // 提现查询
            CashoutRetMsg cashoutRetMsg = channelAccountService.cashoutQuery(cashoutRecord, mchAppConfigContext, cashoutRecord.getIfCode());

            mchChannelCashoutService.processChannelMsg(cashoutRetMsg, cashoutRecord.getRid());

            log.info("\n完成处理支付接口：{}, 应用appId：{}，提现任务", cashoutRecord.getIfCode(), cashoutRecord.getAppId());
        }catch (BizException e) {
            log.error("支付接口：{}, 应用appId：{}，提现异常：{}", cashoutRecord.getIfCode(), cashoutRecord.getAppId(), e.getMessage()); // 内存异常，打印错误，继续执行
        }

    }


}
