package com.zm.order.tool.server.manager;

import com.alibaba.fastjson.JSON;
import com.zm.order.tool.server.exception.InnerApiException;
import com.zm.order.tool.server.inner.ThirdApiRequest;
import com.zm.order.tool.server.utils.HttpUtils;
import com.zm.util.dto.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author nianchang
 * @ClassName ThirdApiMessage
 * @date 2021/11/08 4:44 下午
 */
@Component
public class ThirdApiMessage {

    /**
     * 路由连接串
     */
    public static final String ROUTER_SEPARATOR = "/";

    /**
     * 数据格式
     */
    public static final String CONTENT_TYPE = "application/json";

    /**
     * 签名Key：sign
     */
    public static final String SIGNATURE_KEY_SIGN = "sign";

    public Result request(ThirdApiRequest request) {
        CloseableHttpClient httpClient = HttpClients.custom().build();
        HttpUtils.Result httpResult = null;
        try {
            httpResult = HttpUtils.req(httpClient, request.getMethod(), request.getUrl(), request.getParams(),
                request.getHeaders(), request.getContentTypeOrDefault());
        } catch (HttpException e) {
            e.printStackTrace();
        } finally {
            HttpUtils.closeHttpClient(httpClient);
        }
        if (httpResult != null && httpResult.isStatusOk()) {
            Result result = JSON.parseObject(httpResult.getResponse(), Result.class);
            result.setStatus(true);
            return result;
        }
        throw new InnerApiException("调用内部方法错误");
    }

    public ThirdApiRequest buildRequest(String domainName, String url, Map<String, Object> param,
                                        Map<String, String> headers, String appendKey, String appendValue) {
        ThirdApiRequest request = new ThirdApiRequest();
        request.setUrl(joinUrl(domainName, url));
        request.setMethod(HttpUtils.MethodEnum.POST);
        request.setContentType(HttpUtils.ContentTypeEnum.JSON);

        headers.put(HTTP.CONTENT_TYPE, CONTENT_TYPE);
        headers.put(SIGNATURE_KEY_SIGN, signature(param, appendKey, appendValue));
        request.setHeaders(headers);
        // 验签
        request.setParams(param);
        return request;
    }

    /**
     * 签名
     * 
     * @param param	参数
     * @param appendKey	追加的key
     * @param appendValue 追加的value
     * @return 
     * Date: 2021/11/10 4:46 下午
     */
    public String signature(Map<String, Object> param, String appendKey, String appendValue) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry: param.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String signKey;
        if (!StringUtils.isEmpty(appendKey)) {
            signKey = sb.append(appendKey).append("=").append(appendValue).toString();
        } else {
            // 去除字符串最后一个"&"
            signKey = sb.deleteCharAt(sb.length() - 1).toString();
        }
        return DigestUtils.md5Hex(signKey);
    }

    /**
     * 拼接url
     * 
     * @param baseUri 域名或ip
     * @param path	请求路径
     * @return 
     * Date: 2021/11/10 4:45 下午
     */
    private String joinUrl(String baseUri, String path) {
        if (!baseUri.endsWith(ROUTER_SEPARATOR)) {
            baseUri += ROUTER_SEPARATOR;
        }
        if (!path.startsWith(ROUTER_SEPARATOR)) {
            path = ROUTER_SEPARATOR + path;
        }
        return baseUri + ROUTER_SEPARATOR + path;
    }
}
