package cn.van.business.erp.request;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public abstract class ERPRequestBase {
    protected String url;
    protected String sign;
    protected ERPAccount erpAccount;
    protected JSONObject requestBody;

    public ERPRequestBase(String url, ERPAccount erpAccount) {
        this.url = url;
        this.erpAccount = erpAccount;
    }

    public void setRequestBody(JSONObject requestBody) {
        this.requestBody = requestBody;
    }

    public String genMd5(String str) {
        StringBuilder result = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
            for (byte b : digest) {
                result.append(String.format("%02x", b & 0xff));
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return result.toString();
    }

    public void genSign() {
        long timestamp = System.currentTimeMillis() / 1000;
        String jsonStr = requestBody.toJSONString();
        String data = erpAccount.getApiKey() + "," + genMd5(jsonStr) + "," + timestamp + "," + erpAccount.getApiKeySecret();
        this.sign = genMd5(data);
    }

    public String getRequestUrl() {
        return url+"?appid="+erpAccount.getApiKey()+"&timestamp="+System.currentTimeMillis()/1000+"&sign="+sign;
    }
    public String getRequestBody() {
        return requestBody.toJSONString();
    }
    public String getResponseBody() {
        genSign();
        HttpRequest post = HttpRequest.post(getRequestUrl());
        post.body(getRequestBody());
        return post.execute().body();
    }

}
