package com.gxwebsoft.common.core.controller;

import com.gxwebsoft.common.core.service.EnvironmentAwarePaymentService;
import com.gxwebsoft.common.core.service.PaymentCacheService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.Payment;
import com.gxwebsoft.common.system.service.PaymentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 开发环境管理控制器
 * 仅在开发环境启用，用于管理开发调试配置
 *
 * @author WebSoft
 * @since 2025-01-15
 */
@Slf4j
@Tag(name = "开发环境管理")
@RestController
@RequestMapping("/api/dev")
// @ConditionalOnProperty(name = "spring.profiles.active", havingValue = "dev")
public class DevEnvironmentController extends BaseController {

    @Autowired
    private EnvironmentAwarePaymentService environmentAwarePaymentService;

    @Autowired
    private PaymentCacheService paymentCacheService;

    @Autowired
    private PaymentService paymentService;

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

    @Operation(summary = "获取当前环境信息")
    @GetMapping("/environment/info")
    public ApiResult<Map<String, Object>> getEnvironmentInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("activeProfile", activeProfile);
        info.put("isDevelopment", environmentAwarePaymentService.isDevelopmentEnvironment());
        info.put("isProduction", environmentAwarePaymentService.isProductionEnvironment());
        info.put("currentEnvironment", environmentAwarePaymentService.getCurrentEnvironment());

