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

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jeesharp.business.modules.pay.bill.dto.PayBillApplyResultDTO;
import com.jeesharp.business.modules.pay.bill.dto.PayBillFundFlowApplyRequestDTO;
import com.jeesharp.business.modules.pay.bill.dto.PayBillTradeApplyRequestDTO;
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.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;

/**
 * 微信支付 V3 账单申请客户端（交易账单 / 资金账单）。
 *
 * @author jeesharp
 * @since 2026-06-12
 */
@Component
@RequiredArgsConstructor
public class PayWechatBillClient {

    private final PayWechatWxPayClientHolder payWechatWxPayClientHolder;
    private final PayWechatInterfaceLogRecorder interfaceLogRecorder;

    public PayBillApplyResultDTO applyTradeBill(PayBillTradeApplyRequestDTO request) {
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            String suffix = UriComponentsBuilder.fromPath(WxApiType.TRADE_BILL.getType())
                    .queryParam("bill_date", request.getBillDate())
                    .queryParam("bill_type", StrUtil.blankToDefault(request.getBillType(), "ALL"))
                    .queryParam("tar_type", StrUtil.blankToDefault(request.getTarType(), "GZIP"))
                    .build()
                    .toUriString();
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.BILL_TRADE_APPLY,
                    suffix,
                    "billDate=" + request.getBillDate(),
                    request.getBillDate(),
                    request.getPlatformTenantId(),
                    "申请交易账单失败",
                    config);
            return toBillResult(wxResp);
        } catch (Exception ex) {
            return fail(ex.getMessage());
        }
    }

    public PayBillApplyResultDTO applyFundFlowBill(PayBillFundFlowApplyRequestDTO request) {
        try {
            PayWechatConfig config = resolveConfig(request.getPlatformTenantId());
            String suffix = UriComponentsBuilder.fromPath(WxApiType.FUND_FLOW_BILL.getType())
                    .queryParam("bill_date", request.getBillDate())
                    .queryParam("account_type", StrUtil.blankToDefault(request.getAccountType(), "BASIC"))
                    .queryParam("tar_type", StrUtil.blankToDefault(request.getTarType(), "GZIP"))
                    .build()
                    .toUriString();
            JSONObject wxResp = executeLogged(
                    PayWechatInterfaceLogScenario.BILL_FUND_FLOW_APPLY,
                    suffix,
                    "billDate=" + request.getBillDate() + ",accountType=" + request.getAccountType(),
                    request.getBillDate(),
                    request.getPlatformTenantId(),
                    "申请资金账单失败",
                    config);
            return toBillResult(wxResp);
        } 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,
            String urlSuffix,
            String requestParam,
            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, RequestMethod.GET.name(), requestUrl, requestParam, businessId,
                "configTenantId=" + StrUtil.blankToDefault(tenantId, ""));
        try {
            IJPayHttpResponse response = v3Get(config, urlSuffix);
            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 PayBillApplyResultDTO toBillResult(JSONObject wxResp) {
        PayBillApplyResultDTO result = new PayBillApplyResultDTO();
        result.setHashType(wxResp.getStr("hash_type"));
        result.setHashValue(wxResp.getStr("hash_value"));
        result.setDownloadUrl(wxResp.getStr("download_url"));
        result.setSuccess(StrUtil.isNotBlank(result.getDownloadUrl()));
        result.setRawResponse(wxResp.toString());
        return result;
    }

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