package com.eegrid.webapi.util;

import com.alibaba.fastjson.JSONObject;
import com.eegrid.webapi.exception.EEGridWebApiException;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


public class HttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    private static final String SERVER_BASE_URL = "http://webapi.eegrid.com";
    private static final String CLIENT_ACCESS_TOKEN = "70bc43a37516f153d086901f1d85bc4d";
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

    /**
     * 封装 JSON Post
     * @param api
     * @param paramString
     * @return
     */
    public static String post(String api, String paramString) {
        String entityString = "";
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httpPost = new HttpPost(getApiUri(api));
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity stringEntity;
        try {
            stringEntity = new StringEntity(paramString);
            stringEntity.setContentType(CONTENT_TYPE_TEXT_JSON);
            httpPost.setEntity(stringEntity);
            logger.debug("==========================================");
            logger.debug("HttpClientUtil.post: " + httpPost.getURI());
            logger.debug("==========================================");
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    entityString = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("entityString: " + entityString);
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return parseResponseEntity(entityString);
    }

    /**
     * 解析返回数据
     * @param entityString
     * @return
     */
    private static String parseResponseEntity(String entityString) {
        if (entityString == null || entityString.equals("")) {
            throw new EEGridWebApiException("[eegrid]接口异常");
        }

        // 错误信息处理
        JSONObject jsonObject = JSONObject.parseObject(entityString);
        int code = jsonObject.getIntValue("code");
        if (code != 0) {
            String message = jsonObject.getString("errorMessage");
            logger.error("code = " + code + ", message = " + message);
            System.out.println("[eegrid]接口异常：" + message);
            throw new EEGridWebApiException("[eegrid]接口异常：" + message);
        }

        return jsonObject.getString("data");
    }

    private static String getApiUri(String api) {
        return SERVER_BASE_URL + api + "?accessToken=" + CLIENT_ACCESS_TOKEN;
    }


    public static void main(String args[]) throws Exception {
        // 创建参数队列
        Map<String, Object> params = new HashMap<>();
        params.put("ProjectCode", "145");
        String response = HttpClientUtil.post("/device/get", JSONObject.toJSONString(params));
        System.out.println("HttpClientUtil response: " + response);
    }
}
