import store from "@/store";

/**
 * 获取用户
 * @returns {String}
 */
export function getUserInfo() {
  return JSON.parse(sessionStorage.getItem("user_info")) || {};
}

/**
 * 获取token失效时间
 * @returns {String}
 */
export function tokenDate() {
  return getUserInfo().expireTime;
}

/**
 * 获取token
 * @returns {String}
 */
export function getToken() {
  return getUserInfo().token || "";
}
/**
 * 获取企业token
 * @returns {String}
 */
export function getEnToken() {
  console.log("获取企业token", sessionStorage.getItem("enToken"));
  return sessionStorage.getItem("enToken") || "";
}
/**
 * 获取用户权限节点
 * @returns {*}
 */
export function getUserAccess() {
  return JSON.parse(sessionStorage.getItem("nodes")) || [];
}
/**
 * 获取用户数据域权限
 * @returns {*}
 */
export function getDataField() {
  return sessionStorage.getItem("dataField")
    ? JSON.parse(sessionStorage.getItem("dataField"))
    : { dataField: 3 };
}
/**
 * 获取用户数据域权限radio
 * @returns {*}
 */
export function getDataFieldRadio() {
  return getDataField().dataField || 3;
}

/**
 * 是否超级管理员
 * @returns {boolean}
 */
export function isSuperAdmin() {
  if (sessionStorage.getItem("isSuper") === null) {
    return true;
  } else {
    return !!JSON.parse(sessionStorage.getItem("isSuper"));
  }
}

/**
 * 检查路由权限
 * @param route
 * @returns {boolean}
 */
export function checkRouterAccess(route) {
  if (isSuperAdmin()) {
    return true;
  }
  const {
    meta: { access },
  } = route;
  if (access === undefined) {
    return true;
  }
  const roles = getUserAccess();
  return checkAccess(access, roles);
}

/**
 * 检查操作权限
 * @param role
 * @returns {boolean}
 */
export function checkActionAccess(role) {
  if (isSuperAdmin()) {
    return true;
  }
  if (role === undefined) {
    return true;
  }
  const roles = getUserAccess();
  return checkAccess(role, roles);
}

/**
 * 检查权限
 * @param role
 * @param rolescheckRouterAccess
 * @returns {boolean}
 */
export function checkAccess(role, roles = []) {
  let isCheck = false;
  for (let i in roles) {
    const item = roles[i];
    if (item === role) {
      isCheck = true;
      break;
    }
  }
  return isCheck;
}
