package com.beanpodtech.allinone.utils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.beanpodtech.allinone.bean.IpBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;

public class IPUtils {
    private static final String TAG = "lhs-IPUtils";

    /**
     * 获取IP地址
     *
     * @return
     * @throws SocketException
     */
    public static String getLocalIPAddress() throws SocketException {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
        return "null";
    }

    /**
     * 从搜狐API获取外网IP地址
     * <p>
     * demo
     * new Thread(new Runnable() {
     *
     * @return
     * @Override public void run() {
     * IPUtils.getNetIpFromSohu()
     * }
     * }).start();
     */
    public static String getNetIpFromSohu(String userId) {
        final String[] ip = {""};
        OkGo.<String>get("http://pv.sohu.com/cityjson?ie=utf-8").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                // 从反馈的结果中提取出IP地址
                int start = body.indexOf("{");
                int end = body.indexOf("}");
                String json = body.substring(start, end + 1);
                if (json != null) {
//                    try {
//                        JSONObject jsonObject = new JSONObject(json);
//                        ip = jsonObject.optString("cip");
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
                    Gson gson = new Gson();
                    IpBean ipBean = gson.fromJson(json, IpBean.class);
                    ip[0] = ipBean.getCip();

                }
            }
        });
        return ip[0];
//        URL infoUrl = null;
//        InputStream inStream = null;
//        String ip = "";
//        try {
//            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
//            URLConnection connection = infoUrl.openConnection();
//            HttpURLConnection httpConnection = (HttpURLConnection) connection;
//            int responseCode = httpConnection.getResponseCode();
//            if (responseCode == HttpURLConnection.HTTP_OK) {
//                inStream = httpConnection.getInputStream();
//                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
//                StringBuilder strber = new StringBuilder();
//                String strLine = "";
//                while ((strLine = reader.readLine()) != null) {
//                    strber.append(strLine + "\n");
//                    Log.d(TAG, "strLine====" + strLine.toString());
//                }
//                inStream.close();
//                Log.d(TAG, "strber====" + strber.toString());
//                // 从反馈的结果中提取出IP地址
//                int start = strber.indexOf("{");
//                int end = strber.indexOf("}");
//                String json = strber.substring(start, end + 1);
//                if (json != null) {
//                    try {
//                        JSONObject jsonObject = new JSONObject(json);
//                        ip = jsonObject.optString("cip");
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//
//                }
//                Log.d(TAG, "ip====" + ip);
//            }
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return ip;
    }

    public static void getDeviceStatus(final String userId, final Handler handler) {
//        final String[] status = new String[1];
        OkGo.<String>get("http://pv.sohu.com/cityjson?ie=utf-8").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                // 从反馈的结果中提取出IP地址
                int start = body.indexOf("{");
                int end = body.indexOf("}");
                String json = body.substring(start, end + 1);
                if (json != null) {
                    Gson gson = new Gson();
                    IpBean ipBean = gson.fromJson(json, IpBean.class);
                    String cip = ipBean.getCip();
//                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), initRequestJson(cip, getDeviceSN(), userId));
                    OkGo.<String>post(UrlConfig.FIXED_POSITION).upRequestBody(HttpUtils.getRequestJson(initRequestJson(cip, BoxUtil.getDeviceSN(), userId))).execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            String result = response.body();
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                int status = jsonObject.getInt("status");
                                Message message = Message.obtain();
                                message.what = -1;
                                message.arg1 = status;
                                handler.sendMessage(message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
//        return status[0];

    }

    /**
     * @return 返回requestBody  做筛选条件的请求使用
     */
    private static HashMap initRequestJson(String ip, String deviceSN, String userId) {
        HashMap<String, String> map = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
//        try {
        map.put("userId", userId);
        map.put("ip", ip);
        map.put("longitude", "");
        map.put("latitude", "");
//            jsonObject.put("boxID", deviceSN);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
        return map;
    }

    /**
     * 从淘宝服务获取外网IP地址
     *
     * @return
     */
    public static String GetNetIpFromTaoBao() {
        String IP = "";
        try {
            String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
            URL url = new URL(address);

            //URLConnection htpurl=url.openConnection();

            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //设置浏览器ua 保证不出现503

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream in = connection.getInputStream();

                // 将流转化为字符串
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));

                String tmpString = "";
                StringBuilder retJSON = new StringBuilder();
                while ((tmpString = reader.readLine()) != null) {
                    retJSON.append(tmpString + "\n");
                }

                JSONObject jsonObject = new JSONObject(retJSON.toString());
                String code = jsonObject.getString("code");

                if (code.equals("0")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    IP = data.getString("ip") + "(" + data.getString("country")
                            + data.getString("area") + "区"
                            + data.getString("region") + data.getString("city")
                            + data.getString("isp") + ")";

                    Log.e(TAG, "您的IP地址是：" + IP);
                } else {
                    IP = "";
                    Log.e(TAG, "IP接口异常，无法获取IP地址！");
                }
            } else {
                IP = "";
                Log.e(TAG, "网络连接异常，无法获取IP地址！");
            }
        } catch (Exception e) {
            IP = "";
            Log.e(TAG, "获取IP地址时出现异常，异常信息是：" + e.toString());
        }
        return IP;
    }
}
