import db from '@/utils/db'
import type { PiniaPluginContext, StateTree, Store } from 'pinia'

const cache = ['user']

function getStoreKey(key: string) {
  return `store_${key}`
}

// 解析数据同步到state
function hydrateStore(store: Store, key: string) {
  try {
    const data = db.get(getStoreKey(key))
    if (!data) return
    store.$patch(data)
  } catch (err) {
    console.error(err)
  }
}

// 序列化之后存储到storage
function persistState(state: StateTree, key: string) {
  try {
    db.set(getStoreKey(key), state)
  } catch (err) {
    console.error(err)
  }
}

function PiniaPluginPersist(context: PiniaPluginContext) {
  const { store } = context
  // 没包含的就不缓存
  if (!cache.includes(store.$id)) return

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

export default PiniaPluginPersist
