/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.common.security.authentication;

import com.hzbank.testteam.autotest.dependencies.authDependency.constants.AuthDependencyConstants;
import com.hzbank.testteam.autotest.dependencies.authDependency.entity.User;
import com.hzbank.testteam.autotest.dependencies.authDependency.utils.RequestUtil;
import com.hzbank.testteam.autotest.dependencies.baseDefineDependency.utils.SpringUtil;
import net.northking.cctp.common.saas.SaaSContext;
import net.northking.cctp.common.saas.cache.StaticTenantCache;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;

import java.util.List;

/**
 * 当前操作用户
 *
 * @author : xiusong.xie
 * @version : 1.0
 */
public class NKSecurityContext
{
  private NKSecurityContext()
  {
  }


  public static String getUserId() {
    Long userId = null;

    if (RequestUtil.getRequestUserId() != null) {
      return String.valueOf(RequestUtil.getRequestUserId());
    } else if (RequestUtil.getUser() != null) {
      userId = RequestUtil.getUser().getId();
    }
    return userId == null ? null : String.valueOf(userId);
  }

  public static void setUserId(String userId)
  {
    User user = new User();
    user.setId(Long.parseLong(userId));
    RequestUtil.setUser(user);
  }

  public static void unload()
  {
    RequestUtil.setUser(null);
    SaaSContext.unload();
  }

  /**
   * 设置当前线程的 租户ID
   *
   * @param tenantId 租户ID
   */
  public static void setTenantId(String tenantId)
  {
    SaaSContext.setTenantId(tenantId);
  }

  /**
   * 获取当前线程的 租户ID
   *
   * @return 租户ID
   */
  public static String getTenantId()
  {
   return StaticTenantCache.getDefaultTenantId();
  }

  public static void setDomains(String domains)
  {
    SaaSContext.setDomains(domains);
  }

  public static String getDomains()
  {
    return SaaSContext.getDomains();
  }

  public static List<String> getTokensByUserId(String userId)  {
    RedissonClient redisson = SpringUtil.getBean(RedissonClient.class);
    RBucket<List<String>> userIdTokensBucket = redisson.getBucket(AuthDependencyConstants.USER_ID_TOKENS_PREFIX + userId);
    List<String> tokens = userIdTokensBucket.get();
    return tokens;
  }
}
