package com.gxwebsoft.common.core.controller;

import com.gxwebsoft.common.core.service.PaymentCacheService;
import com.gxwebsoft.common.system.entity.Payment;
import com.gxwebsoft.common.system.service.PaymentService;
import com.gxwebsoft.common.system.param.PaymentParam;
import com.gxwebsoft.common.core.web.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试控制器
 * 用于测试LocalDateTime序列化
 *
 * @author WebSoft
 * @since 2025-01-12
 */
@Tag(name = "测试接口")
@RestController
@RequestMapping("/api/test")
public class TestController extends BaseController {

    @Autowired
    private PaymentCacheService paymentCacheService;

    @Autowired
    private PaymentService paymentService;

    @Operation(summary = "测试LocalDateTime序列化")
    @GetMapping("/datetime")
    public ApiResult<Map<String, Object>> testDateTime() {
        Map<String, Object> result = new HashMap<>();
        // 使用字符串格式避免序列化问题
        result.put("currentTime", LocalDateTime.now().toString());
        result.put("currentTimeFormatted", LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        result.put("message", "LocalDateTime序列化测试");
        result.put("timestamp", System.currentTimeMillis());
        return success(result);
    }

    @Operation(summary = "基础诊断 - 不依赖支付服务")
    @GetMapping("/basic-debug/{tenantId}")
    public ApiResult<String> basicDebug(@PathVariable Integer tenantId) {
        try {
            System.out.println("=== 基础诊断开始 ===");
            System.out.println("接收到的租户ID: " + tenantId);

            if (tenantId == null) {
                return fail("租户ID为null",null);
            }

            return success("基础诊断通过，租户ID: " + tenantId,null);

        } catch (Exception e) {
            System.err.println("基础诊断异常: " + e.getMessage());
            e.printStackTrace();
            return fail("基础诊断异常: " + e.getMessage(),null);
        }
    }

    @Operation(summary = "快速诊断支付配置")
    @GetMapping("/payment-debug/{tenantId}")
    public ApiResult<String> debugPaymentConfig(@PathVariable Integer tenantId) {
        try {
            System.out.println("=== 开始诊断租户 " + tenantId + " 的支付配置 ===");

            // 检查基础参数
            if (tenantId == null) {
                return fail("租户ID为null",null);
            }

            // 检查服务是否可用
            if (paymentCacheService == null) {
                return fail("PaymentCacheService未注入",null);
            }

            System.out.println("准备调用 paymentCacheService.getWechatPayConfig(" + tenantId + ")");

            // 获取支付配置
            Payment payment = null;
            try {
                payment = paymentCacheService.getWechatPayConfig(tenantId);
                System.out.println("成功调用 getWechatPayConfig，结果: " + (payment != null ? "非null" : "null"));
            } catch (Exception e) {
                System.err.println("调用 getWechatPayConfig 异常: " + e.getMessage());
                e.printStackTrace();
                return fail("获取支付配置异常: " + e.getMessage() + " (类型: " + e.getClass().getName() + ")",null);
            }

            if (payment == null) {
                System.out.println("❌ 支付配置不存在");
                return fail("支付配置不存在，租户ID: " + tenantId,null);
            }

            // 构建诊断信息字符串，避免序列化问题
            StringBuilder diagnosis = new StringBuilder();
            diagnosis.append("=== 支付配置诊断结果 ===\n");
            diagnosis.append("租户ID: ").append(tenantId).append("\n");
            diagnosis.append("商户号: ").append(payment.getMchId()).append("\n");
            diagnosis.append("应用ID: ").append(payment.getAppId()).append("\n");
            diagnosis.append("证书序列号: ").append(payment.getMerchantSerialNumber()).append("\n");
            diagnosis.append("API密钥: ").append(payment.getApiKey() != null ? "已配置(长度:" + payment.getApiKey().length() + ")" : "未配置").append("\n");
            diagnosis.append("状态: ").append(payment.getStatus()).append("\n");
            diagnosis.append("私钥文件: ").append(payment.getApiclientKey()).append("\n");
            diagnosis.append("证书文件: ").append(payment.getApiclientCert()).append("\n");
            diagnosis.append("公钥文件: ").append(payment.getPubKey()).append("\n");
            diagnosis.append("公钥ID: ").append(payment.getPubKeyId()).append("\n");

            // 检查问题
            StringBuilder issues = new StringBuilder();
            if (payment.getMchId() == null || payment.getMchId().trim().isEmpty()) {
                issues.append("❌ 商户号为空\n");
            }
            if (payment.getAppId() == null || payment.getAppId().trim().isEmpty()) {
                issues.append("❌ 应用ID为空\n");
            }
            if (payment.getMerchantSerialNumber() == null || payment.getMerchantSerialNumber().trim().isEmpty()) {
                issues.append("❌ 证书序列号为空\n");
            }
            if (payment.getApiKey() == null || payment.getApiKey().trim().isEmpty()) {
                issues.append("❌ API密钥为空\n");
            } else if (payment.getApiKey().length() != 32) {
                issues.append("❌ API密钥长度错误(").append(payment.getApiKey().length()).append("位)\n");
            }
            if (payment.getStatus() == null || !payment.getStatus()) {
                issues.append("❌ 支付配置未启用\n");
            }

            if (issues.length() > 0) {
                diagnosis.append("\n=== 发现的问题 ===\n");
                diagnosis.append(issues.toString());
            } else {
                diagnosis.append("\n✅ 配置检查通过，无问题发现");
            }

            // 打印到控制台
            System.out.println(diagnosis.toString());

            if (issues.length() > 0) {
                return fail(diagnosis.toString(),null);
            } else {
                return success(diagnosis.toString(),null);
            }

        } catch (Exception e) {
            String errorMsg = "诊断失败: " + e.getMessage() + " (类型: " + e.getClass().getName() + ")";
            System.err.println(errorMsg);
            e.printStackTrace();
            return fail(errorMsg,null);
        }
    }

    @Operation(summary = "直接数据库查询支付配置")
    @GetMapping("/db-payment-check/{tenantId}")
    public ApiResult<String> checkPaymentFromDB(@PathVariable Integer tenantId) {
        try {
            System.out.println("=== 直接数据库查询支付配置 ===");
            System.out.println("租户ID: " + tenantId);

            if (tenantId == null) {
                return fail("租户ID为null",null);
            }

            if (paymentService == null) {
                return fail("PaymentService未注入",null);
            }

            // 直接查询数据库，不使用缓存
            PaymentParam param = new PaymentParam();
            param.setType(0); // 微信支付
            param.setTenantId(tenantId);

            System.out.println("准备查询数据库，参数: type=0, tenantId=" + tenantId);

            java.util.List<Payment> payments = paymentService.listRel(param);

            System.out.println("查询结果数量: " + (payments != null ? payments.size() : "null"));

            if (payments == null || payments.isEmpty()) {
                return fail("数据库中没有找到租户 " + tenantId + " 的微信支付配置",null);
            }

            Payment payment = payments.get(0);

            StringBuilder result = new StringBuilder();
            result.append("=== 数据库查询结果 ===\n");
            result.append("租户ID: ").append(payment.getTenantId()).append("\n");
            result.append("支付方式: ").append(payment.getName()).append("\n");
            result.append("类型: ").append(payment.getType()).append("\n");
            result.append("商户号: ").append(payment.getMchId()).append("\n");
            result.append("应用ID: ").append(payment.getAppId()).append("\n");
            result.append("证书序列号: ").append(payment.getMerchantSerialNumber()).append("\n");
            result.append("API密钥状态: ").append(payment.getApiKey() != null ? "已配置(长度:" + payment.getApiKey().length() + ")" : "未配置").append("\n");
            result.append("状态: ").append(payment.getStatus()).append("\n");
            result.append("是否删除: ").append(payment.getDeleted()).append("\n");

            System.out.println(result.toString());

            return success(result.toString(),null);

        } catch (Exception e) {
            String errorMsg = "数据库查询异常: " + e.getMessage() + " (类型: " + e.getClass().getName() + ")";
            System.err.println(errorMsg);
            e.printStackTrace();
            return fail(errorMsg,null);
        }
    }

    @Operation(summary = "清理支付配置缓存")
    @GetMapping("/clear-payment-cache/{tenantId}")
    public String clearPaymentCache(@PathVariable Integer tenantId) {
        try {
            System.out.println("=== 清理支付配置缓存 ===");
            System.out.println("租户ID: " + tenantId);

            if (tenantId == null) {
                return "错误: 租户ID为null";
            }

            // 清理可能的缓存键
            paymentCacheService.removePaymentConfig("0", tenantId);  // 微信支付
            paymentCacheService.removePaymentConfig("wechat", tenantId);  // 可能的其他格式

            String result = "✅ 缓存已清理，租户ID: " + tenantId;
            System.out.println(result);
            return result;

        } catch (Exception e) {
            String errorMsg = "❌ 清理缓存异常: " + e.getMessage();
            System.err.println(errorMsg);
            e.printStackTrace();
            return errorMsg;
        }
    }

    @Operation(summary = "最简单的测试接口")
    @GetMapping("/simple-test")
    public String simpleTest() {
        return "✅ 测试接口正常工作，时间: " + System.currentTimeMillis();
    }

    @Operation(summary = "测试支付配置是否存在")
    @GetMapping("/check-payment-exists/{tenantId}")
    public String checkPaymentExists(@PathVariable Integer tenantId) {
        try {
            System.out.println("=== 检查支付配置是否存在 ===");
            System.out.println("租户ID: " + tenantId);

            if (tenantId == null) {
                return "❌ 租户ID为null";
            }

            if (paymentService == null) {
                return "❌ PaymentService未注入";
            }

            // 使用最简单的查询
            PaymentParam param = new PaymentParam();
            param.setType(0);
            param.setTenantId(tenantId);

            java.util.List<Payment> payments = paymentService.listRel(param);

            if (payments == null) {
                return "❌ 查询结果为null";
            }

            if (payments.isEmpty()) {
                return "❌ 没有找到支付配置，租户ID: " + tenantId;
            }

            Payment payment = payments.get(0);
            StringBuilder result = new StringBuilder();
            result.append("✅ 找到支付配置\n");
            result.append("租户ID: ").append(payment.getTenantId()).append("\n");
            result.append("商户号: ").append(payment.getMchId() != null ? payment.getMchId() : "NULL").append("\n");
            result.append("应用ID: ").append(payment.getAppId() != null ? payment.getAppId() : "NULL").append("\n");
            result.append("状态: ").append(payment.getStatus()).append("\n");

            return result.toString();

        } catch (Exception e) {
            String error = "❌ 检查异常: " + e.getMessage();
            System.err.println(error);
            e.printStackTrace();
            return error;
        }
    }
}
