import Taro from "@tarojs/taro";

const postfix = "_lapse_time";

/**
 * 设置时效缓存
 * @param key 缓存key值
 * @param value 缓存数据
 * @param second 缓存时效时间（单位：秒，不填则默认3600s）
 */
export function setStorageSyncSecond<T>(key: string, value: T, second = 3600) {
  Taro.setStorageSync(key, value);

  if (!second) {
    Taro.removeStorageSync(`${key}${postfix}`);
    return;
  }

  const timestamp = Date.parse(String(new Date())) / 1000 + second;
  Taro.setStorageSync(`${key}${postfix}`, timestamp);
}

/**
 * 读取缓存，若缓存不存在，返回null
 * @param key 缓存key
 */
export function getStorageSyncTime<T>(key: string): T | null {
  const deadTime = Taro.getStorageSync(`${key}${postfix}`);
  const currentSecond = Date.parse(String(new Date())) / 1000;

  if (deadTime && deadTime < currentSecond) {
    Taro.removeStorageSync(key);
    Taro.removeStorageSync(`${key}${postfix}`);
    return null;
  }

  const data = Taro.getStorageSync(key);

  return data || null;
}

/**
 * 移除缓存
 */
export function removeStorageSync(key: string) {
  Taro.removeStorageSync(key);
}
