// 定义key名
const USER_INFO_KEY = 'wx_user_info'
const TOKEN_KEY = 'wx_token'
const SEARCH_HISTORY_KEY = 'search_history'
const Collect_HISTORY_KEY = 'collect_goods_key'
const HasAddFriend = 'has_add_guide'
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 saveSearchHistory (value) {
  let historys = loadSearchHistory() || []
  historys = historys.filter(item => item !== value)
  historys.unshift(value)
  return saveStorage(SEARCH_HISTORY_KEY, historys.slice(0, 10))
}

export function loadSearchHistory () {
  return loadStorage(SEARCH_HISTORY_KEY)
}

export function removeSearchHistory () {
  return removeStorage(SEARCH_HISTORY_KEY)
}

export function saveCollectHistory (goods) {
  let historys = loadCollectHistory() || []
  historys = historys.filter(item => item.id !== goods.id)
  historys.unshift(goods)
  return saveStorage(Collect_HISTORY_KEY, historys)
}

export function loadCollectHistory (goods_id) {
  let arr = loadStorage(Collect_HISTORY_KEY) ? loadStorage(Collect_HISTORY_KEY) : []
  let result = arr
  if (goods_id) {
    result = arr.find(item => item.id == goods_id)
  }
  return result
}

export function removeCollect (goods_id) {
  let historys = loadCollectHistory() || []
  historys = historys.filter(item => item.id !== goods_id)
  return saveStorage(Collect_HISTORY_KEY, historys)
}

export function saveHasAddFriend () {
  return saveStorage(HasAddFriend, true)
}

export function loadHasAddFriend () {
  return loadStorage(HasAddFriend)
}

export function removeHasAddFriend () {
  return removeStorage(HasAddFriend)
}