package com.qmth.teachcloud.common.util;

import com.alibaba.fastjson.JSONObject;
import com.qmth.boot.core.enums.Platform;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @Description: http工具
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/4/10
 */
public class ServletUtil {
    private final static Logger log = LoggerFactory.getLogger(ServletUtil.class);

    /**
     * 输出错误
     *
     * @param response
     * @param code
     * @param message
     * @throws IOException
     */
    public static void responseError(ServletResponse response, int code, String message) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        Result result = ResultUtil.error(code, message);
        String json = JSONObject.toJSONString(result);
        httpResponse.getWriter().print(json);
    }

    /**
     * 获取请求的sign
     *
     * @return
     */
    public static String getRequestSign() {
        try {
            HttpServletRequest request = getRequest();
            return Objects.isNull(request.getHeader(SystemConstant.SIGN)) ? request.getParameter(SystemConstant.SIGN) : request.getHeader(SystemConstant.SIGN);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            throw ExceptionResultEnum.SIGN_INVALID.exception();
        }
    }

    /**
     * 获取请求的token
     *
     * @return
     */
    public static String getRequestToken() {
        try {
            HttpServletRequest request = getRequest();
            return Objects.isNull(request.getHeader(SystemConstant.TOKEN)) ? request.getParameter(SystemConstant.TOKEN) : request.getHeader(SystemConstant.TOKEN);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            throw ExceptionResultEnum.TOKEN_INVALID.exception();
        }
    }

    /**
     * 获取请求的platform
     *
     * @return
     */
    public static Platform getRequestPlatform() {
        try {
            HttpServletRequest request = getRequest();
            String value = Objects.isNull(request.getHeader(SystemConstant.HEADER_PLATFORM)) ? request.getParameter(SystemConstant.HEADER_PLATFORM) : request.getHeader(SystemConstant.HEADER_PLATFORM);
            return Platform.valueOf(value);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            throw ExceptionResultEnum.PLATFORM_INVALID.exception();
        }
    }

    /**
     * 获取请求的deviceId
     *
     * @return
     */
    public static String getRequestDeviceId() {
        try {
            HttpServletRequest request = getRequest();
            return Objects.isNull(request.getHeader(SystemConstant.HEADER_DEVICE_ID)) ? request.getParameter(SystemConstant.HEADER_DEVICE_ID) : request.getHeader(SystemConstant.HEADER_DEVICE_ID);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            throw ExceptionResultEnum.DEVICE_ID_INVALID.exception();
        }
    }

    /**
     * 获取请求的Authorization
     *
     * @return
     */
    public static String getRequestAuthorization() {
        try {
            HttpServletRequest request = getRequest();
            return Objects.isNull(request.getHeader(SystemConstant.HEADER_AUTHORIZATION)) ? request.getParameter(SystemConstant.HEADER_AUTHORIZATION) : request.getHeader(SystemConstant.HEADER_AUTHORIZATION);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            throw ExceptionResultEnum.AUTHORIZATION_INVALID.exception();
        }
    }

    /**
     * 获取请求的Authorization
     *
     * @return
     */
    public static Long getRequestTime() {
        try {
            HttpServletRequest request = getRequest();
            String time = Objects.isNull(request.getHeader(SystemConstant.HEADER_TIME)) ? request.getParameter(SystemConstant.HEADER_TIME) : request.getHeader(SystemConstant.HEADER_TIME);
            return Objects.nonNull(time) ? Long.parseLong(time) : null;
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            throw ExceptionResultEnum.TIME_INVALID.exception();
        }
    }

    /**
     * 获取请求的Session
     *
     * @return
     */
    public static Object getRequestSession() {
        Object object = getRequest().getAttribute(SystemConstant.SESSION);
        if (Objects.isNull(object)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        return object;
    }

    /**
     * 获取请求的用户
     *
     * @return
     */
    public static Long getRequestUserId() {
        Object object = getRequest().getHeader(SystemConstant.USER_ID);
        if (Objects.isNull(object)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        return Long.parseLong(object.toString());
    }

    /**
     * 获取请求的用户
     *
     * @return
     */
    public static Object getRequestUser() {
        Object object = getRequest().getAttribute(SystemConstant.USER);
        if (Objects.isNull(object)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        return object;
    }

    /**
     * 获取header中schoolId
     *
     * @return
     */
    public static Object getRequestHeaderSchoolId() {
//        BasicSchool basicSchool = (BasicSchool) getRequestSchool();
//        return basicSchool.getId();
        Object object = getRequest().getHeader(SystemConstant.SCHOOL_ID);
        if (Objects.isNull(object)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        return object;
    }

    /**
     * 获取header中schoolId
     *
     * @return
     */
    public static Object getRequestHeaderSchoolIdByNotVaild() {
        return getRequest().getHeader(SystemConstant.SCHOOL_ID);
    }

    /**
     * 获取请求的学校
     *
     * @return
     */
    public static Object getRequestSchool() {
        Object object = getRequest().getAttribute(SystemConstant.SCHOOL);
        if (Objects.isNull(object)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        return object;
    }

    /**
     * 获取请求的学校
     *
     * @return
     */
    public static Object getRequestSchoolByNotVaild() {
        return getRequest().getAttribute(SystemConstant.SCHOOL);
    }

    /**
     * 获取请求的机构
     *
     * @return
     */
    public static Object getRequestOrg() {
        Object object = getRequest().getAttribute(SystemConstant.ORG);
        if (Objects.isNull(object)) {
            throw ExceptionResultEnum.NOT_LOGIN.exception();
        }
        return object;
    }

    /**
     * 获取请求的md5
     *
     * @return
     */
    public static String getRequestMd5() {
        String md5 = getRequest().getHeader(SystemConstant.MD5.toLowerCase());
        if (Objects.isNull(md5)) {
            throw ExceptionResultEnum.MD5_EMPTY.exception();
        }
        return md5;
    }

    /**
     * 设置id
     *
     * @param ids
     * @return
     */
    public static void setRequestId(List<Long> ids) {
        HttpServletRequest request = getRequest();
        request.setAttribute(SystemConstant.ID, ids);
    }

    /**
     * 获取id
     *
     * @return
     */
    public static List<Long> getRequestId() {
        return Objects.nonNull(getRequest().getAttribute(SystemConstant.ID)) ? (List<Long>) getRequest().getAttribute(SystemConstant.ID) : null;
    }

    /**
     * 获取当前请求的菜单ID
     */
    public static Long getCurrentPrivilegeId() {
        try {
            HttpServletRequest request = getRequest();
            String currentPrivilegeId = request.getHeader(SystemConstant.CURRENT_PRIVILEGE_ID);
            return StringUtils.isBlank(currentPrivilegeId) ? null : Long.valueOf(currentPrivilegeId);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            throw ExceptionResultEnum.PRIVILEGE_ID_INVALID.exception();
        }
    }

    /**
     * 获取HttpServletRequest
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    /**
     * 获取HttpServletResponse
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    /***
     * 获取客户端ip地址
     */
    public static String getIP() {
        HttpServletRequest request = getRequest();
        String ipStr = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipStr) || "unknown".equalsIgnoreCase(ipStr)) {
            ipStr = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ipStr.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ipStr = str;
                break;
            }
        }
        //目的是将localhost访问对应的ip 0:0:0:0:0:0:0:1 转成 127.0.0.1。
        return ipStr.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ipStr;
    }

    /**
     * excludeProxyIp
     *
     * @param request        request
     * @param excludeProxyIp 是否排除代理ip
     * @return ip
     */
    public static String getRemoteIp(HttpServletRequest request, boolean excludeProxyIp) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-real-ip");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (excludeProxyIp) {
            //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ip != null && ip.length() > 15) { //"***.***.***.***".length() = 15
                if (ip.indexOf(",") > 0) {
                    ip = ip.substring(0, ip.indexOf(","));
                }
            }
        }
        return ip;
    }
}
