package com.gxwebsoft.common.core.controller;

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 com.gxwebsoft.common.core.service.PaymentCacheService;
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 支付配置管理控制器
 * 用于检查和管理支付配置
 *
 * @author 科技小王子
 * @since 2025-07-27
 */
@Slf4j
@Tag(name = "支付配置管理")
@RestController
@RequestMapping("/api/system/payment-config")
public class PaymentConfigController extends BaseController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private PaymentCacheService paymentCacheService;

    @Operation(summary = "检查支付配置")
    @GetMapping("/check/{payType}")
    @PreAuthorize("hasAuthority('sys:payment:list')")
    public ApiResult<Map<String, Object>> checkPaymentConfig(@PathVariable Integer payType) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取支付配置
            Payment payment = paymentCacheService.getPaymentConfig(payType, getTenantId());
            
            if (payment == null) {
                result.put("status", "error");
                result.put("message", "未找到支付配置");
                return success("检查完成", result);
            }
            
            // 检查配置完整性
            Map<String, Object> configCheck = new HashMap<>();
            configCheck.put("id", payment.getId());
            configCheck.put("name", payment.getName());
            configCheck.put("type", payment.getType());
            configCheck.put("code", payment.getCode());
            configCheck.put("appId", payment.getAppId());
            configCheck.put("mchId", payment.getMchId());
            configCheck.put("apiKeyConfigured", payment.getApiKey() != null && !payment.getApiKey().trim().isEmpty());
            configCheck.put("apiKeyLength", payment.getApiKey() != null ? payment.getApiKey().length() : 0);
            configCheck.put("merchantSerialNumber", payment.getMerchantSerialNumber());
            configCheck.put("status", payment.getStatus());
            configCheck.put("tenantId", payment.getTenantId());
            
            // 检查必要字段
            boolean isValid = true;
            StringBuilder errors = new StringBuilder();
            
            if (payment.getMchId() == null || payment.getMchId().trim().isEmpty()) {
                isValid = false;
                errors.append("商户号(mchId)未配置; ");
            }
            
            if (payment.getApiKey() == null || payment.getApiKey().trim().isEmpty()) {
                isValid = false;
                errors.append("API密钥(apiKey)未配置; ");
            }
            
            if (payment.getMerchantSerialNumber() == null || payment.getMerchantSerialNumber().trim().isEmpty()) {
                isValid = false;
                errors.append("商户证书序列号(merchantSerialNumber)未配置; ");
            }
            
            if (payment.getAppId() == null || payment.getAppId().trim().isEmpty()) {
                isValid = false;
                errors.append("应用ID(appId)未配置; ");
            }
            
            result.put("status", isValid ? "success" : "error");
            result.put("valid", isValid);
            result.put("errors", errors.toString());
            result.put("config", configCheck);
            
            return success("检查完成", result);
            
        } catch (Exception e) {
            log.error("检查支付配置失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("status", "error");
            result.put("message", "检查失败: " + e.getMessage());
            return success("检查完成", result);
        }
    }

    @Operation(summary = "初始化微信支付配置")
    @PostMapping("/init-wechat")
    @PreAuthorize("hasAuthority('sys:payment:save')")
    public ApiResult<?> initWechatPayConfig(@RequestBody Map<String, String> config) {
        try {
            Payment payment = new Payment();
            payment.setName("微信支付");
            payment.setType(0); // 微信支付类型为0
            payment.setCode("0");
            payment.setAppId(config.get("appId"));
            payment.setMchId(config.get("mchId"));
            payment.setApiKey(config.get("apiKey"));
            payment.setMerchantSerialNumber(config.get("merchantSerialNumber"));
            payment.setStatus(true);
            payment.setTenantId(getTenantId());
            
            if (paymentService.save(payment)) {
                // 缓存配置
                paymentCacheService.cachePaymentConfig(payment, getTenantId());
                return success("微信支付配置初始化成功");
            } else {
                return fail("微信支付配置初始化失败");
            }
            
        } catch (Exception e) {
            log.error("初始化微信支付配置失败", e);
            return fail("初始化失败: " + e.getMessage());
        }
    }

    @Operation(summary = "清除支付配置缓存")
    @DeleteMapping("/cache/{payType}")
    @PreAuthorize("hasAuthority('sys:payment:update')")
    public ApiResult<?> clearPaymentCache(@PathVariable Integer payType) {
        try {
            paymentCacheService.removePaymentConfig(payType.toString(), getTenantId());
            return success("缓存清除成功");
        } catch (Exception e) {
            log.error("清除支付配置缓存失败", e);
            return fail("清除缓存失败: " + e.getMessage());
        }
    }
}
