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

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
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.PayProfitSharingFinishRequestDTO;
import com.jeesharp.business.modules.pay.profitsharing.dto.PayProfitSharingRequestDTO;
import com.jeesharp.business.modules.pay.profitsharing.dto.PayProfitSharingResultDTO;
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 PayWechatProfitSharingClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatProfitSharingReceiverClient payWechatProfitSharingReceiverClient;

    public PayProfitSharingResultDTO requestOrders(PayProfitSharingRequestDTO request) {
        PayProfitSharingResultDTO result = new PayProfitSharingResultDTO();
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            var ensureResult = payWechatProfitSharingReceiverClient.ensureSubMerchantSelfReceiver(
                    request.getPlatformTenantId(), request.getSubMchId());
            if (!Boolean.TRUE.equals(ensureResult.getSuccess())) {
                result.setSuccess(false);
                result.setErrorMsg("注册分账接收方失败：" + ensureResult.getErrorMsg());
                return result;
            }
            JSONObject body = buildRequestBody(config, request);
            IJPayHttpResponse response = v3Post(config, WxApiType.PROFIT_SHARING_ORDERS.getType(), body.toString());
            return toResult(parseResponse(response, "请求分账失败"), body.toString());
        } catch (Exception ex) {
            result.setSuccess(false);
            result.setErrorMsg(ex.getMessage());
            return result;
        }
    }

    public PayProfitSharingResultDTO finishOrder(PayProfitSharingFinishRequestDTO request) {
        PayProfitSharingResultDTO result = new PayProfitSharingResultDTO();
        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_order_no", request.getOutOrderNo());
            body.set("description", StrUtil.blankToDefault(request.getDescription(), "分账完结"));
            IJPayHttpResponse response = v3Post(config, WxApiType.PROFIT_SHARING_FINISH_ORDER.getType(), body.toString());
            return toResult(parseResponse(response, "完结分账失败"), body.toString());
        } catch (Exception ex) {
            result.setSuccess(false);
            result.setErrorMsg(ex.getMessage());
            return result;
        }
    }

    public PayProfitSharingResultDTO queryOrders(String platformTenantId, String subMchId,
            String transactionId, String outOrderNo) {
        PayProfitSharingResultDTO result = new PayProfitSharingResultDTO();
        try {
            PayWechatConfig config = resolveConfig(platformTenantId);
            String suffix = UriComponentsBuilder.fromPath(WxApiType.PROFIT_SHARING_ORDERS.getType())
                    .queryParam("sub_mchid", subMchId)
                    .queryParam("transaction_id", transactionId)
                    .queryParam("out_order_no", outOrderNo)
                    .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 buildRequestBody(PayWechatConfig config, PayProfitSharingRequestDTO request) {
        JSONObject body = new JSONObject();
        body.set("appid", config.getAppId());
        body.set("sub_mchid", request.getSubMchId());
        body.set("transaction_id", request.getTransactionId());
        body.set("out_order_no", request.getOutOrderNo());
        JSONObject receiver = new JSONObject();
        receiver.set("type", "MERCHANT_ID");
        receiver.set("receiver_account", request.getSubMchId());
        receiver.set("amount", request.getAmountFen());
        receiver.set("description", StrUtil.blankToDefault(request.getDescription(), "商户货款"));
        JSONArray receivers = new JSONArray();
        receivers.add(receiver);
        body.set("receivers", receivers);
        body.set("finish", false);
        return body;
    }

    private static PayProfitSharingResultDTO toResult(JSONObject wxResp, String requestBody) {
        PayProfitSharingResultDTO result = new PayProfitSharingResultDTO();
        result.setRawResponse(wxResp.toString());
        if (StringUtils.hasText(requestBody)) {
            result.setRawResponse(JSONUtil.createObj()
                    .set("request", requestBody)
                    .set("response", wxResp)
                    .toString());
        }
        result.setWxOrderId(wxResp.getStr("order_id"));
        result.setState(wxResp.getStr("state"));
        result.setSuccess(StrUtil.isNotBlank(result.getWxOrderId()));
        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);
    }
}