        return success("获取成功", info);
    }

    @Operation(summary = "获取环境感知的支付配置")
    @GetMapping("/payment/config/{payType}")
    public ApiResult<Map<String, Object>> getPaymentConfig(@PathVariable Integer payType) {
        try {
            Integer tenantId = getTenantId();

            // 获取原始配置
            Payment originalConfig = paymentCacheService.getPaymentConfig(payType, tenantId);

            // 获取环境感知配置
            Payment envConfig = environmentAwarePaymentService.getEnvironmentAwarePaymentConfig(payType, tenantId);

            Map<String, Object> result = new HashMap<>();
            result.put("tenantId", tenantId);
            result.put("payType", payType);
            result.put("environment", activeProfile);
            result.put("originalConfig", originalConfig);
            result.put("environmentAwareConfig", envConfig);

            if (originalConfig != null && envConfig != null) {
                result.put("notifyUrlChanged", !originalConfig.getNotifyUrl().equals(envConfig.getNotifyUrl()));
                result.put("originalNotifyUrl", originalConfig.getNotifyUrl());
                result.put("environmentNotifyUrl", envConfig.getNotifyUrl());
            }

            return success("获取成功", result);

        } catch (Exception e) {
            log.error("获取支付配置失败", e);
            return fail("获取失败: " + e.getMessage(),null);
        }
    }

    @Operation(summary = "切换开发环境回调地址")
    @PostMapping("/payment/switch-notify-url")
    public ApiResult<?> switchNotifyUrl(@RequestBody Map<String, String> request) {
        try {
            String newNotifyUrl = request.get("notifyUrl");
            Integer payType = Integer.valueOf(request.getOrDefault("payType", "0"));

            if (newNotifyUrl == null || newNotifyUrl.trim().isEmpty()) {
                return fail("回调地址不能为空");
            }

            Integer tenantId = getTenantId();

            // 获取当前配置
            Payment payment = paymentCacheService.getPaymentConfig(payType, tenantId);
            if (payment == null) {
                return fail("未找到支付配置");
            }

            // 更新回调地址
            payment.setNotifyUrl(newNotifyUrl);

            // 更新数据库
            boolean updated = paymentService.updateById(payment);

            if (updated) {
                // 清除缓存，强制重新加载
                paymentCacheService.removePaymentConfig(payType.toString(), tenantId);

                log.info("开发环境回调地址已更新: {} -> {}", payment.getNotifyUrl(), newNotifyUrl);

                Map<String, Object> result = new HashMap<>();
                result.put("oldNotifyUrl", payment.getNotifyUrl());
                result.put("newNotifyUrl", newNotifyUrl);
                result.put("payType", payType);
                result.put("tenantId", tenantId);

                return success("回调地址更新成功", result);
            } else {
                return fail("更新失败");
            }

        } catch (Exception e) {
            log.error("切换回调地址失败", e);
            return fail("切换失败: " + e.getMessage());
        }
    }

    @Operation(summary = "重置为生产环境回调地址")
    @PostMapping("/payment/reset-to-prod")
    public ApiResult<?> resetToProdNotifyUrl(@RequestParam(defaultValue = "0") Integer payType) {
        try {
            Integer tenantId = getTenantId();

            // 获取当前配置
            Payment payment = paymentCacheService.getPaymentConfig(payType, tenantId);
            if (payment == null) {
                return fail("未找到支付配置");
            }

            // 设置为生产环境回调地址
            String prodNotifyUrl = "https://cms-api.websoft.top/api/shop/shop-order/notify";
            String oldNotifyUrl = payment.getNotifyUrl();

            payment.setNotifyUrl(prodNotifyUrl);

            // 更新数据库
            boolean updated = paymentService.updateById(payment);

            if (updated) {
                // 清除缓存
                paymentCacheService.removePaymentConfig(payType.toString(), tenantId);

                log.info("回调地址已重置为生产环境: {} -> {}", oldNotifyUrl, prodNotifyUrl);

                Map<String, Object> result = new HashMap<>();
                result.put("oldNotifyUrl", oldNotifyUrl);
                result.put("newNotifyUrl", prodNotifyUrl);
                result.put("payType", payType);
                result.put("tenantId", tenantId);

                return success("已重置为生产环境回调地址", result);
            } else {
                return fail("重置失败");
            }

        } catch (Exception e) {
            log.error("重置回调地址失败", e);
            return fail("重置失败: " + e.getMessage());
        }
    }

    @Operation(summary = "清除支付配置缓存")
    @PostMapping("/payment/clear-cache")
    public ApiResult<?> clearPaymentCache(@RequestParam(defaultValue = "0") Integer payType) {
        try {
            Integer tenantId = getTenantId();

            paymentCacheService.removePaymentConfig(payType.toString(), tenantId);

            log.info("支付配置缓存已清除: payType={}, tenantId={}", payType, tenantId);

            return success("缓存清除成功");

        } catch (Exception e) {
            log.error("清除缓存失败", e);
            return fail("清除失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取开发环境使用指南")
    @GetMapping("/guide")
    public ApiResult<Map<String, Object>> getDevGuide() {
        Map<String, Object> guide = new HashMap<>();

        guide.put("title", "开发环境支付调试指南");
        guide.put("environment", activeProfile);

        Map<String, String> steps = new HashMap<>();
        steps.put("step1", "使用 /api/dev/payment/switch-notify-url 切换到本地回调地址");
        steps.put("step2", "进行支付功能调试和测试");
        steps.put("step3", "调试完成后使用 /api/dev/payment/reset-to-prod 恢复生产环境配置");
        steps.put("step4", "或者直接在后台管理界面修改回调地址");

        guide.put("steps", steps);

        Map<String, String> apis = new HashMap<>();
        apis.put("环境信息", "GET /api/dev/environment/info");
        apis.put("查看配置", "GET /api/dev/payment/config/{payType}");
        apis.put("切换回调", "POST /api/dev/payment/switch-notify-url");
        apis.put("重置生产", "POST /api/dev/payment/reset-to-prod");
        apis.put("清除缓存", "POST /api/dev/payment/clear-cache");

        guide.put("apis", apis);

        Map<String, String> tips = new HashMap<>();
        tips.put("tip1", "此控制器仅在开发环境启用");
        tips.put("tip2", "生产环境不会加载这些接口");
        tips.put("tip3", "建议使用环境感知服务自动切换");
        tips.put("tip4", "记得在调试完成后恢复生产配置");

        guide.put("tips", tips);

        return success("获取成功", guide);
    }
}
