package shop.alien.store.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import shop.alien.entity.result.R;
import shop.alien.store.service.PlatformMembershipPaymentQueryService;
import shop.alien.store.strategy.platformMembershipPayment.PlatformMembershipPaymentStrategy;
import shop.alien.store.strategy.platformMembershipPayment.PlatformMembershipPaymentStrategyFactory;

@Slf4j
@Service
@RequiredArgsConstructor
public class PlatformMembershipPaymentQueryServiceImpl implements PlatformMembershipPaymentQueryService {

    private static final int MAX_ATTEMPTS = 3;
    private static final long RETRY_DELAY_MS = 1500L;

    private static final String[] NON_RETRYABLE_MSGS = {
            "交易已关闭",
            "等待用户付款",
            "等待买家付款",
            "交易不存在",
            "会员卡订单不存在",
            "支付单不存在",
            "该门店未配置支付参数",
            "门店ID和商户订单号不能为空",
            "支付成功"
    };

    private final PlatformMembershipPaymentStrategyFactory factory;

    @Override
    public R<Object> queryPayStatusWithRetry(Integer storeId, String outTradeNo, String payType) {
        PlatformMembershipPaymentStrategy strategy = factory.getStrategy(payType);
        R<Object> last = null;
        for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
            last = strategy.queryPayStatus(storeId, outTradeNo);
            if (last == null) {
                if (attempt < MAX_ATTEMPTS) {
                    sleep(RETRY_DELAY_MS);
                }
                continue;
            }
            if (R.isSuccess(last)) {
                return last;
            }
            String msg = last.getMsg();
            if (msg != null && isNonRetryable(msg)) {
                return last;
            }
            if (attempt < MAX_ATTEMPTS) {
                log.warn("会员卡支付查单可重试失败 attempt={}/{} storeId={} outTradeNo={} msg={}",
                        attempt, MAX_ATTEMPTS, storeId, outTradeNo, msg);
                sleep(RETRY_DELAY_MS);
            }
        }
        if (last != null && !R.isSuccess(last)) {
            String msg = last.getMsg();
            if (msg != null && (msg.contains("查询失败") || msg.contains("查询异常"))) {
                return R.fail("查询失败：网络异常，请稍后重试或到订单列表查看");
            }
        }
        return last != null ? last : R.fail("查询失败：请稍后重试");
    }

    private static boolean isNonRetryable(String msg) {
        for (String s : NON_RETRYABLE_MSGS) {
            if (StringUtils.contains(msg, s)) {
                return true;
            }
        }
        return false;
    }

    private static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("PlatformMembershipPaymentQueryService sleep interrupted");
        }
    }
}
