// 定义key名
const USER_INFO_KEY = 'wx_user_info'
const TOKEN_KEY = 'wx_token'
const VIEW_HISTORY_KEY = 'view_history'

function saveStorage (key, value, expired = 0) {
  const storage = {
    value
  }
  // 设置过期时间
  if (expired) {
    storage.expired = new Date().getTime() + expired * 1000
  }
  try {
    return wx.setStorageSync(key, storage)
  } catch (e) {
    console.log(e, `save ${key} storage err`)
  }
}

function loadStorage (key) {
  try {
    const storage = wx.getStorageSync(key)
    // 过期
    if (storage.expired && storage.expired <= new Date().getTime) {
      storage.value = ''
      removeStorage(key)
    }
    return storage.value
  } catch (e) {
    console.log(e, `load ${key} storage err`)
  }
}

function removeStorage (key) {
  try {
    return wx.removeStorageSync(key)
  } catch (e) {
    console.log(e, `remove ${key} storage err`)
  }
}

export function saveUserInfo (userinfo) {
  return saveStorage(USER_INFO_KEY, userinfo, 86400 / 24)
}

export function loadUserInfo () {
  return loadStorage(USER_INFO_KEY)
}

export function removeUserInfo () {
  return removeStorage(USER_INFO_KEY)
}

export function saveToken (token) {
  return saveStorage(TOKEN_KEY, token, 86400 / 24)
}

export function loadToken () {
  return loadStorage(TOKEN_KEY)
}

export function removeToken () {
  return removeStorage(TOKEN_KEY)
}

export function saveViewHistory (house) {
  let historys = loadViewHistory() || []
  historys = historys.filter(item => item.house_id !== house.house_id)
  historys.unshift(house)
  return saveStorage(VIEW_HISTORY_KEY, historys)
}

export function loadViewHistory () {
  return loadStorage(VIEW_HISTORY_KEY)
}