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

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jeesharp.business.modules.pay.core.IJPayHttpResponse;
import com.jeesharp.business.modules.pay.core.enums.RequestMethod;
import com.jeesharp.business.modules.pay.payfundbalance.support.PayWechatFundClient;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.support.PayWechatInterfaceLogRecorder;
import com.jeesharp.business.modules.pay.weixin.support.PayWechatInterfaceLogScenario;
import com.jeesharp.business.modules.pay.paywechatconfig.entity.PayWechatConfig;
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.business.modules.pay.config.weixin.PayWechatCredentialSupport;
import com.jeesharp.framework.log.api.entity.InterfaceLogEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 微信支付 V3 预约提现客户端（平台服务商 / 电商收付通特约商户）。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class PayWechatFundWithdrawClient {

    private final PayWechatFundClient payWechatFundClient;
    private final PayWechatInterfaceLogRecorder interfaceLogRecorder;

    public JSONObject submitPlatformWithdraw(String requestJson, String configTenantId) throws Exception {
        PayWechatConfig config = payWechatFundClient.requireConfig(configTenantId);
        String suffix = WxApiType.MERCHANT_FUND_WITHDRAW.getType();
        return executeLogged(
                PayWechatInterfaceLogScenario.FUND_WITHDRAW_PLATFORM_SUBMIT,
                RequestMethod.POST.name(),
                suffix,
                requestJson,
                extractOutRequestNo(requestJson),
                configTenantId,
                "平台预约提现失败",
                () -> v3Post(config, suffix, requestJson));
    }

    public JSONObject queryPlatformWithdrawByOutNo(String outRequestNo, String configTenantId) throws Exception {
        PayWechatConfig config = payWechatFundClient.requireConfig(configTenantId);
        String suffix = String.format(WxApiType.MERCHANT_FUND_QUERY_WITHDRAW_BY_OUT_NO.getType(), outRequestNo);
        return executeLogged(
                PayWechatInterfaceLogScenario.FUND_WITHDRAW_PLATFORM_QUERY,
                RequestMethod.GET.name(),
                suffix,
                null,
                outRequestNo,
                configTenantId,
                "查询平台预约提现状态失败",
                () -> v3Get(config, suffix));
    }

    public JSONObject submitSubMerchantWithdraw(String requestJson, String configTenantId) throws Exception {
        PayWechatConfig config = payWechatFundClient.requireConfig(configTenantId);
        String suffix = WxApiType.WITHDRAW.getType();
        return executeLogged(
                PayWechatInterfaceLogScenario.FUND_WITHDRAW_MERCHANT_SUBMIT,
                RequestMethod.POST.name(),
                suffix,
                requestJson,
                extractOutRequestNo(requestJson),
                configTenantId,
                "特约商户预约提现失败",
                () -> v3Post(config, suffix, requestJson));
    }

    public JSONObject querySubMerchantWithdrawByOutNo(String subMchId, String outRequestNo, String configTenantId) throws Exception {
        PayWechatConfig config = payWechatFundClient.requireConfig(configTenantId);
        String suffix = UriComponentsBuilder
                .fromPath(String.format(WxApiType.ECOMMERCE_QUERY_WITHDRAW_BY_OUT_NO.getType(), outRequestNo))
                .queryParam("sub_mchid", subMchId)
                .build()
                .toUriString();
        return executeLogged(
                PayWechatInterfaceLogScenario.FUND_WITHDRAW_MERCHANT_QUERY,
                RequestMethod.GET.name(),
                suffix,
                null,
                outRequestNo,
                configTenantId,
                "查询特约商户预约提现状态失败",
                () -> v3Get(config, suffix));
    }

    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,
                "configTenantId=" + 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 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 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 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;
    }
}
