import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '@/api/auth'
import type { User, LoginRequest } from '@/types'
import { OrganizationalLevel, OrganizationalLevelValue } from '@/types'

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const initialized = ref(false)

  // 只检查token是否存在
  const isAuthenticated = computed(() => !!token.value)
  
  // 获取组织级别的数值（用于权限比较）
  const organizationalLevelNum = computed(() => {
    if (!user.value?.organizationalLevel) return 4
    return OrganizationalLevelValue[user.value.organizationalLevel] ?? 4
  })
  
  const canManageSubordinates = computed(() => organizationalLevelNum.value < 4)
  
  const canCreateAllocations = computed(() => organizationalLevelNum.value === 1)
  
  const canApprove = computed(() => organizationalLevelNum.value < 4)

  async function login(credentials: LoginRequest): Promise<boolean> {
    try {
      const response = await authApi.login(credentials)
      token.value = response.token
      user.value = {
        id: response.userId,
        username: response.username,
        displayName: response.displayName,
        organizationalUnitId: response.organizationalUnitId,
        organizationalUnitName: response.organizationalUnitName,
        organizationalLevel: response.organizationalLevel
      }
      localStorage.setItem('token', response.token)
      initialized.value = true
      return true
    } catch {
      return false
    }
  }

  async function logout(): Promise<void> {
    try {
      await authApi.logout()
    } catch {
      // 忽略登出错误
    } finally {
      token.value = null
      user.value = null
      initialized.value = false
      localStorage.removeItem('token')
    }
  }

  async function fetchProfile(): Promise<boolean> {
    if (!token.value) {
      initialized.value = true
      return false
    }
    try {
      const response = await authApi.getProfile()
      user.value = {
        id: (response as any).userId,
        username: response.username,
        displayName: response.displayName,
        organizationalUnitId: response.organizationalUnitId,
        organizationalUnitName: response.organizationalUnitName,
        organizationalLevel: response.organizationalLevel
      }
      initialized.value = true
      return true
    } catch {
      // token无效，清除
      token.value = null
      user.value = null
      localStorage.removeItem('token')
      initialized.value = true
      return false
    }
  }

  function hasPermission(requiredLevel: number): boolean {
    return organizationalLevelNum.value <= requiredLevel
  }

  return {
    user,
    token,
    initialized,
    isAuthenticated,
    organizationalLevel: computed(() => user.value?.organizationalLevel),
    organizationalLevelNum,
    unitId: computed(() => user.value?.organizationalUnitId),
    canManageSubordinates,
    canCreateAllocations,
    canApprove,
    login,
    logout,
    fetchProfile,
    hasPermission
  }
})
