package shop.alien.util.ip;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 根据IP地址获取详细的地域信息工具类
 *
 * @author ssk
 * @version 1.0
 * @date 2019/12/27 10:50
 */
public class IpAddressUtil {
    /**
     * 测试
     *
     * @param args 主方法参数
     */
    public static void main(String[] args) {
        //广州
//        String ip = "219.136.134.157";
        //大连
//        String ip = "119.113.132.222";
        //台湾
        String ip = "34.80.132.13";
        IpAddressUtil ipAddressUtils = new IpAddressUtil();
        String address = ipAddressUtils.getAddresses(ip);
        System.out.println(address);
    }

    /**
     * 获取地区
     *
     * @param ip ip地址
     * @return 地区
     */

    public String getAddresses(String ip) {
        // 这里调用淘宝的接口
        String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
        // 从http://whois.pconline.com.cn取得IP所在的省市区信息
        ip = "ip=" + ip;
        String returnStr = this.getResult(urlStr, ip);
        if (returnStr != null) {
            //处理返回的省市区信息
            String[] temp = returnStr.split(",");
            int size = 3;
            if (temp.length < size) {
                //无效IP，局域网测试
                return "0";
            }
            //ip,1
            String ipNo = "";
            //国家,2
            String country = "";
            //区域,3
            String area;
            //省,4
            String region = "";
            //市,5
            String city = "";
            //地区,6
            String county;
            //运营商,bootstrap
            String isp = "";
            for (int i = 0; i < temp.length; i++) {
                switch (i) {
                    default:
                        break;
                    case 1:
                        ipNo = (temp[i].split(":"))[2].replaceAll("\"", "");
                        ipNo = decodeUnicode(ipNo);
                        break;
                    case 2:
                        country = (temp[i].split(":"))[1].replaceAll("\"", "");
                        country = decodeUnicode(country);
                        break;
                    case 3:
                        area = (temp[i].split(":"))[1].replaceAll("\"", "");
                        area = decodeUnicode(area);
                        break;
                    case 4:
                        region = (temp[i].split(":"))[1].replaceAll("\"", "");
                        region = decodeUnicode(region);
                        break;
                    case 5:
                        city = (temp[i].split(":"))[1].replaceAll("\"", "");
                        city = decodeUnicode(city);
                        break;
                    case 6:
                        county = (temp[i].split(":"))[1].replaceAll("\"", "");
                        county = decodeUnicode(county);
                        break;
                    case 7:
                        isp = (temp[i].split(":"))[1].replaceAll("\"", "");
                        isp = decodeUnicode(isp);
                        break;
                }
            }
            return country + "," + region + "," + city + "," + isp + "," + ipNo;
        }
        return null;
    }

    /**
     * 请求服务
     *
     * @param urlStr  请求的地址
     * @param content 请求的参数 格式为：name=xxx&pwd=xxx
     * @return json串
     */
    public String getResult(String urlStr, String content) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            // 新建连接实例
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间，单位毫秒
            connection.setConnectTimeout(2000);
            // 设置读取数据超时时间，单位毫秒
            connection.setReadTimeout(2000);
            // 是否打开输出流true|false
            connection.setDoOutput(true);
            // 是否打开输入流true|false
            connection.setDoInput(true);
            // 提交方法POST|GET
            connection.setRequestMethod("POST");
            // 是否缓存true|false
            connection.setUseCaches(false);
            // 打开连接端口
            connection.connect();
            // 打开输出流往对端服务器写数据
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            // 写数据,也就是提交你的表单name=xxx&pwd=xxx
            out.writeBytes(content);
            // 刷新
            out.flush();
            // 关闭输出流
            out.close();
            // 往对端写完数据对端服务器返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            // 以BufferedReader流来读取
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                // 关闭连接
                connection.disconnect();
            }
        }
        return null;
    }

    /**
     *     * unicode 转换成 中文
     * <p>
     *     *
     * <p>
     *     * @author fanhui 2007-3-15
     * <p>
     *     * @param theString
     * <p>
     *     * @return
     * <p>
     *    
     */
    public static String decodeUnicode(String theString) {
        char aChar;
        int len = theString.length();
        StringBuilder outBuffer = new StringBuilder(len);
        for (int x = 0; x < len; ) {
            aChar = theString.charAt(x++);
            if (aChar == '\\') {
                aChar = theString.charAt(x++);
                if (aChar == 'u') {
                    int value = 0;
                    int size = 4;
                    for (int i = 0; i < size; i++) {
                        aChar = theString.charAt(x++);
                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                value = (value << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                value = (value << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                value = (value << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException("Malformed      encoding.");
                        }
                    }
                    outBuffer.append((char) value);
                } else {
                    if (aChar == 't') {
                        aChar = '\t';
                    } else if (aChar == 'r') {
                        aChar = '\r';
                    } else if (aChar == 'n') {
                        aChar = '\n';
                    } else if (aChar == 'f') {
                        aChar = '\f';
                    }
                    outBuffer.append(aChar);
                }
            } else {
                outBuffer.append(aChar);
            }
        }
        return outBuffer.toString();
    }

}
