package com.hs.api.common.utils;

import java.io.IOException;
import java.net.URI;

import com.hs.common.utils.StringUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.hs.api.model.TokenResult;

public class HttpClientUtil {
    /**
     * 带参数的get请求
     * @param url
     * @return String
     */
    public static String doGet(String url) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 医院接口校验token
     * @param url
     * @return boolean
     */
    public static boolean tokenCheck(String url){
        System.out.println("-----------------调用接口 token验证API BEGIN--------------->");
        System.out.println("请求url:" + url);
        boolean match = false; //是否有效
        try {
            String result = HttpClientUtil.doGet(url);
            System.out.println("请求结果：" + result);
            TokenResult tokenResult = JsonUtil.parse(result, TokenResult.class);
            System.out.println(tokenResult.toString());
            if(!StringUtil.isNullOrEmpty(result) && !tokenResult.getIsExpired()){
                TokenUtil.setToken(tokenResult.getKey(),tokenResult);
                match = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("<-----------------调用接口 token验证API END---------------");
        return match;
    }
}
