package com.ytpm.attach;

import cn.hutool.core.util.StrUtil;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Enumeration;

public class WebUtil extends WebUtils {

    /**
     * 获取请求参数值，依次从paramter,header,cookie中查找
     *
     * @param request 请求
     * @param name    参数名
     * @return
     */
    public static String getRequestParamValue(HttpServletRequest request, String name) {
        String value = findParameterValue(request, name);

        if (StrUtil.isBlank(value)) {
            value = getHeaderValue(request, name);
        }

        if (StrUtil.isBlank(value)) {
            value = getCookieValue(request, name);
        }

        return value;
    }

    /**
     * 获取cookie值
     *
     * @param request 请求
     * @param name    参数名
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        String value = null;
        if (cookie != null) {
            value = cookie.getValue();
        }
        return value;
    }

    /**
     * 获取请求头header值
     *
     * @param request 请求
     * @param name    参数名
     * @return
     */
    public static String getHeaderValue(HttpServletRequest request, String name) {
        String value = null;
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            if (key.equals(name)) {
                value = request.getHeader(name);
            }
        }
        return value;
    }

    /**
     * 响应初始化（下载用）
     *
     * @param response 响应
     * @param fileName 文件名 例exp.xls
     * @throws UnsupportedEncodingException 转码异常
     */
    public static void initDownloadHeader(HttpServletResponse response, String fileName) {

        response.reset();
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 响应初始化（pdf在线展示用）
     *
     * @param response 响应
     * @param fileName 文件名 例exp.xls
     * @throws UnsupportedEncodingException 转码异常
     */
    public static void initPdfOnlineHeader(HttpServletResponse response, String fileName) {

        response.reset();
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/pdf");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取用户Ip地址
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String 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_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.getRemoteAddr();
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            }
        }
        return ip;
    }
}
