package com.skyversation.poiaddr.util;

import com.alibaba.fastjson.JSONArray;
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.io.FileWriter;
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();
        }
    }

    public static void main(String[] args) {
        com.alibaba.fastjson.JSONObject AllData = new com.alibaba.fastjson.JSONObject();
        JSONArray featuresList = new JSONArray();
        for (int i = 1; i <= 7282; i++) {
            if (i == 7282) {
                String requestData = requestWFS(i + "");
                com.alibaba.fastjson.JSONObject requestJson = com.alibaba.fastjson.JSONObject.parseObject(requestData);
                if (requestJson.containsKey("features")) {
                    featuresList.add(requestJson.getJSONArray("features").getJSONObject(0));
                }
            }
        }
        AllData.put("features", featuresList);
        AllData.put("type", "FeatureCollection");
        System.out.println("内容大小：" + featuresList.size());
        String jsonString = AllData.toJSONString();
        String filePath = "output/cj_1.geojson";
        try (FileWriter fileWriter = new FileWriter(filePath)) {
            fileWriter.write(jsonString);
            System.out.println("完成！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String requestWFS(String index) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String urlF = "https://data.songjiang.gov.cn:19997/geoscene/rest/services/7unv4vbwqxnq4a7m9h/SHBDC/JWH_3857/MapServer/4/query?where=&text=&objectIds=";
            String urlE = "&time=&timeRelation=esriTimeRelationOverlaps&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&havingClause=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&returnExtentOnly=false&sqlFormat=none&datumTransformation=&parameterValues=&rangeValues=&quantizationParameters=&featureEncoding=esriDefault&f=geojson";
            HttpGet httpGet = new HttpGet(urlF + index + 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;
        }
    }
}
