package com.tianji.common.utils;


import com.tianji.common.constants.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Collection;
import java.util.Map;

@Slf4j
public class WebUtils {

    /**
     * 获取ServletRequestAttributes
     *
     * @return ServletRequestAttributes
     */
    public static ServletRequestAttributes getServletRequestAttributes() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        if (ra == null) {
            return null;
        }
        return (ServletRequestAttributes) ra;
    }

    /**
     * 获取request
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
        return servletRequestAttributes == null ? null : servletRequestAttributes.getRequest();
    }

    /**
     * 获取response
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
        return servletRequestAttributes == null ? null : servletRequestAttributes.getResponse();
    }

    /**
     * 获取request header中的内容
     *
     * @param headerName 请求头名称
     * @return 请求头的值
     */
    public static String getHeader(String headerName) {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        return request.getHeader(headerName);
    }

    public static void setResponseHeader(String key, String value) {
        HttpServletResponse response = getResponse();
        if (response == null) {
            return;
        }
        response.setHeader(key, value);
    }


    public static String getRequestId() {
        return getHeader(Constant.REQUEST_ID_HEADER);
    }

    public static boolean isGatewayRequest() {
        String originName = getHeader(Constant.REQUEST_FROM_HEADER);
        return Constant.GATEWAY_ORIGIN_NAME.equals(originName);
    }

    public static boolean isFeignRequest() {
        String originName = getHeader(Constant.REQUEST_FROM_HEADER);
        return Constant.FEIGN_ORIGIN_NAME.equals(originName);
    }

    public static boolean isSuccess() {
        HttpServletResponse response = getResponse();
        return response != null && response.getStatus() < 300;
    }

    /**
     * 获取请求地址中的请求参数组装成 key1=value1&key2=value2
     * 如果key对应多个值，中间使用逗号隔开例如 key1对应value1，key2对应value2，value3， key1=value1&key2=value2,value3
     *
     * @param request
     * @return 返回拼接字符串
     */
    public static String getParameters(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        return getParameters(parameterMap);
    }

    /**
     * 获取请求地址中的请求参数组装成 key1=value1&key2=value2
     * 如果key对应多个值，中间使用逗号隔开例如 key1对应value1，key2对应value2，value3， key1=value1&key2=value2,value3
     *
     * @param queries
     * @return
     */
    public static <T> String getParameters(final Map<String, T> queries) {
        StringBuffer buffer = new StringBuffer();
        for (Map.Entry<String, T> entry : queries.entrySet()) {
            if (entry.getValue() instanceof String[]) {
                buffer.append(entry.getKey()).append(String.join(",", ((String[]) entry.getValue())))
                        .append("&");
            } else if (entry.getValue() instanceof Collection) {
                buffer.append(entry.getKey()).append(
                        CollUtils.join(((Collection<String>) entry.getValue()), ",")
                ).append("&");
            }
        }
        return buffer.length() > 0 ? buffer.substring(0, buffer.length() - 1) : StringUtils.EMPTY;
    }

    /**
     * 获取请求url中的uri
     *
     * @param url
     * @return
     */
    public static String getUri(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }

        String uri = url;
        //uri中去掉 http:// 或者https
        if (uri.contains("http://")) {
            uri = uri.replace("http://", StringUtils.EMPTY);
        } else if (uri.contains("https://")) {
            uri = uri.replace("https://", StringUtils.EMPTY);
        }

        int endIndex = uri.length(); //uri 在url中的最后一个字符的序号+1
        if (uri.contains("?")) {
            endIndex = uri.indexOf("?");
        }
        return uri.substring(uri.indexOf("/"), endIndex);
    }

    public static String getRemoteAddr() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return "";
        }
        return request.getRemoteAddr();
    }

    public static CookieBuilder cookieBuilder() {
        return new CookieBuilder(getRequest(), getResponse());
    }

    public static void setAttribute(String key, String value) {
        HttpServletRequest request = getRequest();
        if (null == request) {
            return;
        }
        request.setAttribute(key, value);
    }

    public static void removeAttribute(String key) {
        HttpServletRequest request = getRequest();
        if (null == request) {
            return;
        }
        request.removeAttribute(key);
    }

    public static Object getAttribute(String key) {
        HttpServletRequest request = getRequest();
        if (null == request) {
            return null;
        }
        return request.getAttribute(key);
    }
}
