package com.gxwebsoft.shop.task;

import com.gxwebsoft.common.core.annotation.IgnoreTenant;
import com.gxwebsoft.payment.dto.PaymentResponse;
import com.gxwebsoft.payment.enums.PaymentType;
import com.gxwebsoft.payment.exception.PaymentException;
import com.gxwebsoft.payment.service.PaymentService;
import com.gxwebsoft.shop.entity.ShopOrder;
import com.gxwebsoft.shop.service.ShopOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 退款状态查询定时任务
 * 定期查询处理中的退款订单状态，并更新订单状态
 *
 * @author WebSoft
 * @since 2025-01-26
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "shop.order.refund-query", name = "enabled", havingValue = "true", matchIfMissing = true)
public class RefundStatusQueryTask {

    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private PaymentService paymentService;

    /**
     * 查询退款状态并更新订单
     * 生产环境：每10分钟执行一次
     * 开发环境：每2分钟执行一次（便于测试）
     */
    @Scheduled(cron = "${shop.order.refund-query.cron:0 0/10 * * * ?}")
    @IgnoreTenant("定时任务需要处理所有租户的退款订单")
    public void queryRefundStatusAndUpdateOrders() {
        log.info("开始执行退款状态查询任务...");

        try {
            long startTime = System.currentTimeMillis();
            int totalProcessedCount = 0;

            // 查询所有退款处理中的订单（状态为5）
            List<ShopOrder> refundProcessingOrders = shopOrderService.lambdaQuery()
                    .eq(ShopOrder::getOrderStatus, 5)
                    .isNotNull(ShopOrder::getRefundOrder)
                    .list();

            if (refundProcessingOrders.isEmpty()) {
                log.info("没有找到退款处理中的订单");
                return;
            }

            log.info("找到 {} 个退款处理中的订单，开始查询退款状态...", refundProcessingOrders.size());

            int successCount = 0;
            int failedCount = 0;

            for (ShopOrder order : refundProcessingOrders) {
                try {
                    // 查询退款状态
                    PaymentResponse response = paymentService.queryRefund(
                            order.getRefundOrder(),    // 退款单号
                            PaymentType.WECHAT_NATIVE, // 支付类型（这里假设是微信支付）
                            order.getTenantId()        // 租户ID
                    );

                    if (response != null) {
                        // 根据退款状态更新订单
                        if (response.getSuccess()) {
                            // 退款成功
                            order.setOrderStatus(6); // 退款成功
                            shopOrderService.updateById(order);
                            log.info("订单 {} 退款成功，更新订单状态为退款成功", order.getOrderNo());
                            successCount++;
                        } else if (response.getPaymentStatus() != null) {
                            // 根据具体的退款状态处理
                            switch (response.getPaymentStatus()) {
                                case REFUND_FAILED:
                                    // 退款失败
                                    order.setOrderStatus(5); // 退款被拒绝（保持原状态或根据业务需要调整）
                                    shopOrderService.updateById(order);
                                    log.info("订单 {} 退款失败，更新订单状态", order.getOrderNo());
                                    failedCount++;
                                    break;
                                case REFUNDING:
                                    // 仍在退款中，无需处理
                                    log.debug("订单 {} 仍在退款中", order.getOrderNo());
                                    break;
                                default:
                                    log.warn("订单 {} 未知的退款状态: {}", order.getOrderNo(), response.getPaymentStatus());
                                    break;
                            }
                        }
                    } else {
                        log.warn("订单 {} 退款状态查询返回空结果", order.getOrderNo());
                    }
                } catch (PaymentException e) {
                    log.error("查询订单 {} 退款状态时发生支付异常: {}", order.getOrderNo(), e.getMessage(), e);
                    failedCount++;
                } catch (Exception e) {
                    log.error("查询订单 {} 退款状态时发生系统异常: {}", order.getOrderNo(), e.getMessage(), e);
                    failedCount++;
                }
            }

            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            log.info("退款状态查询任务完成，总处理数量: {}，成功: {}，失败: {}，耗时: {}ms",
                    refundProcessingOrders.size(), successCount, failedCount, duration);

        } catch (Exception e) {
            log.error("退款状态查询任务执行失败", e);
        }
    }

    /**
     * 手动触发退款状态查询任务（用于测试）
     */
    @IgnoreTenant("手动触发的定时任务需要处理所有租户的退款订单")
    public void manualQueryRefundStatus() {
        log.info("手动触发退款状态查询任务...");
        queryRefundStatusAndUpdateOrders();
    }
}