package com.ruoyi.task.pay;

import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.ruoyi.bst.pay.domain.PayQuery;
import com.ruoyi.bst.pay.domain.enums.PayStatus;
import com.ruoyi.bst.pay.mapper.PayMapper;
import com.ruoyi.bst.pay.service.PayService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class PayTask implements ApplicationRunner {

    @Autowired
    private PayService payService;

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 查询所有未支付的支付单
        PayQuery query = new PayQuery();
        query.setStatusList(PayStatus.unPayList());
        List<String> payList = payMapper.selectNoList(query);

        log.info("查询到{}条未支付的支付单", payList.size());
        for (String no : payList) {
            scheduledExecutorService.schedule(() -> {
                try {
                    payService.refreshPayResultBeforeExpire(no);
                } catch (Exception e) {
                    log.error("刷新支付结果失败，支付单号：{}", no, e);
                }
            }, 0, TimeUnit.SECONDS);
        }
    }
    
}
