import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo, UserType, AuthState } from '@/types/auth'
import { StorageManager } from '@/utils/storage'
import { AuthAPI } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string | null>(null)
  const userInfo = ref<UserInfo | null>(null)
  const isAuthenticated = ref<boolean>(false)

  // 计算属性
  const userType = computed<UserType | null>(() => {
    return userInfo.value?.accountType || null
  })

  const userName = computed<string>(() => {
    return userInfo.value?.accountName || ''
  })

  const userId = computed<number | null>(() => {
    return userInfo.value?.accountId || null
  })

  // 初始化认证状态
  const initAuth = () => {
    const authInfo = StorageManager.getAuthInfo()
    if (authInfo.token && authInfo.userInfo) {
      token.value = authInfo.token
      userInfo.value = authInfo.userInfo
      isAuthenticated.value = true
    }
  }

  // 登录
  const login = async (credentials: { accountName: string; accountPassword: string }) => {
    try {
      const response = await AuthAPI.login(credentials)

      if (response.code === 200) {
        const { token: newToken, accountInfo } = response.data

        // 更新状态
        token.value = newToken
        userInfo.value = accountInfo
        isAuthenticated.value = true

        return { success: true, message: '登录成功' }
      } else {
        return { success: false, message: response.msg || '登录失败' }
      }
    } catch (error: any) {
      console.error('登录错误:', error)
      return {
        success: false,
        message: error.response?.data?.msg || '网络错误，请重试',
      }
    }
  }

  // 注册
  const register = async (userData: any) => {
    try {
      const response = await AuthAPI.register(userData)

      if (response.code === 200) {
        return { success: true, message: '注册成功' }
      } else {
        return { success: false, message: response.msg || '注册失败' }
      }
    } catch (error: any) {
      console.error('注册错误:', error)
      return {
        success: false,
        message: error.response?.data?.msg || '网络错误，请重试',
      }
    }
  }

  // 修改密码
  const changePassword = async (passwordData: any) => {
    try {
      const response = await AuthAPI.changePassword(passwordData)

      if (response.code === 200) {
        return { success: true, message: '密码修改成功' }
      } else {
        return { success: false, message: response.msg || '密码修改失败' }
      }
    } catch (error: any) {
      console.error('修改密码错误:', error)
      return {
        success: false,
        message: error.response?.data?.msg || '网络错误，请重试',
      }
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    userInfo.value = null
    isAuthenticated.value = false
    StorageManager.clearAuthData()
  }

  // 检查权限
  const hasPermission = (requiredRole: UserType): boolean => {
    return userType.value === requiredRole
  }

  // 获取重定向路径
  const getRedirectPath = (): string => {
    switch (userType.value) {
      case 'admin':
        return '/admin'
      case 'manager':
        return '/merchant'
      case 'customer':
        return '/user'
      default:
        return '/login'
    }
  }

  return {
    // 状态
    token,
    userInfo,
    isAuthenticated,

    // 计算属性
    userType,
    userName,
    userId,

    // 方法
    initAuth,
    login,
    register,
    changePassword,
    logout,
    hasPermission,
    getRedirectPath,
  }
})
