package com.gxwebsoft.common.core.service;

import com.gxwebsoft.common.system.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 环境感知的支付配置服务
 * 根据不同环境自动切换支付回调地址
 *
 * @author WebSoft
 * @since 2025-01-15
 */
@Slf4j
@Service
public class EnvironmentAwarePaymentService {

    @Autowired
    private PaymentCacheService paymentCacheService;

    @Value("${spring.profiles.active:dev}")
    private String activeProfile;

    @Value("${config.server-url:}")
    private String serverUrl;

    // 开发环境回调地址配置
    @Value("${payment.dev.notify-url:http://frps-10550.s209.websoft.top/api/shop/shop-order/notify}")
    private String devNotifyUrl;

    // 生产环境回调地址配置
    @Value("${payment.prod.notify-url:https://cms-api.websoft.top/api/shop/shop-order/notify}")
    private String prodNotifyUrl;

    /**
     * 获取环境感知的支付配置
     * 根据当前环境自动调整回调地址
     *
     * @param payType 支付类型
     * @param tenantId 租户ID
     * @return 支付配置
     */
    public Payment getEnvironmentAwarePaymentConfig(Integer payType, Integer tenantId) {
        // 获取原始支付配置
        Payment payment = paymentCacheService.getPaymentConfig(payType, tenantId);
        
        if (payment == null) {
            return null;
        }

        // 开发/测试环境允许强制覆盖，方便本地联调。
        if (isDevelopmentEnvironment()) {
            Payment envPayment = clonePayment(payment);
            String notifyUrl = getEnvironmentNotifyUrl();
            log.info("环境感知支付配置(开发/测试) - 环境: {}, 原始回调: {}, 覆盖后回调: {}",
                activeProfile, payment.getNotifyUrl(), notifyUrl);
            envPayment.setNotifyUrl(notifyUrl);
            return envPayment;
        }

        // 生产/其它环境：优先使用数据库中的 notifyUrl（多租户域名可能不同）。
        if (payment.getNotifyUrl() != null && !payment.getNotifyUrl().trim().isEmpty()) {
            return payment;
        }

        // 数据库未配置时才兜底使用环境配置。
        Payment envPayment = clonePayment(payment);
        String notifyUrl = getEnvironmentNotifyUrl();
        log.info("环境感知支付配置(兜底) - 环境: {}, 原始回调为空，兜底回调: {}", activeProfile, notifyUrl);
        envPayment.setNotifyUrl(notifyUrl);
        return envPayment;
    }

    /**
     * 根据当前环境获取回调地址
     */
    private String getEnvironmentNotifyUrl() {
        if ("dev".equals(activeProfile) || "test".equals(activeProfile)) {
            // 开发/测试环境使用本地回调地址
            return devNotifyUrl;
        } else if ("prod".equals(activeProfile)) {
            // 生产环境使用生产回调地址
            return prodNotifyUrl;
        } else {
            // 默认使用配置的服务器地址
            return serverUrl + "/shop/shop-order/notify";
        }
    }

    /**
     * 克隆支付配置对象
     */
    private Payment clonePayment(Payment original) {
        Payment cloned = new Payment();
        cloned.setId(original.getId());
        cloned.setName(original.getName());
        cloned.setType(original.getType());
        cloned.setCode(original.getCode());
        cloned.setImage(original.getImage());
        cloned.setWechatType(original.getWechatType());
        cloned.setAppId(original.getAppId());
        cloned.setMchId(original.getMchId());
        cloned.setApiKey(original.getApiKey());
        cloned.setApiclientCert(original.getApiclientCert());
        cloned.setApiclientKey(original.getApiclientKey());
        cloned.setPubKey(original.getPubKey());
        cloned.setPubKeyId(original.getPubKeyId());
        cloned.setMerchantSerialNumber(original.getMerchantSerialNumber());
        cloned.setNotifyUrl(original.getNotifyUrl()); // 这个会被后续覆盖
        cloned.setComments(original.getComments());
        cloned.setSortNumber(original.getSortNumber());
        cloned.setStatus(original.getStatus());
        cloned.setDeleted(original.getDeleted());
        cloned.setTenantId(original.getTenantId());
        return cloned;
    }

    /**
     * 获取微信支付配置（环境感知）
     */
    public Payment getWechatPayConfig(Integer tenantId) {
        return getEnvironmentAwarePaymentConfig(0, tenantId);
    }

    /**
     * 获取支付宝配置（环境感知）
     */
    public Payment getAlipayConfig(Integer tenantId) {
        return getEnvironmentAwarePaymentConfig(1, tenantId);
    }

    /**
     * 检查当前环境
     */
    public String getCurrentEnvironment() {
        return activeProfile;
    }

    /**
     * 是否为开发环境
     */
    public boolean isDevelopmentEnvironment() {
        return "dev".equals(activeProfile) || "test".equals(activeProfile);
    }

    /**
     * 是否为生产环境
     */
    public boolean isProductionEnvironment() {
        return "prod".equals(activeProfile);
    }
}
