import Cookies from 'js-cookie';

const TokenKey = 'GCLS_Token';

export function getSessionID() {
  const token = Cookies.get(TokenKey) || sessionStorage.getItem(TokenKey) || localStorage.getItem(TokenKey);
  const _token = token ? JSON.parse(token) : null;
  return _token ? _token.session_id ?? '' : '';
}

/**
 * 获取 token
 * @returns {object | null}
 */
export function getToken() {
  const token = Cookies.get(TokenKey) || sessionStorage.getItem(TokenKey) || localStorage.getItem(TokenKey);
  return token ? JSON.parse(token) : null;
}

/**
 * 设置 token
 * @param {object} token
 */
export function setToken(token) {
  const _token = typeof token === 'object' ? JSON.stringify(token) : '';
  sessionStorage.setItem(TokenKey, _token);
  localStorage.setItem(TokenKey, _token);
  Cookies.set(TokenKey, _token);
}

/**
 * 删除 token
 */
export function removeToken() {
  localStorage.removeItem(TokenKey);
  sessionStorage.removeItem(TokenKey);
  Cookies.remove(TokenKey);
}

// 系统信息
const ConfigKey = 'GCLS_Config';

export function getConfig() {
  const config = Cookies.get(ConfigKey) || sessionStorage.getItem(ConfigKey) || localStorage.getItem(ConfigKey);
  return config ? JSON.parse(config) : null;
}

export function setConfig(value) {
  let _val = typeof value === 'object' ? JSON.stringify(value) : '';
  localStorage.setItem(ConfigKey, _val);
  sessionStorage.setItem(ConfigKey, _val);
  Cookies.set(ConfigKey, _val);
}

export function removeConfig() {
  localStorage.removeItem(ConfigKey);
  sessionStorage.removeItem(ConfigKey);
  Cookies.remove(ConfigKey);
}
