import { validateNull } from '@utils/validate';

const keyName = 'platform_';
const expireTimeMs = 24 * 60 * 60 * 1000;
/**
 * 存储localStorage
 */
export const setStore = (name, content, sessionFlag = false) => {
  const obj = {
    dataType: typeof content,
    content: content,
    datetime: new Date().getTime()
  };
  if (sessionFlag) {
    window.sessionStorage.setItem(keyName + name, JSON.stringify(obj));
  } else {
    window.localStorage.setItem(keyName + name, JSON.stringify(obj));
  }
};

/**
 * 获取localStorage
 */
export const getStore = (name, sessionFlag = false) => {
  let storage = sessionFlag ? window.sessionStorage : window.localStorage;
  let obj = storage.getItem(keyName + name);
  let content;
  if (validateNull(obj)) {
    return;
  }
  try {
    obj = JSON.parse(obj);
  } catch {
    return obj;
  }
  if (obj.dataType === 'string') {
    content = obj.content;
  } else if (obj.dataType === 'number') {
    content = Number(obj.content);
  } else if (obj.dataType === 'object') {
    content = obj.content;
  }
  return content;
};

export const isExpired = (name, sessionFlag = false) => {
  let storage = sessionFlag ? window.sessionStorage : window.localStorage;
  let obj = storage.getItem(keyName + name);
  if (validateNull(obj)) {
    return true;
  }
  try {
    obj = JSON.parse(obj);
  } catch {
    return true;
  }
  return new Date().getTime() - obj.datetime > expireTimeMs;
};

/**
 * 删除localStorage
 */
export const removeStore = name => {
  window.localStorage.removeItem(keyName + name);
  window.sessionStorage.removeItem(keyName + name);
};

/**
 * 清空全部localStorage
 */
export const clearStore = () => {
  window.localStorage.clear();
  window.sessionStorage.clear();
};
