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

const noCache = [
  'urge',
  'groupPape',
  'home-red-point',
  'taskJump',
  'student-manage',
  'lead-task',
  'word-book-select',
  'share',
]

// 解析数据同步到state
function hydrateStore(store: Store, key: string) {
  const fromStorage = getCache(`store_${key}`)
  if (fromStorage) {
    try {
      store.$patch(JSON.parse(fromStorage))
    } catch (err) {
      console.error(err)
    }
  }
}
// 序列化之后存储到storage
function persistState(state: StateTree, key: string) {
  try {
    setCache(`store_${key}`, JSON.stringify(state))
  } catch (err) {
    console.error(err)
  }
}

function PiniaPluginPersist(context: PiniaPluginContext) {
  const { store } = context

  if (noCache.includes(store.$id)) return

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

export default PiniaPluginPersist
