package com.jeesharp.business.modules.pay.subsidy.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.paychannelconfig.support.PayChannelTenantSupport;
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.subsidy.dto.PaySubsidyCancelRequestDTO;
import com.jeesharp.business.modules.pay.subsidy.dto.PaySubsidyCreateRequestDTO;
import com.jeesharp.business.modules.pay.subsidy.dto.PaySubsidyResultDTO;
import com.jeesharp.business.modules.pay.subsidy.dto.PaySubsidyReturnRequestDTO;
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-12
 */
@Component
@RequiredArgsConstructor
public class PayWechatSubsidyClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatInterfaceLogRecorder interfaceLogRecorder;

    public PaySubsidyResultDTO createSubsidy(PaySubsidyCreateRequestDTO request) {
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            JSONObject body = new JSONObject();
            body.set("sub_mchid", request.getSubMchId());
            body.set("transaction_id", request.getTransactionId());
            body.set("out_subsidy_no", request.getOutSubsidyNo());
            body.set("amount", request.getAmountFen());
            body.set("description", StrUtil.blankToDefault(request.getDescription(), "平台补差"));
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.SUBSIDY_CREATE,
                    RequestMethod.POST,
                    WxApiType.CREATE_SUBSIDIES.getType(),
                    body.toString(),
                    request.getOutSubsidyNo(),
                    request.getPlatformTenantId(),
                    "请求补差失败",
                    config);
            return toResult(wxResp, body.toString());
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    public PaySubsidyResultDTO querySubsidy(String platformTenantId, String subMchId, String transactionId) {
        try {
            PayWechatConfig config = resolveConfig(platformTenantId);
            String suffix = String.format(WxApiType.QUERY_SUBSIDIES.getType(), subMchId, transactionId);
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.SUBSIDY_QUERY,
                    RequestMethod.GET,
                    suffix,
                    null,
                    transactionId,
                    platformTenantId,
                    "查询补差失败",
                    config);
            return toResult(wxResp, null);
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    public PaySubsidyResultDTO returnSubsidy(PaySubsidyReturnRequestDTO request) {
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            JSONObject body = new JSONObject();
            body.set("sub_mchid", request.getSubMchId());
            body.set("transaction_id", request.getTransactionId());
            body.set("refund_id", request.getRefundId());
            body.set("out_order_no", request.getOutOrderNo());
            body.set("amount", request.getAmountFen());
            body.set("description", StrUtil.blankToDefault(request.getDescription(), "补差回退"));
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.SUBSIDY_RETURN,
                    RequestMethod.POST,
                    WxApiType.RETURN_SUBSIDIES.getType(),
                    body.toString(),
                    request.getOutOrderNo(),
                    request.getPlatformTenantId(),
                    "补差回退失败",
                    config);
            return toResult(wxResp, body.toString());
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    public PaySubsidyResultDTO cancelSubsidy(PaySubsidyCancelRequestDTO request) {
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            JSONObject body = new JSONObject();
            body.set("sub_mchid", request.getSubMchId());
            body.set("transaction_id", request.getTransactionId());
            body.set("description", StrUtil.blankToDefault(request.getDescription(), "取消补差"));
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.SUBSIDY_CANCEL,
                    RequestMethod.POST,
                    WxApiType.CANCEL_SUBSIDIES.getType(),
                    body.toString(),
                    request.getTransactionId(),
                    request.getPlatformTenantId(),
                    "取消补差失败",
                    config);
            return toResult(wxResp, body.toString());
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    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 PaySubsidyResultDTO toResult(JSONObject wxResp, String requestBody) {
        PaySubsidyResultDTO result = new PaySubsidyResultDTO();
        result.setSubsidyId(wxResp.getStr("subsidy_id"));
        result.setStatus(wxResp.getStr("result") != null ? wxResp.getStr("result") : wxResp.getStr("status"));
        result.setSuccess(StrUtil.isNotBlank(result.getSubsidyId()) || StrUtil.isNotBlank(result.getStatus()));
        if (StringUtils.hasText(requestBody)) {
            result.setRawResponse(JSONUtil.createObj().set("request", requestBody).set("response", wxResp).toString());
        } else {
            result.setRawResponse(wxResp.toString());
        }
        return result;
    }

    private static PaySubsidyResultDTO fail(String message) {
        PaySubsidyResultDTO result = new PaySubsidyResultDTO();
        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);
    }
}
