import Cookies from 'js-cookie';
import { getUrlSearchQuery } from '@/utils';

const TokenKey = 'Admin-Token';
const Tenantid = 'Tenantid';

export function getToken() {
  return Cookies.get(TokenKey);
}
export function getTenantid() {
  return Cookies.get(Tenantid);
}

export function setToken(token) {
  return Cookies.set(TokenKey, token);
}
export function setTenantid(id) {
  return Cookies.set(Tenantid, id);
}

export function removeToken() {
  return Cookies.remove(TokenKey);
}

export function removeTenantid() {
  return Cookies.remove(Tenantid);
}

export function setBiAuth(token) {
  if (!token) return false;
  sessionStorage.setItem("DSK_SYSTEM_AUTH_TOKEN", token);
  return true;
}

/**
 * 获取第三方app key
 * @param {*} onlyUrl 是否仅从url获取
 * @returns
 */
export function getThirdPlatform(onlyUrl = false) {
  if (!onlyUrl) {
    const platForm = sessionStorage.getItem("PLAT_FORM");
    if (platForm) return platForm;
  }
  // sessiongStorage 未获取到appkey 寻找url上的参数
  const { platFormKey } = getUrlSearchQuery();
  if (platFormKey) {
    return platFormKey;
  } else {
    return "";
  };
}

/**
 * 检测 appkey是否存在变动
 * @param {*} appkey
 */
export function checkThirdPlatformChange(appkey) {
  const platForm = sessionStorage.getItem("PLAT_FORM");
  return platForm !== appkey;
}

/**
 * 储存第三方app key
 * @param {*} appkey
 * @returns
 */
export function setThirdPlatform(appkey) {
  try {
    if (!appkey) throw new Error("");
    sessionStorage.setItem("PLAT_FORM", appkey);
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * 移除第三方app key
 */
export function removeThirdPlatform() {
  sessionStorage.removeItem("PLAT_FORM");
}
