package com.seer.teach.mall.shipping.jt.http;

import com.alibaba.fastjson2.JSONObject;
import com.seer.teach.mall.shipping.jt.auth.Digests;
import com.seer.teach.mall.shipping.jt.client.JtExpressExecutor;
import com.seer.teach.mall.shipping.jt.exception.ExceptionCodeEnum;
import com.seer.teach.mall.shipping.jt.exception.JtApiException;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Getter
public class DefaultApiExecutor implements JtExpressExecutor {

    private String apiAccount;
    private String privateKey;
    private String customerCode;
    private String customerPwd;


    public DefaultApiExecutor(String apiAccount, String privateKey, String customerCode, String customerPwd) {
        this.apiAccount = apiAccount;
        this.privateKey = privateKey;
        this.customerCode = customerCode;
        this.customerPwd = customerPwd;
    }

    public String executor(Map<String, Object> body, String url) throws IOException {
        if (null == body) {
            body = new HashMap(8);
        }

        if (StringUtils.isEmpty(url)) {
            throw new JtApiException(ExceptionCodeEnum.BAD_REQUEST, "url is empty");
        } else {
            String paramJson = JSONObject.toJSONString(body);
            Map<String, String> headers = new HashMap(8);
            headers.put("digest", Digests.digestForHead(paramJson, this.getPrivateKey()));
            headers.put("timestamp", System.currentTimeMillis() + "");
            headers.put("apiAccount", this.getApiAccount());
            return HttpClientManager.getInstance().post(url, paramJson, headers);
        }
    }

    public String executorAuth(Map<String, Object> body, String url) throws IOException {
        if (null == body) {
            body = new HashMap(8);
        }

        if (this.hasProtocolAccount()) {
            body.put("digest", Digests.digestForBizParam(this.getCustomerCode(), this.getCustomerPwd(), this.getPrivateKey()));
            body.put("customerCode", this.getCustomerCode());
            return this.executor(body, url);
        } else {
            throw new JtApiException(ExceptionCodeEnum.BAD_REQUEST, "customerCode or customerPwd is empty ");
        }
    }

    private boolean hasProtocolAccount() {
        return StringUtils.isNotEmpty(this.getCustomerCode()) && StringUtils.isNotEmpty(this.getCustomerPwd());
    }

}
