package com.yihu.jw.util.common;


import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.http.client.HttpClient;
import org.omg.CORBA.WStringSeqHelper;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class LatitudeUtils {


    /**
     * 没有ak有的服务请求获取不到地址
     */
    public static final String ak = "wm9Cih17l010vL91nOfTbu8M";

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double lat1) {
        return lat1 * Math.PI / 180.0;
    }




    /**
     * 返回输入地址的经纬度坐标
     * key lng(经度),lat(纬度)
     */
    public static Map<String,String> getGeocoderLatitude(String address){
        BufferedReader in = null;
        try {
            //将地址转换成utf-8的16进制
            address = URLEncoder.encode(address, "UTF-8");
            URL tirc = new URL("https://api.map.baidu.com/geocoder/v2/?address="+ address +"&output=json&key="+ UUID.randomUUID().toString().replace("-","")+"&ak="+ak);


            in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while((res = in.readLine())!=null){
                sb.append(res.trim());
            }
            String str = sb.toString();
            Map<String,String> map = null;
            if(!StringUtils.isEmpty(str)){
                int lngStart = str.indexOf("lng\":");
                int lngEnd = str.indexOf(",\"lat");
                int latEnd = str.indexOf("},\"precise");
                if(lngStart > 0 && lngEnd > 0 && latEnd > 0){
                    String lng = str.substring(lngStart+5, lngEnd);
                    String lat = str.substring(lngEnd+7, latEnd);
                    map = new HashMap<String,String>();
                    map.put("lng", lng);
                    map.put("lat", lat);
                    return map;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 根据两个位置的经纬度，来计算两地的距离（单位为KM）
     * 参数为String类型
     * @param lat1Str 用户经度
     * @param lng1Str 用户纬度
     * @param lat2Str 商家经度
     * @param lng2Str 商家纬度
     * @return
     */
    public static String getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
        if(StringUtils.isEmpty(lat1Str)||StringUtils.isEmpty(lng1Str)
                ||StringUtils.isEmpty(lat2Str)||StringUtils.isEmpty(lng2Str)){
            return "";
        }
        double lat1 = Double.parseDouble(lat1Str);
        double lng1 = Double.parseDouble(lng1Str);
        double lat2 = Double.parseDouble(lat2Str);
        double lng2 = Double.parseDouble(lng2Str);
        double patm = 2;
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double difference = radLat1 - radLat2;
        double mdifference = rad(lng1) - rad(lng2);
        double distance = patm * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / patm), patm)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(mdifference / patm), patm)));
        distance = distance * EARTH_RADIUS;
        String distanceStr = String.valueOf(distance);
        return distanceStr;
    }

    public static String getLocationAddress(String lat, String lng)
    {
        BufferedReader in = null;
        try {
            String location = MessageFormat.format("{0},{1}", lat, lng);
            URL tirc = null;
            tirc = new URL("https://api.map.baidu.com/geocoder/v2/?location="+location+"&output=json&ak="+ak);

            in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while((res = in.readLine())!=null){
                sb.append(res.trim());
            }
            String str = sb.toString();
            JSONObject obj = JSONObject.parseObject(str);
            if (0==obj.getInteger("status")){
                JSONObject tmp = obj.getJSONObject("result");
                if (null!=tmp){
                    return tmp.getString("formatted_address");
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String args[]){
        try {
            Map<String, String> json = LatitudeUtils.getGeocoderLatitude("厦门海沧区新阳海新阳光公寓15梯304");
            System.out.println("经度 : " + json.get("lng"));
            System.out.println("纬度 : " + json.get("lat"));
        }catch (Exception e ){
            e.printStackTrace();
        }
    }


}
