import { useUserStore } from '@/store/user'
import { watch } from 'vue'

/**
 * 基于用户ID的响应式存储
 * 自动根据当前登录用户隔离数据
 *
 * @param key - 存储键名
 * @param defaultValue - 默认值
 * @returns 响应式引用
 *
 * @example
 * const selectedExamId = useUserStorage('selectedExamId', 0);
 * // 使用方式和普通 ref 完全一样
 * selectedExamId.value = 123;
 */
export function useUserStorage<T>(key: string, defaultValue: T) {
  const userStore = useUserStore()
  const valueRef = ref<T>(defaultValue)

  // 生成基于用户ID的存储键
  const getStorageKey = () => {
    const userId = userStore.info?.id || 'default'
    return `user_${userId}_${key}`
  }

  // 从 uni.storage 加载数据
  const loadFromStorage = () => {
    const storageKey = getStorageKey()
    const stored = uni.getStorageSync(storageKey)

    if (stored) {
      try {
        valueRef.value = JSON.parse(stored)
      }
      catch {
        // 如果是数字类型，直接转换
        if (typeof defaultValue === 'number') {
          valueRef.value = Number(stored) as T
        }
        else {
          valueRef.value = stored as T
        }
      }
    }
    else {
      valueRef.value = defaultValue
    }
  }

  // 保存到 uni.storage
  const saveToStorage = (value: T) => {
    const storageKey = getStorageKey()
    if (value === undefined || value === null || value === 0 || value === '') {
      uni.removeStorageSync(storageKey)
    }
    else {
      const toStore = typeof value === 'object' ? JSON.stringify(value) : String(value)
      uni.setStorageSync(storageKey, toStore)
    }
  }

  // 监听值变化，自动保存
  watch(valueRef, (newValue) => {
    saveToStorage(newValue)
  })

  // 监听用户变化，自动重新加载
  watch(
    () => userStore.info?.id,
    () => {
      loadFromStorage()
    },
    { immediate: true },
  )

  return valueRef
}

