package com.ruoyi.task.bill;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.ss.payBill.domain.PayBillQuery;
import com.ruoyi.ss.payBill.domain.PayBillVO;
import com.ruoyi.ss.payBill.domain.enums.PayBillStatus;
import com.ruoyi.ss.payBill.service.PayBillService;
import com.ruoyi.ss.transactionBill.domain.TransactionBillQuery;
import com.ruoyi.ss.transactionBill.domain.vo.TransactionBillVO;
import com.ruoyi.ss.transactionBill.domain.enums.TransactionBillStatus;
import com.ruoyi.ss.transactionBill.domain.enums.TransactionBillType;
import com.ruoyi.ss.transactionBill.service.TransactionBillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wjh
 * 2024/4/10
 */
@Component("payTask")
@Slf4j
public class PayTask implements ApplicationRunner {

    @Autowired
    private PayBillService payBillService;

    /**
     * 更新支付结果
     */
    @Transactional
    public void refreshPayResult() {
        PayBillQuery query = new PayBillQuery();
        query.setStartCreateTime(LocalDateTime.now().plusMinutes(-10));
        query.setStatus(PayBillStatus.PAYING.getStatus());
        List<PayBillVO> payList = payBillService.selectPayBillList(query);
        if (CollectionUtils.isEmptyElement(payList)) {
            log.info("十分钟以内没有支付中的支付订单");
            return;
        }

        payBillService.refreshPayResult(payList);
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 查询支付中的支付订单，将其加入到延迟队列
        PayBillQuery query = new PayBillQuery();
        query.setStatus(PayBillStatus.PAYING.getStatus());
        List<PayBillVO> list = payBillService.selectPayBillList(query);
        if (CollectionUtils.isEmptyElement(list)) {
            log.info("没有支付中的订单");
            return;
        }
        log.info("查询到{}个正在支付的订单", list.size());
        for (PayBillVO bill : list) {
            try {
                payBillService.refreshPayResultMaxCount(bill, 20L, TimeUnit.SECONDS, 10);
            } catch (Exception e) {
                log.error("加入延迟队列异常：{} ", bill.getPayNo());
            }
        }
    }
}
