package com.jeesharp.business.modules.pay.partner.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.partner.dto.PayPartnerCloseRequestDTO;
import com.jeesharp.business.modules.pay.partner.dto.PayPartnerJsapiRequestDTO;
import com.jeesharp.business.modules.pay.partner.dto.PayPartnerTransactionResultDTO;
import com.jeesharp.business.modules.pay.paychannelconfig.support.PayChannelTenantSupport;
import com.jeesharp.business.modules.pay.paysubmerchantapplyment.support.PayWechatInterfaceLogRecorder;
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;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 微信 partner JSAPI 下单客户端（/v3/pay/partner/transactions/jsapi）。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class PayWechatPartnerTransactionClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatInterfaceLogRecorder interfaceLogRecorder;

    public PayPartnerTransactionResultDTO jsapiPrepay(PayPartnerJsapiRequestDTO request) {
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            JSONObject body = buildJsapiBody(config, request);
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.PARTNER_TRANSACTIONS_JSAPI,
                    RequestMethod.POST,
                    WxApiType.PARTNER_JS_API_PAY.getType(),
                    body.toString(),
                    request.getOutTradeNo(),
                    request.getPlatformTenantId(),
                    "partner JSAPI 下单失败",
                    config);
            return toJsapiResult(wxResp, body.toString());
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    public PayPartnerTransactionResultDTO queryByOutTradeNo(String platformTenantId, String subMchId, String outTradeNo) {
        try {
            PayWechatConfig config = resolveConfig(platformTenantId);
            String suffix = UriComponentsBuilder.fromPath(
                            String.format(WxApiType.PARTNER_ORDER_QUERY_BY_NO.getType(), outTradeNo))
                    .queryParam("sp_mchid", config.getMchId())
                    .queryParam("sub_mchid", subMchId)
                    .build()
                    .toUriString();
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.PARTNER_TRANSACTIONS_QUERY,
                    RequestMethod.GET,
                    suffix,
                    null,
                    outTradeNo,
                    platformTenantId,
                    "partner 查单失败",
                    config);
            PayPartnerTransactionResultDTO result = new PayPartnerTransactionResultDTO();
            result.setTradeState(wxResp.getStr("trade_state"));
            result.setSuccess(true);
            result.setRawResponse(wxResp.toString());
            return result;
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    public PayPartnerTransactionResultDTO close(PayPartnerCloseRequestDTO request) {
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            JSONObject body = new JSONObject();
            body.set("sp_mchid", config.getMchId());
            body.set("sub_mchid", request.getSubMchId());
            String suffix = String.format(WxApiType.PARTNER_CLOSE_ORDER_BY_NO.getType(), request.getOutTradeNo());
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.PARTNER_TRANSACTIONS_CLOSE,
                    RequestMethod.POST,
                    suffix,
                    body.toString(),
                    request.getOutTradeNo(),
                    request.getPlatformTenantId(),
                    "partner 关单失败",
                    config);
            PayPartnerTransactionResultDTO result = new PayPartnerTransactionResultDTO();
            result.setSuccess(true);
            result.setRawResponse(JSONUtil.createObj().set("request", body).set("response", wxResp).toString());
            return result;
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    private static JSONObject buildJsapiBody(PayWechatConfig config, PayPartnerJsapiRequestDTO request) {
        JSONObject body = new JSONObject();
        body.set("sp_appid", config.getAppId());
        body.set("sp_mchid", config.getMchId());
        body.set("sub_mchid", request.getSubMchId());
        body.set("description", StrUtil.blankToDefault(request.getDescription(), "商品支付"));
        body.set("out_trade_no", request.getOutTradeNo());
        if (StrUtil.isNotBlank(request.getNotifyUrl())) {
            body.set("notify_url", request.getNotifyUrl());
        }
        if (StrUtil.isNotBlank(request.getAttach())) {
            body.set("attach", request.getAttach());
        }
        JSONObject amount = new JSONObject();
        amount.set("total", request.getTotalAmountFen());
        amount.set("currency", "CNY");
        body.set("amount", amount);
        JSONObject payer = new JSONObject();
        payer.set("sp_openid", request.getPayerOpenId());
        body.set("payer", payer);
        if (Boolean.TRUE.equals(request.getProfitSharing())) {
            JSONObject settleInfo = new JSONObject();
            settleInfo.set("profit_sharing", true);
            body.set("settle_info", settleInfo);
        }
        return body;
    }

    private PayWechatConfig resolveConfig(String platformTenantId) {
        String tenantId = StrUtil.blankToDefault(platformTenantId, PayChannelTenantSupport.PLATFORM_TENANT_ID);
        PayWechatConfig config = payWechatWxPayClientHolder.requireActiveConfig(tenantId);
        if (!PayWechatCredentialSupport.isWxEnabled(config)) {
            throw new IllegalStateException("未启用真实微信 V3：请在后台开启「调用真实微信」");
        }
        return config;
    }

    private JSONObject executeLogged(
            String scenarioType,
            RequestMethod method,
            String urlSuffix,
            String requestBody,
            String businessId,
            String tenantId,
            String action,
            PayWechatConfig config) throws Exception {
        String requestUrl = WxDomain.CHINA.getType() + urlSuffix;
        long startMs = System.currentTimeMillis();
        InterfaceLogEntity logEntity = interfaceLogRecorder.begin(
                scenarioType, method.name(), requestUrl, requestBody, businessId,
                "configTenantId=" + StrUtil.blankToDefault(tenantId, ""));
        try {
            IJPayHttpResponse response = method == RequestMethod.GET
                    ? v3Get(config, urlSuffix)
                    : v3Post(config, urlSuffix, StrUtil.blankToDefault(requestBody, ""));
            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 PayPartnerTransactionResultDTO toJsapiResult(JSONObject wxResp, String requestBody) {
        PayPartnerTransactionResultDTO result = new PayPartnerTransactionResultDTO();
        result.setPrepayId(wxResp.getStr("prepay_id"));
        result.setSuccess(StrUtil.isNotBlank(result.getPrepayId()));
        result.setRawResponse(JSONUtil.createObj().set("request", requestBody).set("response", wxResp).toString());
        return result;
    }

    private static PayPartnerTransactionResultDTO fail(String message) {
        PayPartnerTransactionResultDTO result = new PayPartnerTransactionResultDTO();
        result.setSuccess(false);
        result.setErrorMsg(message);
        return result;
    }

    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);
    }
}
