package com.jeesharp.business.modules.pay.paysubmerchantapplyment.support;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jeesharp.business.modules.pay.config.weixin.PayWechatCredentialSupport;
import com.jeesharp.business.modules.pay.config.weixin.PayWechatWxPayClientHolder;
import com.jeesharp.business.modules.pay.core.IJPayHttpResponse;
import com.jeesharp.business.modules.pay.core.enums.RequestMethod;
import com.jeesharp.business.modules.pay.paywechatconfig.entity.PayWechatConfig;
import com.jeesharp.business.modules.pay.weixin.support.PayWechatInterfaceLogScenario;
import com.jeesharp.business.modules.pay.wxpay.WxPayApi;
import com.jeesharp.business.modules.pay.wxpay.enums.WxApiType;
import com.jeesharp.business.modules.pay.wxpay.enums.WxDomain;
import com.jeesharp.framework.log.api.entity.InterfaceLogEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 微信支付电商收付通 · 二级商户注销/注销提现 V3 接口客户端。
 *
 * @author jeesharp
 * @since 2026-06-15
 */
@Component
@RequiredArgsConstructor
public class PayWechatSubMerchantCancelClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatInterfaceLogRecorder interfaceLogRecorder;

    /**
     * 注销资格校验 GET /v3/ecommerce/account/apply-cancel-withdraw/validate-cancel/{sub_mchid}
     */
    public JSONObject validateCancel(String subMchId, String tenantId) throws Exception {
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        ensureWxReady(config);
        String suffix = String.format(WxApiType.CANCEL_WITHDRAW_VALIDATE.getType(), subMchId);
        return executeLogged(
                PayWechatInterfaceLogScenario.CANCEL_VALIDATE,
                RequestMethod.GET.name(),
                suffix,
                null,
                subMchId,
                tenantId,
                "注销资格校验失败",
                () -> v3Get(config, suffix));
    }

    /**
     * 提交注销/注销提现 POST /v3/ecommerce/account/apply-cancel-withdraw
     */
    public JSONObject submitCancelWithdraw(String requestJson, String tenantId) throws Exception {
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        ensureWxReady(config);
        String body = PayWechatApplymentCryptoSupport.encryptCancelWithdrawFields(requestJson, config);
        String suffix = WxApiType.CANCEL_WITHDRAW_SUBMIT.getType();
        String businessId = extractOutRequestNo(requestJson);
        return executeLogged(
                PayWechatInterfaceLogScenario.CANCEL_SUBMIT,
                RequestMethod.POST.name(),
                suffix,
                body,
                businessId,
                tenantId,
                "提交商户注销失败",
                () -> v3Post(config, suffix, body));
    }

    /**
     * 按商户注销申请单号查询状态。
     */
    public JSONObject queryByOutRequestNo(String outRequestNo, String tenantId) throws Exception {
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        ensureWxReady(config);
        String suffix = String.format(WxApiType.CANCEL_WITHDRAW_QUERY_BY_OUT_NO.getType(), outRequestNo);
        return executeLogged(
                PayWechatInterfaceLogScenario.CANCEL_QUERY,
                RequestMethod.GET.name(),
                suffix,
                null,
                outRequestNo,
                tenantId,
                "查询商户注销状态失败",
                () -> v3Get(config, suffix));
    }

    /**
     * 按微信注销申请单号查询状态。
     */
    public JSONObject queryByWxApplymentId(String wxApplymentId, String tenantId) throws Exception {
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        ensureWxReady(config);
        String suffix = String.format(WxApiType.CANCEL_WITHDRAW_QUERY_BY_ID.getType(), wxApplymentId);
        return executeLogged(
                PayWechatInterfaceLogScenario.CANCEL_QUERY,
                RequestMethod.GET.name(),
                suffix,
                null,
                wxApplymentId,
                tenantId,
                "查询商户注销状态失败",
                () -> v3Get(config, suffix));
    }

    /**
     * 平台代商户确认注销 POST /v3/ecommerce/account/apply-cancel-withdraw/confirm
     */
    public JSONObject confirmCancel(String requestJson, String tenantId) throws Exception {
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        ensureWxReady(config);
        String suffix = WxApiType.CANCEL_WITHDRAW_CONFIRM.getType();
        String businessId = extractOutRequestNo(requestJson);
        if (StrUtil.isBlank(businessId)) {
            businessId = extractWxApplymentId(requestJson);
        }
        return executeLogged(
                PayWechatInterfaceLogScenario.CANCEL_CONFIRM,
                RequestMethod.POST.name(),
                suffix,
                requestJson,
                businessId,
                tenantId,
                "代商户确认注销失败",
                () -> v3Post(config, suffix, requestJson));
    }

    private JSONObject executeLogged(
            String scenarioType,
            String httpMethod,
            String urlSuffix,
            String requestParam,
            String businessId,
            String tenantId,
            String action,
            V3Call call) throws Exception {
        String requestUrl = WxDomain.CHINA.getType() + urlSuffix;
        long startMs = System.currentTimeMillis();
        InterfaceLogEntity logEntity = interfaceLogRecorder.begin(
                scenarioType, httpMethod, requestUrl, requestParam, businessId, "applymentTenantId=" + StrUtil.blankToDefault(tenantId, ""));
        try {
            IJPayHttpResponse response = call.execute();
            int status = response != null ? response.getStatus() : 0;
            if (status >= 200 && status < 300) {
                interfaceLogRecorder.completeSuccess(logEntity, response, startMs);
            } else {
                interfaceLogRecorder.completeHttpFail(logEntity, response, startMs, buildHttpErrorMessage(response, action));
            }
            JSONObject result = parseResponse(response, action);
            interfaceLogRecorder.saveAsync(logEntity);
            return result;
        } catch (Exception e) {
            interfaceLogRecorder.completeError(logEntity, startMs, e.getMessage());
            interfaceLogRecorder.saveAsync(logEntity);
            throw e;
        }
    }

    private static String buildHttpErrorMessage(IJPayHttpResponse response, String action) {
        if (response == null) {
            return action + "：无响应";
        }
        String body = response.getBody();
        if (StringUtils.hasText(body) && JSONUtil.isTypeJSON(body)) {
            JSONObject err = JSONUtil.parseObj(body);
            String msg = err.getStr("message", body);
            if (err.containsKey("code")) {
                return err.getStr("code") + ": " + msg;
            }
            return msg;
        }
        return action + "（HTTP " + response.getStatus() + "）";
    }

    private static String extractOutRequestNo(String requestJson) {
        if (!StringUtils.hasText(requestJson) || !JSONUtil.isTypeJSON(requestJson)) {
            return null;
        }
        try {
            return JSONUtil.parseObj(requestJson).getStr("out_request_no");
        } catch (Exception ignored) {
            return null;
        }
    }

    private static String extractWxApplymentId(String requestJson) {
        if (!StringUtils.hasText(requestJson) || !JSONUtil.isTypeJSON(requestJson)) {
            return null;
        }
        try {
            return JSONUtil.parseObj(requestJson).getStr("applyment_id");
        } catch (Exception ignored) {
            return null;
        }
    }

    private static void ensureWxReady(PayWechatConfig config) {
        if (!PayWechatCredentialSupport.isWxEnabled(config)) {
            throw new IllegalStateException("请先在【支付 · 微信配置】中启用「调用真实微信 V3」");
        }
        if (!StringUtils.hasText(config.getPublicKeyId())) {
            throw new IllegalStateException("商户注销需配置微信支付公钥 ID（publicKeyId）");
        }
        if (!StringUtils.hasText(PayWechatCredentialSupport.resolveWechatPayPublicKeyPem(config))) {
            throw new IllegalStateException("商户注销需配置微信支付公钥 PEM 或路径");
        }
        if (!StringUtils.hasText(config.getCertPrivateKeyPath())) {
            throw new IllegalStateException("商户注销需配置商户 API 私钥路径 certPrivateKeyPath");
        }
    }

    private IJPayHttpResponse v3Post(PayWechatConfig config, String urlSuffix, String body) throws Exception {
        return WxPayApi.v3(RequestMethod.POST, WxDomain.CHINA.getType(), urlSuffix,
                config.getMchId(),
                PayWechatCredentialSupport.resolveMerchantSerialNo(config),
                config.getPublicKeyId(),
                config.getCertPrivateKeyPath().trim(),
                body);
    }

    private IJPayHttpResponse v3Get(PayWechatConfig config, String urlSuffix) throws Exception {
        return WxPayApi.v3(RequestMethod.GET, WxDomain.CHINA.getType(), urlSuffix,
                config.getMchId(),
                PayWechatCredentialSupport.resolveMerchantSerialNo(config),
                config.getPublicKeyId(),
                config.getCertPrivateKeyPath().trim(),
                "");
    }

    private static JSONObject parseResponse(IJPayHttpResponse response, String action) {
        if (response == null) {
            throw new IllegalStateException(action + "：无响应");
        }
        int status = response.getStatus();
        String body = response.getBody();
        if (status >= 200 && status < 300) {
            return StringUtils.hasText(body) ? JSONUtil.parseObj(body) : new JSONObject();
        }
        String msg = body;
        if (StringUtils.hasText(body) && JSONUtil.isTypeJSON(body)) {
            JSONObject err = JSONUtil.parseObj(body);
            msg = err.getStr("message", body);
            if (err.containsKey("code")) {
                msg = err.getStr("code") + ": " + msg;
            }
        }
        throw new IllegalStateException(action + "（HTTP " + status + "）：" + msg);
    }

    @FunctionalInterface
    private interface V3Call {
        IJPayHttpResponse execute() throws Exception;
    }
}
