package com.ruoyi.task.bill;

import com.ruoyi.ss.transactionBill.domain.TransactionBill;
import com.ruoyi.ss.transactionBill.domain.vo.TransactionBillVO;
import com.ruoyi.ss.transactionBill.domain.enums.TransactionBillStatus;
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.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目启动后，处理订单任务
 * @author wjh
 * 2024/3/15
 */
@Component
@Slf4j
public class BillStartTask implements ApplicationRunner {

    @Autowired
    private TransactionBillService billService;

    @Autowired
    private BillDelayedManager billDelayedManager;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("开始处理未支付的充值订单");
        List<TransactionBillVO> billList = billService.selectNoPayedRecharge();
        if (CollectionUtils.isEmpty(billList)) {
            log.info("没有需要处理的订单");
            return;
        }
        log.info("获取到未支付充值订单：{}", billList.size());

        // 未支付已过期
        Date now = new Date();
        for (TransactionBillVO bill : billList.stream().filter(item -> item.getExpireTime() != null &&  now.compareTo(item.getExpireTime()) >= 0).collect(Collectors.toList())) {
            log.info("[未支付已过期]正在处理：{}", bill.getBillNo());
            try {
                billService.cancelRecharge(bill.getBillNo(), TransactionBillStatus.SYS_CANCELED);
            } catch (Exception e) {
                log.error("处理订单{}失败：{}", bill.getBillNo(), e.getMessage());
            }
        }

        // 未支付未过期，加入延时队列
        for (TransactionBill bill : billList.stream().filter(item -> item.getExpireTime() != null && now.compareTo(item.getExpireTime()) < 0).collect(Collectors.toList())) {
            log.info("[未支付未过期]加入延时队列：{}", bill.getBillNo());
            try {
                billDelayedManager.add(bill.getBillNo(), bill.getExpireTime().getTime());
            } catch (Exception e) {
                log.error("处理订单{}失败：{}", bill.getBillNo(), e.getMessage());
            }
        }

        log.info("未支付的充值订单已处理完成");
    }
}
