/**
 * 保存时间戳，设置过期时间
 * @param {String} kind [大类]
 * @param {String} key [key值]
 * @param {*} value
 */

export function setLocalStorageAndTime (kind, key, value) {
  const data = localStorage.getItem(kind)
  if (!data || data === 'undefined') {
    localStorage.setItem(kind, JSON.stringify({ [key]: { data: value, time: new Date().getTime() } }))
    return
  }
  const obj = JSON.parse(data)
  obj[key] = { data: value, time: new Date().getTime() }
  localStorage.setItem(kind, JSON.stringify(obj))
}

// 默认过期时间随机一至两小时
export function getLocalStorageAndTime (kind, key, exp = 3600 * 1000 * (Math.random() + 1)) {
  // 获取数据
  const data = localStorage.getItem(kind)
  if (!data) return null
  const dataObj = JSON.parse(data)
  if (!dataObj[key]) return null
  // 与过期时间比较
  if (new Date().getTime() - dataObj[key].time > exp) {
    // 过期删除返回null
    dataObj[key] = null
    localStorage.setItem(kind, JSON.stringify(dataObj))
    return null
  } else {
    return dataObj[key].data
  }
}
