package com.example.repurchase.utils;

import com.alibaba.fastjson.JSONArray;
import com.example.repurchase.pojo.BaiduResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;


public class BaiDuMapUnit {

    private static Logger log = LoggerFactory.getLogger(BaiDuMapUnit.class);

    private static final String[] AK = {
            "O2tp0amjrqsqMQir4P9e0qvHyNGfv6p9",
//            "khhGWEqc4pCqcGx09g5EctftnngRoUZa",
//            "vcKssv26kGWdRKCjWefKbnsNl5NgElul",
//            "HsqelijTw5c3fWZ43KuOyGcYXHNWILk4"
    };

    /**
     * 输入地址返回经纬度坐标 key lng(经度),lat(纬度)
     */
    public static BaiduResult getGeocoderLatitude(String address, Integer ThreadNum) {
        BufferedReader in = null;
        BaiduResult baiduResult = null;
        int index = Math.abs(ThreadNum % AK.length);
        try {
            address = URLEncoder.encode(address, "UTF-8");
            URL url = new URL("http://api.map.baidu.com/place/v2/search?ak=" + AK[index] + "&output=json&query=" + address +
                    "&page_size=10&page_num=0&scope=1&region=全国&mcode=F5:3E:p06:3E:FC:E8:ED:19:60:2E:99:63:D8:78:85:2E:EB:12:9D:BE;com.mikyou.maptest");
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(30000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB5; .NET CLR 2.0.50727; CIBA)");

            in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            String str = sb.toString();
//            System.out.println(str);
            if (!"".equals(sb)) {
                baiduResult = JSONArray.parseObject(str, BaiduResult.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            baiduResult = new BaiduResult();
            baiduResult.setMessage("失败");
            System.out.println(baiduResult);
            return baiduResult;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return baiduResult;
    }


    public static HashMap<String, Double> getLatLng(String address, Integer threadNum) {
        address = address.replaceAll("[^0-9a-zA-Z\u4e00-\u9fa5.，,。？“”]+", "");
        BaiduResult baiduResult = BaiDuMapUnit.getGeocoderLatitude(address, threadNum);
        if ("失败".equals(baiduResult.getMessage())) {
            log.error(baiduResult.toString());
        }
        HashMap<String, Double> latLngMaps = new HashMap<>();
        if ("ok".equals(baiduResult.getMessage())) {
            if (baiduResult.getResults() != null && baiduResult.getResults().size() >= 1 && baiduResult.getResults().get(0).getLocation() != null) {
                latLngMaps.put("lat", baiduResult.getResults().get(0).getLocation().getLat());
                latLngMaps.put("lng", baiduResult.getResults().get(0).getLocation().getLng());
            } else {
                if (address.contains("村") | address.contains("街道")) {
                    address = address.split("[村|街道]")[0];
                    return getLatLng(address, threadNum);
                }
                if (address.contains("镇") | address.contains("乡")) {
                    address = address.split("[镇|乡]")[0];
                    return getLatLng(address, threadNum);
                }
                if (address.contains("县") | address.contains("区") | address.contains("旗")) {
                    address = address.split("[县|区|旗]")[0];
                    return getLatLng(address, threadNum);
                }
                latLngMaps.put("lat", -120.0);
                latLngMaps.put("lng", -120.0);
            }
        } else if ("服务内部错误".equals(baiduResult.getMessage())) {
            latLngMaps.put("lat", -120.0);
            latLngMaps.put("lng", -120.0);
            log.info(baiduResult.toString());
        } else {
            log.info(baiduResult.toString());
            return null;
        }
        return latLngMaps;
    }
}
