package com.yanzuoguang.util.helper;

import com.yanzuoguang.util.contants.SystemContants;

import java.net.*;
import java.util.*;

/**
 * 地址字符串处理
 *
 * @author 颜佐光
 */
public class UrlHelper {
    /**
     * 转换为%E4%BD%A0形式
     *
     * @param from     来源字符串
     * @param encoding 编码方式
     * @return 转换后的结果
     */
    public static String encoding(String from, String encoding) {
        try {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < from.length(); i++) {
                char c = from.charAt(i);
                if (c >= 0 && c <= 255) {
                    sb.append(c);
                } else {
                    String t = URLEncoder.encode("" + c, encoding);
                    sb.append(t);
                }
            }
            return sb.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 将%E4%BD%A0转换为汉字
     *
     * @param from     来源字符串
     * @param encoding 编码方式
     * @return 转换后的结果
     */
    public static String decoding(String from, String encoding) {
        try {
            return URLDecoder.decode(from, encoding);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取IP
     *
     * @return 获取到的IP
     */
    public static String getIp() {
        List<String> ips = getIps();
        if (ips.size() == 1) {
            return ips.get(0);
        }
        for (String ip : ips) {
            if ("127.0.0.1".equals(ip) || "0.0.0.0".equals(ip)) {
                continue;
            }
            return ip;
        }
        return StringHelper.EMPTY;
    }

    /**
     * 获取IP列表
     *
     * @return IP结果
     */
    public static List<String> getIps() {
        List<String> ipList = new ArrayList<String>();
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    // IPV4
                    if (inetAddress != null && inetAddress instanceof Inet4Address) {
                        String ip = inetAddress.getHostAddress();
                        ipList.add(ip);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipList;
    }


    /**
     * 处理是否斜线分隔符结尾
     *
     * @param url 需要处理的地址
     * @return 处理后的结果
     */
    public static String dealWithUrl(String url) {
        if (!url.endsWith(SystemContants.SLASH) || !url.endsWith(SystemContants.UNSLASH)) {
            url += SystemContants.SLASH;
        }
        return url;
    }

    /**
     * 处理双斜线
     * <p>
     * 1、\\ --> /
     * 2、// --> /
     *
     * @param url 需要处理的地址
     * @return 处理后的结果
     */
    public static String dealUrlDoubleChar(String url) {
        return url.replaceAll(SystemContants.SLASH + SystemContants.SLASH, SystemContants.SLASH).
                replaceAll(SystemContants.UNSLASH + SystemContants.UNSLASH, SystemContants.SLASH);
    }

    /**
     * 获取合法的文件夹路径地址
     *
     * @return 获取合法的文件夹路径地址
     */
    public static String getFolderPath(String url) {
        url = UrlHelper.dealUrlDoubleChar(url);
        url = UrlHelper.dealWithUrl(url);
        return url;
    }

    /**
     * 解析出url请求的路径,包括页面
     *
     * @param strURL url地址
     * @return url路径
     */
    public static String getPage(String strURL) {
        strURL = StringHelper.getFirst(strURL);
        int pos = strURL.indexOf("?");
        if (pos > -1) {
            return strURL.substring(0, pos);
        }
        return strURL;
    }

    /**
     * 去掉url中的路径,留下请求参数部分
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    private static String getQueryString(String strURL) {
        strURL = StringHelper.getFirst(strURL);
        int pos = strURL.indexOf("?");
        if (pos > -1) {
            return strURL.substring(pos + 1);
        }
        return StringHelper.EMPTY;
    }

    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123",解析出Action:del,id:123存入map中
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    public static Map<String, String> getQueryObject(String strURL) {
        String strUrlParam = getQueryString(strURL);
        Map<String, String> mapRequest = new HashMap<>();
        //每个键值为一组 www.2cto.com
        String[] arrSplit = strUrlParam.split("&");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = strSplit.split("=");
            //解析出键值
            if (arrSplitEqual.length > 1) {
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            }
        }
        return mapRequest;
    }

/**
 public static void main(String[] args) {
 String url = "http://wx.pangdly.com/#/orderPayment?companyId=6da527f930be4aa1904fe17fcb41874f&order=z001570428580820822894116f754e96";
 System.out.println(getPage(url));
 System.out.println(getQueryString(url));
 System.out.println(JsonHelper.serialize(getQueryObject(url)));

 url = "orderPayment?companyId=6da527f930be4aa1904fe17fcb41874f&order=z001570428580820822894116f754e96";
 System.out.println(getPage(url));
 System.out.println(getQueryString(url));
 System.out.println(JsonHelper.serialize(getQueryObject(url)));


 url = "http://wx.pangdly.com/orderPayment";
 System.out.println(getPage(url));
 System.out.println(getQueryString(url));
 System.out.println(JsonHelper.serialize(getQueryObject(url)));
 }
 */
}