import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义用户信息接口类型
export interface UserInfo {
  userId?: string | number;
  userName?: string;
  schoolId?: string | number;
  schoolName?: string;
  accountName?: string; // 登录账号名称
  phone?: string;       // 手机号
  [key: string]: any;   // 允许其他额外字段
}
//用户相关的状态管理
export const useUserStore = defineStore('user', () => {
  // State
  const schoolLogo = ref<string>('')
  
  // 如果需要管理 userInfo，也可以放在这里，但通常 userInfo 存在 localStorage 中
  const userInfo = ref<UserInfo>(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  // Getters (可选，如果需要计算属性)
  const hasLogo = computed(() => !!schoolLogo.value)

  //便捷获取用户具体信息的getters
  const userId = computed(() => userInfo.value.userId)
  const userName = computed(() => userInfo.value.userName)
  const schoolId = computed(() => userInfo.value.schoolId)
  const schoolName = computed(() => userInfo.value.schoolName)
  const accountName = computed(() => userInfo.value.accountName)
  const phone = computed(() => userInfo.value.phone)

  // Actions
  function setSchoolLogo(logo: string) {
    schoolLogo.value = logo
  }

  // 新增：设置用户信息
  function setUserInfo(info: UserInfo) {
    userInfo.value = info
    // 同步存储到 localStorage，确保持久化
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  // 新增：更新部分用户信息
  function updateUserInfo(partialInfo: Partial<UserInfo>) {
    userInfo.value = { ...userInfo.value, ...partialInfo }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  // 清除用户状态
  function clearUserState() {
    schoolLogo.value = ''
    userInfo.value = {}
    // 清除 localStorage 中的用户信息
    localStorage.removeItem('userInfo')
  }

  return {
    schoolLogo,
    hasLogo,
    setSchoolLogo,

    // 返回新增的用户相关状态和方法
    userInfo,
    userId,
    userName,
    schoolId,
    schoolName,
    accountName,
    phone,
    setUserInfo,
    updateUserInfo,
    clearUserState
  }
})