import { onActivated, ref } from 'vue'
import type { LoginState } from '@/api'

const cacheKey = '__loginState__'

export const useCacheState = () => {
  const initial = { phone: '', password: '', remember: false }
  const state = ref<LoginState & { remember: boolean }>(initial)
  const updateCacheState = () => {
    try {
      const stateStr = localStorage.getItem(cacheKey)
      if (stateStr) {
        const value = JSON.parse(stateStr)
        if (value.remember) {
          state.value = value
        } else {
          state.value = initial
        }
      } else {
        state.value = initial
      }
      console.log(state.value)
    } catch {}
  }
  updateCacheState()
  onActivated(updateCacheState)

  return [
    state,
    () => {
      if (state.value.remember) {
        localStorage.setItem(cacheKey, JSON.stringify(state.value))
      } else {
        localStorage.removeItem(cacheKey)
      }
    }
  ] as const
}
