package edu.whut.trigger.job;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import edu.whut.domain.order.service.IOrderService;
import lombok.RequiredArgsConstructor;
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()
@RequiredArgsConstructor
public class NoPayNotifyOrderJob {

    private final IOrderService orderService;

    private final AlipayClient alipayClient;

    /**
     * 每 10 秒执行一次，扫描超过 1 分钟未收到回调的待支付订单
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void exec() {
        try {
            log.info("任务：检测未接收到或未正确处理的支付回调通知");
            //查找所有STATUS为PAY_WAIT的订单
            List<String> orderIds = orderService.queryNoPayNotifyOrder();
            if (null == orderIds || orderIds.isEmpty()) return;

            // 遍历订单，调用支付宝查询接口核实支付结果
            for (String orderId : orderIds) {
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel bizModel = new AlipayTradeQueryModel();
                bizModel.setOutTradeNo(orderId);
                request.setBizModel(bizModel);

                // 发起同步查询
                AlipayTradeQueryResponse alipayTradeQueryResponse = alipayClient.execute(request);
                String code = alipayTradeQueryResponse.getCode();
                // 如果支付宝返回业务成功码(10000)，则更新订单为支付成功
                if ("10000".equals(code)) {
                    orderService.changeOrderPaySuccess(orderId, alipayTradeQueryResponse.getSendPayDate());
                }
            }
        } catch (Exception e) {
            log.error("任务：检测未接收到或未正确处理的支付回调通知 失败", e);
        }
    }

}
