package com.engine.custom.yunxuetang.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpClientUtil {

    /**
     * 以post方式调用第三方接口方法.
     *
     * @param pathUrl     请求接口地址.
     * @param dataStr     请求参数.
     * @param accessToken accessToken.
     * @return str.
     */
    public static String doPost(String pathUrl, String dataStr, String accessToken) {

        // 请求参数转换为json字符串
        // String dataStr = JSON.toJSONString(dataMap);
        String result = null;
        try {
            // 组装请求头信息
            Map<String, String> header = new HashMap<>(2);
            header.put("Content-Type", "application/json;charset=utf-8");
            if (accessToken != null && accessToken.length() > 0) {
                header.put("Authorization", accessToken);
            }
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
            RequestBody body = RequestBody.create(mediaType, dataStr);
            Request request = new Request.Builder()
                    .url(pathUrl)                   // 请求接口地址
                    .method("POST", body)   		// 设定请求的方法为"POST"
                    .headers(Headers.of(header))    // 请求头信息
                    .build();
            Response response = client.newBuilder().readTimeout(300000L, TimeUnit.MILLISECONDS).build().newCall(request).execute();
            result = response.body().string();
        } catch (Exception e) {
            System.out.println("执行包含头部的post请求,url:" + pathUrl + "，请求数据:" + dataStr + ",执行错误信息:" + e);
        }
        return result;
    }

    /**
     * 以get方式调用第三方接口方法.
     *
     * @param pathUrl     请求接口地址.
     * @param accessToken accessToken.
     * @return str.
     */
    public static String doGet(String pathUrl, String accessToken) {

        String result = null;
        try {
            // 组装请求头信息
            Map<String, String> header = new HashMap<>(2);
            header.put("Content-Type", "application/json;charset=utf-8");
            if (accessToken != null && accessToken.length() > 0) {
                header.put("Authorization", accessToken);
            }
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            // http创建的request对象默认是get请求
            Request request = new Request.Builder()
                    .url(pathUrl)                   // 请求接口地址
                    .headers(Headers.of(header))    // 请求头信息
                    .build();
            Response response = client.newBuilder().readTimeout(300000L, TimeUnit.MILLISECONDS).build().newCall(request).execute();
            result = response.body().string();
        } catch (Exception e) {
            System.out.println("执行包含头部的get请求,url:" + pathUrl + ",执行错误信息:" + e);
        }
        return result;
    }


    // 获取accessToken
    public static String getAccessToken(String url,String appId,String appSecret) {
        Map<String, Object> body = new HashMap<>();
        String dataStr = JSON.toJSONString(body);
        // url拼接所需参数
        String pathUrl = url + "?" + "appId=" + appId + "&appSecret=" + appSecret;
        // 以post方式调用第三方接口,获取响应结果
        String result = HttpClientUtil.doPost(pathUrl, dataStr, null);

        // 返回accessToken
        JSONObject jsonObject = JSON.parseObject(result, JSONObject.class);
        return jsonObject.getString("accessToken");
    }

}
