package com.gxwebsoft.common.core.controller;

import com.gxwebsoft.common.core.utils.WechatCertAutoConfig;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.wechat.pay.java.core.Config;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 微信支付证书自动配置测试控制器
 *
 * @author 科技小王子
 * @since 2024-07-26
 */
@Slf4j
@RestController
@RequestMapping("/api/wechat-cert-test")
@Tag(name = "微信支付证书自动配置测试")
public class WechatCertTestController extends BaseController {

    @Autowired
    private WechatCertAutoConfig wechatCertAutoConfig;

    @Operation(summary = "测试默认开发环境证书配置")
    @PostMapping("/test-default")
    public ApiResult<Map<String, Object>> testDefaultConfig() {
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始测试默认开发环境证书配置...");

            // 创建自动证书配置
            Config config = wechatCertAutoConfig.createDefaultDevConfig();

            // 测试配置
            boolean testResult = wechatCertAutoConfig.testConfig(config);

            result.put("success", true);
            result.put("configCreated", config != null);
            result.put("testPassed", testResult);
            result.put("message", "默认证书配置测试完成");
            result.put("instructions", wechatCertAutoConfig.getUsageInstructions());

            log.info("✅ 默认证书配置测试成功");
            return success("测试成功", result);

        } catch (Exception e) {
            log.error("❌ 默认证书配置测试失败: {}", e.getMessage(), e);

            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("message", "证书配置测试失败");
            result.put("troubleshooting", getTroubleshootingInfo());

            return fail("测试失败: " + e.getMessage(), result);
        }
    }

    @Operation(summary = "测试自定义证书配置")
    @PostMapping("/test-custom")
    public ApiResult<Map<String, Object>> testCustomConfig(
            @Parameter(description = "商户号") @RequestParam String merchantId,
            @Parameter(description = "私钥文件路径") @RequestParam String privateKeyPath,
            @Parameter(description = "证书序列号") @RequestParam String merchantSerialNumber,
            @Parameter(description = "APIv3密钥") @RequestParam String apiV3Key) {

        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始测试自定义证书配置...");
            log.info("商户号: {}", merchantId);
            log.info("私钥路径: {}", privateKeyPath);

            // 创建自动证书配置
            Config config = wechatCertAutoConfig.createAutoConfig(
                merchantId, privateKeyPath, merchantSerialNumber, apiV3Key);

            // 测试配置
            boolean testResult = wechatCertAutoConfig.testConfig(config);

            result.put("success", true);
            result.put("configCreated", config != null);
            result.put("testPassed", testResult);
            result.put("message", "自定义证书配置测试完成");
            result.put("merchantId", merchantId);
            result.put("privateKeyPath", privateKeyPath);

            log.info("✅ 自定义证书配置测试成功");
            return success("测试成功", result);

        } catch (Exception e) {
            log.error("❌ 自定义证书配置测试失败: {}", e.getMessage(), e);

            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("message", "证书配置测试失败");
            result.put("troubleshooting", getTroubleshootingInfo());

            return fail("测试失败: " + e.getMessage(), result);
        }
    }

    @Operation(summary = "获取使用说明")
    @GetMapping("/instructions")
    public ApiResult<String> getInstructions() {
        String instructions = wechatCertAutoConfig.getUsageInstructions();
        return success("获取使用说明成功", instructions);
    }

    @Operation(summary = "获取故障排除信息")
    @GetMapping("/troubleshooting")
    public ApiResult<Map<String, Object>> getTroubleshooting() {
        Map<String, Object> troubleshooting = getTroubleshootingInfo();
        return success("获取故障排除信息成功", troubleshooting);
    }

    /**
     * 获取故障排除信息
     */
    private Map<String, Object> getTroubleshootingInfo() {
        Map<String, Object> info = new HashMap<>();

        info.put("commonIssues", Map.of(
            "404错误", "商户平台未开启API安全功能或未申请使用微信支付公钥",
            "证书序列号错误", "请检查商户平台中的证书序列号是否正确",
            "APIv3密钥错误", "请确认APIv3密钥是否正确设置",
            "私钥文件不存在", "请检查私钥文件路径是否正确",
            "网络连接问题", "请检查网络连接是否正常"
        ));

        info.put("solutions", Map.of(
            "开启API安全", "登录微信商户平台 -> 账户中心 -> API安全 -> 申请使用微信支付公钥",
            "获取证书序列号", "在API安全页面查看或重新下载证书",
            "设置APIv3密钥", "在API安全页面设置APIv3密钥",
            "检查私钥文件", "确保apiclient_key.pem文件存在且路径正确"
        ));

        info.put("advantages", Map.of(
            "自动下载", "RSAAutoCertificateConfig会自动下载平台证书",
            "自动更新", "证书过期时会自动更新",
            "简化管理", "无需手动管理wechatpay_cert.pem文件",
            "官方推荐", "微信支付官方推荐的证书管理方式"
        ));

        info.put("documentation", "https://pay.weixin.qq.com/doc/v3/merchant/4012153196");

        return info;
    }

    @Operation(summary = "检查商户平台配置状态")
    @PostMapping("/check-merchant-config")
    public ApiResult<Map<String, Object>> checkMerchantConfig(
            @RequestParam String merchantId,
            @RequestParam String privateKeyPath,
            @RequestParam String merchantSerialNumber,
            @RequestParam String apiV3Key) {

        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始检查商户平台配置状态...");
            log.info("商户号: {}", merchantId);

            // 尝试创建自动证书配置
            Config config = wechatCertAutoConfig.createAutoConfig(
                merchantId, privateKeyPath, merchantSerialNumber, apiV3Key);

            result.put("success", true);
            result.put("configCreated", true);
            result.put("message", "商户平台配置正常，自动证书配置创建成功");
            result.put("merchantId", merchantId);
            result.put("recommendation", "配置正常，可以正常使用微信支付功能");

            log.info("✅ 商户平台配置检查成功");
            return success("配置检查成功", result);

        } catch (Exception e) {
            log.error("❌ 商户平台配置检查失败: {}", e.getMessage(), e);

            result.put("success", false);
            result.put("configCreated", false);
            result.put("error", e.getMessage());
            result.put("merchantId", merchantId);

            // 分析错误类型并提供解决方案
            if (e.getMessage().contains("404") || e.getMessage().contains("RESOURCE_NOT_EXISTS")) {
                result.put("errorType", "商户平台配置问题");
                result.put("solution", "请在微信支付商户平台完成以下配置：\n" +
                    "1. 登录商户平台：https://pay.weixin.qq.com/\n" +
                    "2. 进入：产品中心 → 开发配置 → API安全\n" +
                    "3. 申请API证书\n" +
                    "4. 申请使用微信支付公钥\n" +
                    "5. 确保API证书和微信支付公钥状态为\"已生效\"");
                result.put("documentUrl", "https://pay.weixin.qq.com/doc/v3/merchant/4012153196");
            } else {
                result.put("errorType", "其他配置问题");
                result.put("solution", "请检查商户号、证书序列号、API密钥等配置是否正确");
            }

            return success("配置检查完成（发现问题）", result);
        }
    }
}
