package com.skyversation.poiaddr.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 地址查询请求工具类
 * 地址：上海市一张图服务
 */
public class RequestUtils {
    public static String request(String address) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String urlF = "https://service-api.onemap.sh.gov.cn/data-service-manage-service/MapProxyApi/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBsaWNhdGlvbl9pZCI6NjEsImFwcGxpY2F0aW9uX25hbWUiOiLpnZLmtabkuozkuInnu7TmnI3liqHns7vnu58iLCJleHAiOjIwNDY2Nzg0MDN9.IKUMdjUX4U1jncIUNren-iotL7duXI90aLECMjpvUX8/address_search/MapServer?query=";
            String urlE = "&region=310000&page_num=1&page_size=1";
            HttpGet httpGet = new HttpGet(urlF + address + urlE);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    return EntityUtils.toString(entity);
                } else {
                    return "请求失败，状态码: " + statusCode;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    /**
     * httpPost 请求，参数类型为formData
     *
     * @param url
     * @param headers
     * @param formDatas
     * @return
     */
    public static JSONObject requestPost(String url, Map<String, String> headers, Map<String, String> formDatas) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url); // 替换为实际的 API 地址
            if (headers != null && headers.size() > 0) {
                // 设置自定义 Header
                for (String key : headers.keySet()) {
                    httpPost.addHeader(key, headers.get(key));
                }
            }

            if (formDatas != null && formDatas.size() > 0) {
                // 设置 formData
                List<NameValuePair> formData = new ArrayList<>();
                for (String key : formDatas.keySet()) {
                    formData.add(new BasicNameValuePair(key, formDatas.get(key)));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(formData));
            }
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    JSONParser jsonParser = new JSONParser();
                    return (JSONObject) jsonParser.parse(EntityUtils.toString(entity));
                } else {
                    System.err.println("请求失败，状态码: " + statusCode);
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
            return null;
        }
    }


    /**
     * httpPost 请求，参数类型为formData
     *
     * @param url
     * @param headers
     * @param formDatas
     * @return
     */
    public static JSONObject requestPost2(String url, Map<String, String> headers, org.json.JSONObject formDatas) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url); // 替换为实际的 API 地址
            if (headers != null && headers.size() > 0) {
                // 设置自定义 Header
                for (String key : headers.keySet()) {
                    httpPost.addHeader(key, headers.get(key));
                }
            }

            if (formDatas != null && formDatas.length() > 0) {
                // 设置 formData
                List<NameValuePair> formData = new ArrayList<>();
                for (String key : formDatas.keySet()) {
                    formData.add(new BasicNameValuePair(key, formDatas.get(key).toString()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(formData));
            }
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    JSONParser jsonParser = new JSONParser();
                    return (JSONObject) jsonParser.parse(EntityUtils.toString(entity));
                } else {
                    System.err.println("请求失败，状态码: " + statusCode);
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
            return null;
        }
    }
}
