package cn.estsh.i3plus.ext.mes.apiservice.util;


import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.HttpClientTool;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author: wangjie
 * @CreateDate: 2019/9/20 2:03 PM
 * @Description: 仅处理了get请求，其他类型使用 {@link HttpClientTool}
 **/
public class SxMesHttpUtil {

    private static String DEFAULT_CHARACTER_SET = "UTF-8";

    public static String doGet(String url, Map<String, String> params, String charset) throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(url)) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES_PCN.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("传入的url为空，请检查")
                    .build();
        }

        StringBuffer sb = new StringBuffer();
        String result;
        if (!CollectionUtils.isEmpty(params)) {
            if ((url.length() - 1) == url.lastIndexOf("/")) {
                url = url.substring(0, url.length() - 1);
            }
            sb.append(url);
            sb.append("?");
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (i > 0) {
                    sb.append("&");
                }
                sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), charset));
                i++;
            }
        } else {
            sb.append(url);
        }
        result = HttpClientTool.doGet(sb.toString());
        return result;
    }

    public static String doGet(String url, Map<String, String> params) throws UnsupportedEncodingException {
        return doGet(url, params, DEFAULT_CHARACTER_SET);
    }

    public static String doPut(String url, Map<String, String> params) {
        return HttpClientTool.doHttpUrl(CommonEnumUtil.HTTP_METHOD_TYPE.PUT, url, params);
    }


    public static String doPost(String url, Map<String, String> params) {
        return HttpClientTool.doHttpUrl(CommonEnumUtil.HTTP_METHOD_TYPE.POST, true, url, params, null, null);
    }

    public static String doGet(String url, Map<String, String> params, Map<String, String> cookies, Map<String, String> headers) {
        return HttpClientTool.doHttpUrl(CommonEnumUtil.HTTP_METHOD_TYPE.GET, url, params, cookies, headers);
    }

    public static String doPut(String url, Map<String, String> params, Map<String, String> cookies, Map<String, String> headers) {
        return HttpClientTool.doHttpUrl(CommonEnumUtil.HTTP_METHOD_TYPE.PUT, url, params, cookies, headers);
    }


}
