package com.xkrs.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 根据经纬度获取地址:省 市 区 位置名称
 * @author XinYi Song
 */
public class AddressUtils {

    /*public static String getLatAndLng(String lat, String lng) {
        String key = "O7QBZ-ZYDKI-EMKGN-53UHG-5XSJF-AAFBP";
        try {
            String hsUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + key + "&get_poi=1";

            URL url;

            url = new URL(hsUrl);
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
            // 提交模式
            con.setRequestMethod("GET");
            X509TrustManager xtm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    // TODO Auto-generated method stub
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }

                @Override
                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }
            };

            TrustManager[] tm = {xtm};

            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, tm, null);

            con.setSSLSocketFactory(ctx.getSocketFactory());
            con.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });


            InputStream inStream = con.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            //网页的二进制数据
            byte[] b = outStream.toByteArray();
            outStream.close();
            inStream.close();
            String rtn = new String(b, "utf-8");
            if (StringUtils.isNotBlank(rtn)) {
                JSONObject object = JSONObject.fromObject(rtn);
                if (object != null) {
                    if (object.has("status") && object.getInt("status") == 0) {
                        JSONObject result = JSONObject.fromObject(object.get("result"));
                        if (result != null) {
                            JSONObject addressComponent = JSONObject.fromObject(result.get("address_component"));
                            if (addressComponent != null) {
                                String province = (String) addressComponent.get("province");
                                String city = (String) addressComponent.get("city");
                                String district = (String) addressComponent.get("district");
                                String street = (String) addressComponent.get("street");
                                String street_number = (String) addressComponent.get("street_number");
                                String address = province + city + district + street + street_number;
                                return address;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
            "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36";

    /**
     * 获取指定经纬度的地理位置
     * @param latitude 纬度
     * @param longitude 经度
     * @return
     */
    public static String getLocal(String latitude, String longitude) {
        String ok = "ok";
        String msg = "msg";
        String info = getAdd(latitude, longitude);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = null;
        try {
            node = mapper.readTree(info);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        assert node != null;
        String province = null;
        String city = null;
        String county = null;
        String road = null;
        String address = null;
        if (ok.equals(node.path(msg).asText())) {
            province = node.path("result").path("addressComponent").path("province").asText();
            city = node.path("result").path("addressComponent").path("city").asText();
            county = node.path("result").path("addressComponent").path("county").asText();
            road = node.path("result").path("addressComponent").path("road").asText();
            address = node.path("result").path("addressComponent").path("address").asText();
        }
        String fireAddress = province + city + county + road + address;
        return fireAddress;
    }
    /**
     *  根据经纬度获取位置信息
     * @param latitude 纬度
     * @param longitude 经度
     * @return
     */
    public static String getAdd(String latitude, String longitude) {
        // 读取成功标志
        boolean isSuccess = false;
        // 重复次数
        int count = 10;
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> paramMap = new HashMap<>(3);
        paramMap.put("lon", longitude);
        paramMap.put("lat", latitude);
        paramMap.put("ver", "1");
        String paramStr = null;
        try {
            paramStr = mapper.writeValueAsString(paramMap);
        } catch (JsonProcessingException e) {
            log.error("转json失败,{}", (Object) e.getStackTrace());
        }
        String url = String.format("http://api.tianditu.gov.cn/geocoder?type=geocode&tk=5a1d34815475f88e6d8802da6be832ae&postStr=%s",
                paramStr);
        // 创建http对象
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000)
                .build();
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultRequestConfig(defaultRequestConfig).build();

        // 创建并设置URI
        URIBuilder uri = null;
        // 创建Get请求
        HttpGet get = null;

        try {
            URL url1 = new URL(url);
            URI uri1 = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
            uri = new URIBuilder(uri1);
            get = new HttpGet(uri.build());
            // 设置请求头
            setGet(get);
        } catch (URISyntaxException | MalformedURLException e) {
            log.info("错误{}", (Object) e.getStackTrace());
        }
        //发送请求
        HttpEntity entity = null;
        InputStream is = null;
        BufferedReader br = null;
        // 创建响应对象
        CloseableHttpResponse response = null;
        String line;
        String sLine = null;

        String json = null;
        while (!isSuccess && count > 0) {
            try {
                response = client.execute(get);
                // 获取请求结果
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    log.info("实时定位数据未请求成功");
                    count--;
                    //close(is, br, response, client);
                    continue;
                }
                entity = response.getEntity();
                is = entity.getContent();
                br = new BufferedReader(
                        new InputStreamReader(is, StandardCharsets.UTF_8)
                );
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                sLine = sb.toString();
                sLine = sLine.substring(sLine.indexOf("{"));
                //使用ObjectMapper对象对 User对象进行转换
                try {
                    json = mapper.writeValueAsString(sLine);
                } catch (JsonProcessingException e) {
                    log.info("json字符串转化异常{}", (Object) e.getStackTrace());
                }
                isSuccess = true;

            } catch (ClientProtocolException e) {
                log.info("请求超时等问题:{}", (Object) e.getStackTrace());
            } catch (IOException e) {
                log.info("I/O问题:{}", (Object) e.getStackTrace());
            } finally {
                close(is, br, response, client);
            }
        }
        return sLine;
    }

    private static void close(InputStream is, BufferedReader br, CloseableHttpResponse response, CloseableHttpClient client){
        try {
            if (null != is){
                is.close();
            }
            if (null != br){
                br.close();
            }
            if (null != response){
                response.close();
            }
            if (null != client){
                client.close();
            }
        } catch (IOException e) {
            log.info("IO错误{}", (Object) e.getStackTrace());
        }
    }

    private static HttpGet setGet(HttpGet get) {
        get.setHeader("Accept"
                , "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        get.setHeader("Accept-Encoding"
                , "gzip, deflate");
        get.setHeader("Accept-Language"
                , "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6");
        get.setHeader("Connection"
                , "keep-alive");
        get.setHeader("Cache-Control"
                , "no-cache");
        get.setHeader("Upgrade-Insecure-Requests"
                , "1");
        get.setHeader("User-Agent", USER_AGENT);
        return get;
    }

    public static void main(String[] args) {
        String latAndLng = getLocal("36.89", "115.90");
        System.out.println(latAndLng);
    }
}
