package com.jeesharp.business.modules.pay.profitsharing.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.paywechatconfig.entity.PayWechatConfig;
import com.jeesharp.business.modules.pay.profitsharing.dto.PayProfitSharingReturnRequestDTO;
import com.jeesharp.business.modules.pay.profitsharing.dto.PayProfitSharingReturnResultDTO;
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 lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 微信电商收付通分账回退 V3 客户端。
 *
 * @author jeesharp
 * @since 2026-06-11
 */
@Component
@RequiredArgsConstructor
public class PayWechatProfitSharingReturnClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;

    public PayProfitSharingReturnResultDTO applyReturn(PayProfitSharingReturnRequestDTO request) {
        PayProfitSharingReturnResultDTO result = new PayProfitSharingReturnResultDTO();
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            JSONObject body = buildApplyBody(request);
            IJPayHttpResponse response = v3Post(config, WxApiType.PROFIT_SHARING_RETURN_ORDERS.getType(), body.toString());
            return toResult(parseResponse(response, "请求分账回退失败"), body.toString());
        } catch (Exception ex) {
            result.setSuccess(false);
            result.setErrorMsg(ex.getMessage());
            return result;
        }
    }

    public PayProfitSharingReturnResultDTO queryByOutReturnNo(String platformTenantId, String subMchId, String outReturnNo) {
        PayProfitSharingReturnResultDTO result = new PayProfitSharingReturnResultDTO();
        try {
            PayWechatConfig config = resolveConfig(platformTenantId);
            String suffix = UriComponentsBuilder.fromPath(WxApiType.PROFIT_SHARING_RETURN_ORDERS.getType())
                    .queryParam("sub_mchid", subMchId)
                    .queryParam("out_return_no", outReturnNo)
                    .build()
                    .toUriString();
            IJPayHttpResponse response = v3Get(config, suffix);
            return toResult(parseResponse(response, "查询分账回退失败"), null);
        } catch (Exception ex) {
            result.setSuccess(false);
            result.setErrorMsg(ex.getMessage());
            return result;
        }
    }

    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 static JSONObject buildApplyBody(PayProfitSharingReturnRequestDTO request) {
        JSONObject body = new JSONObject();
        body.set("sub_mchid", request.getSubMchId());
        if (StrUtil.isNotBlank(request.getWxOrderId())) {
            body.set("order_id", request.getWxOrderId());
        }
        if (StrUtil.isNotBlank(request.getOutOrderNo())) {
            body.set("out_order_no", request.getOutOrderNo());
        }
        body.set("out_return_no", request.getOutReturnNo());
        body.set("return_mchid", request.getReturnMchId());
        body.set("amount", request.getAmountFen());
        body.set("description", StrUtil.blankToDefault(request.getDescription(), "订单退款分账回退"));
        if (StrUtil.isNotBlank(request.getTransactionId())) {
            body.set("transaction_id", request.getTransactionId());
        }
        return body;
    }

    private static PayProfitSharingReturnResultDTO toResult(JSONObject wxResp, String requestBody) {
        PayProfitSharingReturnResultDTO result = new PayProfitSharingReturnResultDTO();
        result.setRawResponse(wxResp.toString());
        if (StringUtils.hasText(requestBody)) {
            result.setRawResponse(JSONUtil.createObj()
                    .set("request", requestBody)
                    .set("response", wxResp)
                    .toString());
        }
        result.setWxReturnNo(wxResp.getStr("return_no"));
        result.setResult(wxResp.getStr("result"));
        result.setFailReason(wxResp.getStr("fail_reason"));
        result.setSuccess(StrUtil.isNotBlank(result.getWxReturnNo()) || StrUtil.isNotBlank(result.getResult()));
        return result;
    }

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