import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI } from '@/services/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref(null)
  const token = ref(localStorage.getItem('auth_token') || null)
  const permissions = ref([])
  const roles = ref([])
  const isLoading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const userRole = computed(() => user.value?.role || 'guest')
  const userName = computed(() => user.value?.name || '未知用户')
  const userAvatar = computed(() => user.value?.avatar || '/default-avatar.png')

  // 权限检查
  const hasPermission = computed(() => (permission) => {
    if (!permissions.value.length) return false
    return permissions.value.includes(permission) || permissions.value.includes('*')
  })

  const hasRole = computed(() => (role) => {
    if (!roles.value.length) return false
    return roles.value.includes(role) || roles.value.includes('admin')
  })

  const hasAnyRole = computed(() => (roleList) => {
    if (!roles.value.length) return false
    return roleList.some(role => roles.value.includes(role))
  })

  // 动作
  const login = async (credentials) => {
    try {
      isLoading.value = true
      const response = await authAPI.login(credentials)
      
      if (response.success) {
        token.value = response.data.token
        user.value = response.data.user
        permissions.value = response.data.permissions || []
        roles.value = response.data.roles || []
        
        // 存储到本地存储
        localStorage.setItem('auth_token', token.value)
        localStorage.setItem('user_info', JSON.stringify(user.value))
        localStorage.setItem('user_permissions', JSON.stringify(permissions.value))
        localStorage.setItem('user_roles', JSON.stringify(roles.value))
        
        return { success: true, message: '登录成功' }
      } else {
        return { success: false, message: response.message || '登录失败' }
      }
    } catch (error) {
      console.error('登录错误:', error)
      return { success: false, message: '网络错误，请稍后重试' }
    } finally {
      isLoading.value = false
    }
  }

  const logout = async () => {
    try {
      // 调用后端登出接口
      if (token.value) {
        await authAPI.logout()
      }
    } catch (error) {
      console.error('登出错误:', error)
    } finally {
      // 清除本地状态
      user.value = null
      token.value = null
      permissions.value = []
      roles.value = []
      
      // 清除本地存储
      localStorage.removeItem('auth_token')
      localStorage.removeItem('user_info')
      localStorage.removeItem('user_permissions')
      localStorage.removeItem('user_roles')
    }
  }

  const refreshToken = async () => {
    try {
      const response = await authAPI.refreshToken()
      if (response.success) {
        token.value = response.data.token
        localStorage.setItem('auth_token', token.value)
        return true
      }
      return false
    } catch (error) {
      console.error('刷新token错误:', error)
      return false
    }
  }

  const updateProfile = async (profileData) => {
    try {
      isLoading.value = true
      const response = await authAPI.updateProfile(profileData)
      
      if (response.success) {
        user.value = { ...user.value, ...response.data }
        localStorage.setItem('user_info', JSON.stringify(user.value))
        return { success: true, message: '更新成功' }
      } else {
        return { success: false, message: response.message || '更新失败' }
      }
    } catch (error) {
      console.error('更新用户信息错误:', error)
      return { success: false, message: '网络错误，请稍后重试' }
    } finally {
      isLoading.value = false
    }
  }

  const changePassword = async (passwordData) => {
    try {
      isLoading.value = true
      const response = await authAPI.changePassword(passwordData)
      
      if (response.success) {
        return { success: true, message: '密码修改成功' }
      } else {
        return { success: false, message: response.message || '密码修改失败' }
      }
    } catch (error) {
      console.error('修改密码错误:', error)
      return { success: false, message: '网络错误，请稍后重试' }
    } finally {
      isLoading.value = false
    }
  }

  // 初始化用户信息（从本地存储恢复）
  const initializeAuth = () => {
    const storedUser = localStorage.getItem('user_info')
    const storedPermissions = localStorage.getItem('user_permissions')
    const storedRoles = localStorage.getItem('user_roles')
    
    if (storedUser) {
      try {
        user.value = JSON.parse(storedUser)
      } catch (error) {
        console.error('解析用户信息失败:', error)
      }
    }
    
    if (storedPermissions) {
      try {
        permissions.value = JSON.parse(storedPermissions)
      } catch (error) {
        console.error('解析权限信息失败:', error)
      }
    }
    
    if (storedRoles) {
      try {
        roles.value = JSON.parse(storedRoles)
      } catch (error) {
        console.error('解析角色信息失败:', error)
      }
    }
  }

  // 检查token是否过期
  const checkTokenExpiry = () => {
    if (!token.value) return false
    
    try {
      const payload = JSON.parse(atob(token.value.split('.')[1]))
      const currentTime = Date.now() / 1000
      
      // 如果token在30分钟内过期，尝试刷新
      if (payload.exp - currentTime < 1800) {
        refreshToken()
      }
      
      return payload.exp > currentTime
    } catch (error) {
      console.error('检查token过期时间失败:', error)
      return false
    }
  }

  return {
    // 状态
    user,
    token,
    permissions,
    roles,
    isLoading,
    
    // 计算属性
    isAuthenticated,
    userRole,
    userName,
    userAvatar,
    hasPermission,
    hasRole,
    hasAnyRole,
    
    // 动作
    login,
    logout,
    refreshToken,
    updateProfile,
    changePassword,
    initializeAuth,
    checkTokenExpiry
  }
})