package shop.alien.util.httpsend.spring;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Get请求
 *
 * @author ssk
 * @version 1.0
 * @date 2022/8/8 11:02
 */
@Component
@Slf4j
public class GetMethod {

    /**
     * Get请求
     *
     * @param requestUrl 请求地址
     * @param param      请求参数(a=a&b=b&c=c)
     * @return String
     */
    public String get(String requestUrl, String param) {
        //访问返回结果
        StringBuilder result = new StringBuilder();
        //读取访问结果
        BufferedReader read = null;
        try {
            //创建url
            URL url = new URL(requestUrl + "?" + param);
            //打开连接
            URLConnection connection = url.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //建立连接
            connection.connect();
            // 获取所有响应头字段
//            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段，获取到cookies等
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            read = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            //循环读取
            while ((line = read.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("GetMethod: " + e.getMessage());
            return "9999";
        } finally {
            //关闭流
            if (read != null) {
                try {
                    read.close();
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
        }
        return result.toString();
    }

    /**
     * Get请求
     *
     * @param requestUrl 请求地址
     * @param paramMap   请求参数(Map<String, String>)
     * @return String
     */
    public String get(String requestUrl, Map<String, String> paramMap) {
        String result = null;
        HttpGet get = new HttpGet(requestUrl);
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            List<NameValuePair> params = setHttpParams(paramMap);
            String param = URLEncodedUtils.format(params, StandardCharsets.UTF_8);
            get.setURI(URI.create(requestUrl + "?" + param));
            HttpResponse response = httpClient.execute(get);
            result = getHttpEntityContent(response);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && result == null) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            get.abort();
        }
        return result;
    }

    /**
     * Get请求
     *
     * @param requestUrl 请求地址
     * @param paramMap   请求参数
     * @param headerMap  请求头
     * @return String
     */
    public String get(String requestUrl, Map<String, String> paramMap, Map<String, String> headerMap) {
        String result = null;
        HttpGet get = new HttpGet(requestUrl);
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            List<NameValuePair> params = setHttpParams(paramMap);
            String param = URLEncodedUtils.format(params, StandardCharsets.UTF_8);
            get.setURI(URI.create(requestUrl + "?" + param));
            //设置Header
            if (!headerMap.isEmpty()) {
                Set<String> set = headerMap.keySet();
                for (String next : set) {
//                    System.out.println("key为：" + next + ",value为：" + headerMap.get(next));
                    get.setHeader(next, headerMap.get(next));
                }
            }
            HttpResponse response = httpClient.execute(get);
            result = getHttpEntityContent(response);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && result == null) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            get.abort();
        }
        return result;
    }


    /**
     * Get请求
     *
     * @param requestUrl 请求地址
     * @param headerMap  请求头
     * @return String
     */
    public String getWithHeader(String requestUrl, Map<String, String> headerMap) {
        String result = null;
        try {
            HttpGet get = new HttpGet(requestUrl);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置Header
            if (!headerMap.isEmpty()) {
                Set<String> set = headerMap.keySet();
                for (String next : set) {
//                    System.out.println("key为：" + next + ",value为：" + headerMap.get(next));
                    get.setHeader(next, headerMap.get(next));
                }
            }
            HttpResponse response = httpClient.execute(get);
            result = getHttpEntityContent(response);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && result == null) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 请求参数处理
     *
     * @param requestParam 请求参数
     * @return 处理后参数
     */
    public List<NameValuePair> setHttpParams(Map<String, String> requestParam) {
        List<NameValuePair> params = new ArrayList<>();
        Set<Map.Entry<String, String>> set = requestParam.entrySet();
        for (Map.Entry<String, String> entry : set) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return params;
    }

    /**
     * 请求网络
     *
     * @param response 请求内容
     * @return 返回结果
     */
    public String getHttpEntityContent(HttpResponse response) {
        try {
            String result = "";
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream in = entity.getContent();
                BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append('\n');
                }
                br.close();
                in.close();
                result = sb.toString();
            }
            return result;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

}
