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.db.entity.RefundOrder;
import com.jeequan.jeepay.pay.service.ChannelOrderReissueService;
import com.jeequan.jeepay.service.impl.RefundOrderService;
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 terrfly
*
* @date 2021/6/17 14:22
*/
@Slf4j
@Component
public class RefundOrderReissueTask {

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

    @Autowired private RefundOrderService refundOrderService;
    @Autowired private ChannelOrderReissueService channelOrderReissueService;

    @XxlJob("refundOrderReissueMinTaskHandler")
    public void startByMin() {

        //查询条件： 退款中的订单
        LambdaQueryWrapper<RefundOrder> lambdaQueryWrapper = RefundOrder.gw()
                .eq(RefundOrder::getState, RefundOrder.STATE_ING)
                .ge(RefundOrder::getCreatedAt, DateUtil.offsetHour(new Date(), -1)); // 创建时间 > 当前时间 - 一小时： 只查询一小时内的退款单

        start(lambdaQueryWrapper);
    }

    @XxlJob("refundOrderReissueHourTaskHandler")
    public void startByHour() {

        //查询条件： 退款中的订单
        LambdaQueryWrapper<RefundOrder> lambdaQueryWrapper = RefundOrder.gw()
                .eq(RefundOrder::getState, RefundOrder.STATE_ING)
                .le(RefundOrder::getCreatedAt, DateUtil.offsetHour(new Date(), -1)); // 创建时间 <= 当前时间 - 一小时： 只查询一小时内的退款单

       start(lambdaQueryWrapper);
    }


    private void start(LambdaQueryWrapper<RefundOrder> lambdaQueryWrapper){

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

            try {
                IPage<RefundOrder> refundOrderIPage = refundOrderService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper);

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

                for(RefundOrder refundOrder: refundOrderIPage.getRecords()){
                    channelOrderReissueService.processRefundOrder(refundOrder);
                }

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


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

        }

    }

}
