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.components.mq.model.ZftSettOrderMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.db.entity.PayAlizftSettRecord;
import com.jeequan.jeepay.service.impl.PayAlizftSettRecordService;
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 xiaoyu
 * 
 * @date 2023/1/15 15:35
 */
@Slf4j
@Component
public class AlizftSettReissueTask {

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

    @Autowired private PayAlizftSettRecordService alizftSettRecordService;
    @Autowired private IMQSender mqSender;

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

        //查询条件：
        LambdaQueryWrapper<PayAlizftSettRecord> lambdaQueryWrapper = PayAlizftSettRecord.gw()
                .eq(PayAlizftSettRecord::getState, PayAlizftSettRecord.ZFT_SETT_STATUS_WAIT_RETRY); // 限流待重试

        //当前时间 减去10分钟。
        Date offsetDate = DateUtil.offsetMinute(new Date(), -10);

        lambdaQueryWrapper.or(r -> {
            r.eq(PayAlizftSettRecord::getState, PayAlizftSettRecord.ZFT_SETT_STATUS_NOT)
                    .le(PayAlizftSettRecord::getSettTime, offsetDate);  // 未结算 & （ 结算时间 + 10分钟 >= 当前时间 ） 【 为了避免和MQ冲突， 查询的是： 到达结算时间后再加上10分钟后的记录 】
        });

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

            try {
                IPage<PayAlizftSettRecord> iPage = alizftSettRecordService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper);

                if(iPage == null || iPage.getRecords().isEmpty()){ //本次查询无结果, 不再继续查询;
                    break;
                }

                for(PayAlizftSettRecord settRecord: iPage.getRecords()){
                    mqSender.send(ZftSettOrderMQ.build(settRecord.getSettleNo()));
                }

                //已经到达页码最大量，无需再次查询
                if(iPage.getPages() <= currentPageIndex){
                    break;
                }
                currentPageIndex++;

            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
    }



}
