package com.ibeetl.admin.core.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ibeetl.admin.core.conf.SpringWebMvcConfigurer;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreRole;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.rbac.UserLoginInfo;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;

/**
 * 保留用户会话，以方便在业务代码任何地方调用 {@link SpringWebMvcConfigurer}
 *
 * @author lijiazhi
 */
@Slf4j
public final class RequestContextThreadLocal {

  /*当前请求*/
  private static final String ACCESS_CURRENT_REQUEST = "request";

  /*当前用户*/
  private static final String ACCESS_CURRENT_USER = "core:user";

  /*当前登录用户所在部门*/
  private static final String ACCESS_CURRENT_ORG = "core:currentOrg";

  /*用户可选部门*/
  private static final String ACCESS_USER_ORGS = "core:orgs";

  /*用户角色*/
  private static final String ACCESS_USER_ROLES = "core:roles";

  private static final ThreadLocal<Map<String, Object>> CONTEXT =
      ThreadLocal.withInitial(HashMap::new);

  private static final Cache<Object, UserLoginInfo> CACHE = Caffeine.newBuilder().maximumSize(100)
      .expireAfterAccess(10,
          TimeUnit.MINUTES).recordStats().build();

  private RequestContextThreadLocal() {

  }

  public static void setUserRoles(List<CoreRole> roles) {

    CONTEXT.get().put(ACCESS_USER_ROLES, roles);
  }

  public static List<CoreRole> getUserRoles() {

    return Convert.toList(CoreRole.class, CONTEXT.get().get(ACCESS_USER_ROLES));
  }

  public static List<Long> getUserRoleIds() {

    return Convert.toList(CoreRole.class, CONTEXT.get().get(ACCESS_USER_ROLES)).stream()
        .map(CoreRole::getId).collect(
            Collectors.toList());
  }

  public static void setCurrentOrg(CoreOrg org) {

    CONTEXT.get().put(ACCESS_CURRENT_ORG, org);
  }

  public static CoreOrg getCurrentOrg() {

    return (CoreOrg) CONTEXT.get().get(ACCESS_CURRENT_ORG);
  }

  public static void setUserOrgs(List<CoreOrg> orgs) {

    CONTEXT.get().put(ACCESS_USER_ORGS, orgs);
  }

  public static List<CoreOrg> getUserOrgs() {

    return Convert.toList(CoreOrg.class, CONTEXT.get().get(ACCESS_USER_ORGS));
  }

  public static void setCurrentUser(CoreUser user) {

    CONTEXT.get().put(ACCESS_CURRENT_USER, user);
  }

  public static CoreUser getCurrentUser() {

    return (CoreUser) CONTEXT.get().get(ACCESS_CURRENT_USER);
  }

  public static void setLoginerInfo(UserLoginInfo loginerInfo) {

    CACHE.put(loginerInfo.getUser().getId(), loginerInfo);
    setCurrentUser(loginerInfo.getUser());
    setCurrentOrg(loginerInfo.getCurrentOrg());
    setUserOrgs(loginerInfo.getOrgs());
    setUserRoles(loginerInfo.getRoles());
  }

  public static void reset(Object uid) {
    UserLoginInfo loginerInfo = CACHE.getIfPresent(Convert.toLong(uid, null));
    if (Objects.isNull(loginerInfo)) {
      return;
    }
    setLoginerInfo(loginerInfo);
  }

  public static void clearAllSession() {

  }

  public static void destory() {

    CONTEXT.get().clear();
    CONTEXT.remove();
  }

  public static Cookie getCookie(String cookieName) {

    Assert.notNull(cookieName);
    Cookie[] cookies = getRequest().getCookies();
    return Arrays.stream(cookies)
        .filter(cookie -> StrUtil.equals(cookie.getName(), cookieName))
        .findFirst()
        .orElse(null);
  }

  public static Object getSessionValue(String attr) {

    return getSession().getAttribute(attr);
  }

  public static void setSessionValue(String attr, Object obj) {

    getRequest().getSession().setAttribute(attr, obj);
  }

  public static String getAuthorization() {

    return getRequest().getHeader(HttpHeaders.AUTHORIZATION);
  }

  /** @return 请求的uri，域名与参数之间的那部分 */
  public static String getRequestUri() {

    return getRequest().getRequestURI();
  }

  /** @return 获取客户端ip */
  public static String getRequestIp() {

    return getIpAddr(getRequest());
  }

  public static void setRequest(HttpServletRequest request) {

    CONTEXT.get().put(ACCESS_CURRENT_REQUEST, request);
  }

  private static HttpServletRequest getRequest() {

    return (HttpServletRequest) CONTEXT.get().get(ACCESS_CURRENT_REQUEST);
  }

  public static HttpSession getSession() {

    return getRequest().getSession();
  }

  /**
   * 获取当前网络ip
   */
  public static String getIpAddr(HttpServletRequest request) {

    String ipAddress = request.getHeader("x-forwarded-for");
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
      ipAddress = request.getRemoteAddr();
      if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
        // 根据网卡取本机配置的IP
        InetAddress inet = null;
        try {
          inet = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
          e.printStackTrace();
        }
        ipAddress = inet.getHostAddress();
      }
    }
    // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
    if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
      if (ipAddress.indexOf(",") > 0) {
        ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
      }
    }
    return ipAddress;
  }

}
