const redis= "redis"

/**
 * 设置存储
 * k 键key
 * v 值value
 * t 秒
 */
function setStorage(k, v, t) {
  wx.setStorageSync(k, v);
  var seconds = parseInt(t);
  if (seconds > 0) {
    var newtime = Date.parse(new Date());
    newtime = newtime / 1000 + seconds;
    wx.setStorageSync(k + redis, `${newtime}`);
  } else {
    wx.removeStorageSync(k + redis);
  }
}

/**
 * 获取存储
 * k 键key
 */
function getStorage(k) {
  var deadtime = parseInt(wx.getStorageSync(k + redis));
  if (deadtime) {
    if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
      wx.removeStorageSync(k);
      return null;
    }
  }
  var res = wx.getStorageSync(k);
  if (res) {
    return res;
  }
  return null;
}

/**
 * 删除存储
 */
function removeStorage(k) {
  wx.removeStorageSync(k);
  wx.removeStorageSync(k + redis);
}

/**
 * 清除所有存储
 */
function clear() {
  wx.clearStorageSync();
}

module.exports = {
  setStorage,
  getStorage,
  removeStorage,
  clear,
};
