const keys = ["paper"];
// 解析数据同步到state
function hydrateStore(store, key) {
  if (!keys.includes(key)) return;
  const fromStorage = localStorage.getItem(`store_${key}`);
  if (fromStorage) {
    try {
      store.$patch(JSON.parse(fromStorage));
    } catch (err) {
      console.error(err);
    }
  }
}
// 序列化之后存储到storage
function persistState(state, key) {
  try {
    if (!keys.includes(key)) return;
    localStorage.setItem(`store_${key}`, JSON.stringify(state));
  } catch (err) {
    console.error(err);
  }
}

export function CachePiniaPlugin(context) {
  const { store } = context;
  hydrateStore(store, store.$id);
  // 监听数据变化
  store.$subscribe(
    (mutation, state) => {
      persistState(state, store.$id);
    },
    {
      // 组件销毁时，当前监听不会被销毁
      detached: true,
    }
  );
}
