import { ref, watch } from "vue";
/**
 * 临时localStorage缓存，使用后立即删除，适合跨页面使用
 */
const TemKel = "_t";
/**
 * 设置缓存超时
 */
const base_time = 1000 * 60 * 60 * 8;
type Tem = {
  [key: string]: {
    time: number;
    val: TemObj;
  };
};
export function initilTemItem() {
  const tem: Tem = JSON.parse(localStorage.getItem(TemKel) || "{}");
  const _time = Date.now();
  const _tem: Tem = {};
  for (let key in tem) {
    const val = tem[key];
    if (_time - val.time < base_time) {
      _tem[key] = val;
    }
  }

  localStorage.setItem(TemKel, JSON.stringify(_tem));
}
export type TemObj = {
  id: string;
  url: string;
  name: string;
  isEdit: boolean;
};
export function setTemItem(
  val: TemObj,
  time: Number = Date.now() + base_time,
): string {
  const key = `_t${Date.now()}${Math.floor(Math.random() * 100000)}`;
  let Tem: Tem = {};
  try {
    Tem = JSON.parse(localStorage.getItem(TemKel) || "{}");
  } catch (error) {}
  Tem[key] = {
    time: Date.now(),
    val: val,
  };
  localStorage.setItem(TemKel, JSON.stringify(Tem));

  return key;
}
export function getTemItem(key: string): TemObj | null {
  let Tem: Tem = {};
  try {
    Tem = JSON.parse(localStorage.getItem(TemKel) || "{}");
    return Tem[key].val;
  } catch (error) {}
  return null;
}
/**
 *
 * @param val 默认值
 */
export function getCacheVal(key: string, defaultVal: any) {
  const _val = ref(Number(localStorage.getItem(key) || defaultVal));
  watch(
    () => _val.value,
    () => {
      localStorage.setItem(key, `${_val.value}`);
    },
  );
  return _val;
}
