package com.ehking.demo.utils;


import com.alibaba.fastjson.JSONObject;
import com.ehking.sdk.CipherWrapper;
import com.ehking.sdk.RSAUtils;
import com.ehking.sdk.exception.UnknownException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class JsonBuilder {

    String partnerId = "";

    public String getMerchantId() {
        return merchantId;
    }

    String merchantId = "";

    public String getPartnerId() {
        return partnerId;
    }

    public JSONObject getRawDataJson() {
        return rawDataJson;
    }

    JSONObject rawDataJson = null;

    static final Logger LOGGER = LoggerFactory.getLogger(JsonBuilder.class);

    public JsonBuilder(String merchantId, String partnerId, JSONObject rawDataJson) {
        this.merchantId = merchantId;
        this.partnerId = partnerId;
        this.rawDataJson = rawDataJson;
    }


    /**
     * 构建请求参数 签名+加密
     */
    public JSONObject buildRequestParam() {
        JSONObject json = rawDataJson;
        //生成签名数据 此处不会对数据进行散列运算 会在加密时对数据进行处理

        StringBuilder hmacSourceResult = new StringBuilder();
        FastJsonUtils.generateHmacSource(json, null, hmacSourceResult);
        LOGGER.debug("数据签名拼接串，hmacSource: {}", hmacSourceResult.toString());

        try {
            json.put("hmac", RSAUtils.encryptSHA(hmacSourceResult.toString().getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            LOGGER.error("生成摘要数据异常", e);
            throw new UnknownException(e);
        }

        if (StringUtils.isNotBlank(partnerId)) {
            return CipherWrapper.bothEncryptWrap(merchantId, partnerId, json);
        }
        return CipherWrapper.bothEncryptWrap(merchantId, json);
    }
}