package com.blueland.common.core.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 用户工具类
 * @Date 2021/7/22 1:30 下午
 * @Created BigTian
 */
@Component
public class UserUtils {
    public static String getStaffCodeDefault(String staffCode) {
        HttpServletRequest request = getRequest();
        return Optional.ofNullable(request)
                .map(el -> el.getHeader("staffPostCode"))
                .orElse(staffCode);
    }

    public static String getStaffCode() {
        HttpServletRequest request = getRequest();
        return Optional.ofNullable(request)
                .map(el -> el.getHeader("staffPostCode"))
                .orElseThrow(() -> new RuntimeException("请求头缺少任岗编码"));
    }


    /**
     * 获取当前登录人的租户
     *
     * @return String 租户编码
     * @author bigtian
     * @createTime 2022/5/16 10:35
     * @since 6.0
     */
    public static String getTenantId() {
        HttpServletRequest request = getRequest();
        String tenantid = Optional.ofNullable(request)
                .map(el -> el.getHeader("tenantid"))
                .orElseThrow(() -> new RuntimeException("请求头中没有租户"));
        return tenantid;
    }
    public static String getTenantIdDefault() {
        HttpServletRequest request = getRequest();
        String tenantid = Optional.ofNullable(request)
                .map(el -> el.getHeader("tenantid"))
                .orElse("");
        return tenantid;
    }


    /**
     * 获取请求属性
     *
     * @return
     */
    public static ServletRequestAttributes getRequestAttr() {

        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = getRequestAttr();
        return Optional.ofNullable(attributes).
                map(ServletRequestAttributes::getRequest)
                .orElse(null);
    }

    /**
     * 获取response
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = getRequestAttr();
        return attributes.getResponse();
    }

    public static String getLang() {
        return getRequest().getLocale().getLanguage();
    }

}
