package com.blueland.core.util;

import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class AccessUtil {
    /**
     * 获取当前网络ip
     * @param request
     * @return
     */
    public static String getAccessIp2(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        //"***.***.***.***".length() = 15
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    public static String getAccessIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_FORWARDED");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_VIA");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("REMOTE_ADDR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "本地";
        }
        return ip;
    }

    /**
     * 获取网页url
     * @param request
     * @return
     */
    public static String getAccessUrl(HttpServletRequest request) {
        String url = "";
        url = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort()
                + request.getServletPath();
        if (request.getQueryString() != null) {
            url += "?" + request.getQueryString();
        }
        return url;
    }

    /**
     * 获取网页标题
     * @param request
     * @return
     */
    public static String getAccessTitle(HttpServletRequest request){
        //获取htmlUrl网址网页的源码
        String htmlSource = getHtmlSource(getAccessUrl(request));
        if (StringUtil.isEmpty(htmlSource)){
            return "该url为接口调用，无标题";
        }
        return getTitle(htmlSource);
    }

    /**
     * 获取访问来源
     * @param request
     * @return
     */
    public static String getAccessSource(HttpServletRequest request){
        /**
         * android : 所有android设备
         * mac os : iphone ipad
         * windows phone:Nokia等windows系统的手机
         */
        String[] deviceArray = new String[]{"android","mac os","windows phone"};
        //获取http头信息
        String requestHeader = request.getHeader("User-Agent");
        if (requestHeader == null){
            return "unknown";
        }
        requestHeader = requestHeader.toLowerCase();
        for(int i=0;i<deviceArray.length;i++){
            if(requestHeader.indexOf(deviceArray[i])>0){
                return "APP";
            }
        }
        return "PC";
    }

    /**
     * 获取访问设备
     * @param request
     * @return
     */
    public static String getAccessDevice(HttpServletRequest request){
        String agent= request.getHeader("User-Agent");
        if (StringUtil.isEmpty(agent)){
            return "unknown";
        }
        //安卓系统
        if(agent.contains("Android")){
            return "android";
        }else if(agent.contains("iPhone")||agent.contains("iPod")||agent.contains("iPad")){
            return "ios";
        }
        return "Others";
    }

    /**
     * 获取浏览器信息
     * @param request
     * @return
     */
    public static String getAccessBrowse(HttpServletRequest request){
        String agent = request.getHeader("User-Agent");
        if (StringUtil.isEmpty(agent)){
            return "type:unknown;version:unknown";
        }
        //解析agent字符串
        UserAgent userAgent = UserAgentUtil.parse(agent);
        //获取浏览器对象
        Browser browser = userAgent.getBrowser();
        return "type:"+browser.getName()+";version:"+userAgent.getVersion();
    }

    /**
     * 根据网址返回网页的源码
     * @param htmlUrl
     * @return
     */
    public static String getHtmlSource(String htmlUrl){
        URL url;
        StringBuffer sb = new StringBuffer();
        try{
            url = new URL(htmlUrl);
            //读取网页全部内容
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
            String temp;
            while ((temp = in.readLine()) != null)
            {
                sb.append(temp);
            }
            in.close();
        }catch (MalformedURLException e) {
//            log.error("URL格式有问题！");
        }catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 从html源码(字符串)中获取标题
     * @param htmlSource
     * @return
     */
    public static String getTitle(String htmlSource){
        List<String> list = new ArrayList<String>();
        String title = "";
        //Pattern pa = Pattern.compile("<title>.*?</title>", Pattern.CANON_EQ);也可以
        //源码中标题正则表达式
        Pattern pa = Pattern.compile("<title>.*?</title>");
        Matcher ma = pa.matcher(htmlSource);
        while (ma.find())//寻找符合el的字串
        {
            list.add(ma.group());//将符合el的字串加入到list中
        }
        for (int i = 0; i < list.size(); i++)
        {
            title = title + list.get(i);
        }
        return outTag(title);
    }

    /**
     * 去掉html源码中的标签
     * @param s
     * @return
     */
    public static String outTag(String s)
    {
        return s.replaceAll("<.*?>", "");
    }

}
