package com.muyu.cloud.mart.utils;

import com.alibaba.fastjson.JSON;
import com.muyu.cloud.mart.mapper.MarketMapper;
import com.muyu.domain.Connector;
import com.muyu.domain.IpPlace;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author：chaiyapeng
 * @Package：com.muyu.cloud.mart.utils
 * @Project：cloud-mart
 * @name：IPLocation
 * @Date：2024/8/23 20:54
 * IP查询归属地
 */
public class IPLocation {

    public static String API_URL = "http://apis.juhe.cn/ip/ipNewV3";
    // 接口请求Key
    public static String API_KEY = "e84b7d13a9fb87b4ebcc9813e4518955";
    public static IpPlace queryIPLocation(String ip){
//        String apiKey = "e84b7d13a9fb87b4ebcc9813e4518955";
//        String apiUrl = "http://apis.juhe.cn/ip/ipNewV3";
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", API_KEY);
        map.put("ip", ip);
        String urlencode = urlencode(map);

        IpPlace ipPlace = new IpPlace();
        String s = doGet(API_URL, urlencode);
        try {
//            URL url = new URL(String.format(apiUrl + "?" + params(map)));
            JSONObject jsonObject = JSONObject.fromObject(s);
            int error_code = jsonObject.getInt("error_code");
            if (error_code == 0) {
                System.out.println("调用接口成功");

                JSONObject result = jsonObject.getJSONObject("result");

                ipPlace.setCountry(result.getString("Country"));
                ipPlace.setProvince(result.getString("Province"));
                ipPlace.setCity(result.getString("City"));
                ipPlace.setDistrict(result.getString("District"));
                ipPlace.setIsp(result.getString("Isp"));
                ipPlace.setIp(ip);

                System.out.printf("国家：%s%n", result.getString("Country"));
                System.out.printf("省份：%s%n", result.getString("Province"));
                System.out.printf("城市：%s%n", result.getString("City"));
                System.out.printf("邮编：%s%n", result.getString("District"));
                System.out.printf("运营商：%s%n", result.getString("Isp"));

            } else {
                System.out.println("调用接口失败：" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//            BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
//            String inputLine;
//            StringBuffer stringBuffer = new StringBuffer();
//
//            while ((inputLine = in.readLine()) != null){
//                stringBuffer.append(inputLine);
//           /*     System.out.println(inputLine);*/
//            }
//
//            in.close();
//            System.out.println(stringBuffer);
//            return stringBuffer;
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        return ipPlace;
    }


    public static String params(Map<String, String> map) {
        return map.entrySet().stream()
                .map(entry -> {
                    try {
                        return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        return entry.getKey() + "=" + entry.getValue();
                    }
                })
                .collect(Collectors.joining("&"));
    }

    /**
     * get方式的http请求
     *
     * @param httpUrl 请求地址
     * @return 返回结果
     */
    public static String doGet(String httpUrl, String queryParams) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString());
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(5000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(6000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                // 封装输入流，并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append(System.getProperty("line.separator"));
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }

    /**
     * 将map型转为请求参数型
     *
     * @param data
     * @return
     */
    public static String urlencode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }
}
