package com.fdkankan.web.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author dengsixing
 * @since 2022/6/9
 **/
public class WebUtil {

    private final static String UNKNOWN = "unknown";

    /**
     * aop中获取请求参数中的参数值
     * @param pjp
     * @param request
     * @return
     */
    public static String getParameter(String paramName, JoinPoint pjp, HttpServletRequest request){
        Object[] args = pjp.getArgs();
        String contentType = request.getContentType();
        if(StrUtil.isNotEmpty(contentType) && contentType.contains(ContentType.JSON.getValue())){
            HashMap hashMap = JSON.parseObject(JSON.toJSONString(args[0]), HashMap.class);
            return (String) hashMap.get(paramName);
        }
        return request.getParameter(paramName);
    }

    public static Map<String, Object> getParameter(JoinPoint pjp, HttpServletRequest request) {
        Object[] args = pjp.getArgs();
        String contentType = request.getContentType();
        if (StrUtil.isNotEmpty(contentType) && contentType.contains(ContentType.JSON.getValue())) {
            return JSON.parseObject(JSON.toJSONString(args[0]), HashMap.class);
        } else {
            Enumeration<String> parameterNames = request.getParameterNames();
            if(CollUtil.isEmpty(parameterNames)){
                return null;
            }
            Map<String, Object> params = new HashMap<>();
            String name = null;
            do {
                name = parameterNames.nextElement();
                params.put(name, request.getParameter(name));
            }while (parameterNames.hasMoreElements());
            return params;
        }
    }

    public static Map<String, Object> getParameter(HttpServletRequest request) throws IOException {
        String contentType = request.getContentType();
        if (StrUtil.isNotEmpty(contentType) && contentType.contains(ContentType.JSON.getValue())) {
            BufferedReader reader = request.getReader(); // 对于文本数据，如JSON或XML
            String json = "";
            if (reader != null) {
                json = reader.lines().collect(Collectors.joining()); // 收集所有行到一个字符串中
            }
            return JSON.parseObject(json, HashMap.class);
        } else {
            Enumeration<String> parameterNames = request.getParameterNames();
            if(CollUtil.isEmpty(parameterNames)){
                return null;
            }
            Map<String, Object> params = new HashMap<>();
            String name = null;
            do {
                name = parameterNames.nextElement();
                params.put(name, request.getParameter(name));
            }while (parameterNames.hasMoreElements());
            return params;
        }
    }

    public static <T> T getParameter(String name, HttpServletRequest request) throws IOException {
        Map<String, Object> parameters = getParameter(request);
        return (T) parameters.get(name);
    }

    /**
     * 获取客户端请求终端地址
     * @param request  客户端请求request
     * @return  终端ip地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(StrUtil.isNotBlank(ip) && UNKNOWN.equalsIgnoreCase(ip)){
            if(ip.indexOf(",") != -1){
                ip = ip.split(",")[0];
                return ip;
            }
        }
        ip = request.getHeader("Proxy-Client-IP");
        if(StrUtil.isNotBlank(ip)) return ip;
            ip = request.getHeader("WL-Proxy-Client-IP");
        if(StrUtil.isNotBlank(ip)) return ip;
            ip = request.getHeader("HTTP-CLIENT-IP");
        if(StrUtil.isNotBlank(ip)) return ip;
            ip = request.getHeader("HTTP-X-FORWARDED-FOR");
        if(StrUtil.isNotBlank(ip)) return ip;
            ip = request.getHeader("X-Real-IP");
        if(StrUtil.isNotBlank(ip)) return ip;
            ip = request.getRemoteAddr();
        return ip;
    }

    /**
     * <p>
            获取浏览器版本
     * </p>
     * @author dengsixing
     * @date 2022/8/19
     * @param request
     * @return java.lang.String
     **/
    public static  String getBrowser(HttpServletRequest request){
        String userAgentStr = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
        String browserType = userAgent.getBrowser().toString();
        String browserVersion = userAgent.getVersion();
        String browserFormat = "%s(版本%s)";
        return  String.format(browserFormat, browserType, browserVersion);
    }

}
