const storage = {
  setCookie(cName: string, value: any, expiredays: any) {
    const exdate = new Date().setDate(new Date().getDate() + expiredays);
    document.cookie = cName + '=' + value + (expiredays === null ? '' : ';expires=' + exdate); //.toGMTString()
  },
  getCookie(cName: string) {
    if (document.cookie.length > 0) {
      let cStart;
      let cEnd;
      cStart = document.cookie.indexOf(cName + '=');
      if (cStart !== -1) {
        cStart = cStart + cName.length + 1;
        cEnd = document.cookie.indexOf(';', cStart);
        if (cEnd === -1) {
          cEnd = document.cookie.length;
        }
        return document.cookie.substring(cStart, cEnd);
      }
    }
    return '';
  }
};

/**
 * 存储数据
 */
export const setItem = (key: string, value: string) => {
  // 将数组、对象类型的数据转化为 JSON 字符串进行存储
  if (typeof value === 'object') {
    value = JSON.stringify(value);
  }
  window.localStorage.setItem(key, value);
};

/**
 * 获取数据
 */
export const getItem = (key: string) => {
  const data = window.localStorage.getItem(key);
  try {
    return JSON.parse(data as string);
  } catch (err) {
    return data;
  }
};

/**
 * 删除数据
 */
export const removeItem = (key: string) => {
  window.localStorage.removeItem(key);
};

/**
 * 删除所有数据
 */
export const removeAllItem = () => {
  window.localStorage.clear();
};

export default storage;
