package com.xunwang.payment.task;

import com.xunwang.payment.entity.OrderInfo;
import com.xunwang.payment.entity.Refund;
import com.xunwang.payment.service.OrderInfoService;
import com.xunwang.payment.service.RefundService;
import com.xunwang.payment.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class wxPayTask {

    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private WxPayService wxPayService;

    @Resource
    private RefundService refundInfoService;

    /**
     * 从第0秒开始每隔2分钟执行1次，查询创建超过15分钟，并且未支付的订单
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void orderConfirm() throws Exception {
        log.info("orderConfirm 被执行");

        //找出申请支付超过15分钟并且未支付的订单
        List<OrderInfo> orderInfoList = orderInfoService.getNoPayOrderByDuration(15);

        for (OrderInfo orderInfo : orderInfoList) {
            String orderNo = orderInfo.getOrderId();
            log.warn("超时订单 ===> {}", orderNo);

            //核实订单状态：调用微信支付查单接口
            wxPayService.checkOrderStatus(orderNo);
        }
    }

    /**
     * 从第0秒开始每隔2分钟执行1次，查询创建超过5分钟，并且未退款的退款单
     */
    @Scheduled(cron = "0 0/2 * * * ?")
    public void refundConfirm() throws Exception {
        log.info("orderConfirm 被执行");

        //找出申请退款超过5分钟并且未成功的退款单
        List<Refund> refundInfoList = refundInfoService.getNoRefundOrderByDuration(5);

        for (Refund refundInfo : refundInfoList) {
            String refundNo = refundInfo.getRefundNo();
            log.warn("超时未退款的退款单号 ===> {}", refundNo);

            //核实订单状态：调用微信支付查询退款接口
            wxPayService.checkRefundStatus(refundNo);
        }
    }
}
