import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { UserInfo } from '@/types/user'
import type { useInfoResult } from '@/types/login'

export const user = defineStore(
  'user',
  () => {
    const info = ref<useInfoResult>() // 用户信息
    const token = ref('')
    const role = ref(0) // 用户角色
    const permissions = ref<string[]>([]) // 权限
    const parkId = ref('') // 服务区或者停车区id
    // 存储用户信息
    const setUserInfo = (val: useInfoResult) => {
      info.value = val
      role.value = val.type
    }
    const setToken = (val: string) => {
      token.value = val
    }
    const setPermissions = (val: string[]) => {
      permissions.value = val
    }
    const setParkId = (val: string) => {
      parkId.value = val
    }
    // 清空所有信息
    const clearInfo = () => {
      info.value = {} as useInfoResult
      token.value = ''
      role.value = 0
      permissions.value = []
      parkId.value = ''
    }
    return {
      info,
      token,
      role,
      permissions,
      setPermissions,
      setToken,
      setUserInfo,
      setParkId,
      clearInfo
    }
  },
  // 持久化配置
  {
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          uni.setStorageSync(key, value)
        }
      }
    }
  }
)
