import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Admin, AdminLoginRequest } from '@/types/admin'
import { login as loginApi, logout as logoutApi, getAdminInfo } from '@/api/auth'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useAdminStore = defineStore('admin', () => {
  const token = ref<string>(localStorage.getItem('adminToken') || '')
  const adminInfo = ref<Admin | null>(null)
  
  // 登录
  const login = async (loginForm: AdminLoginRequest) => {
    try {
      const res = await loginApi(loginForm)
      const authData = res.data as any
      token.value = authData.accessToken
      adminInfo.value = authData.adminInfo
      
      localStorage.setItem('adminToken', authData.accessToken)
      localStorage.setItem('adminRefreshToken', authData.refreshToken)
      localStorage.setItem('adminInfo', JSON.stringify(authData.adminInfo))
      
      ElMessage.success('登录成功')
      router.push('/')
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }
  
  // 获取管理员信息
  const fetchAdminInfo = async () => {
    try {
      const res = await getAdminInfo()
      adminInfo.value = res.data
      localStorage.setItem('adminInfo', JSON.stringify(res.data))
    } catch (error) {
      console.error('获取管理员信息失败:', error)
      throw error
    }
  }
  
  // 登出
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      token.value = ''
      adminInfo.value = null
      localStorage.removeItem('adminToken')
      localStorage.removeItem('adminRefreshToken')
      localStorage.removeItem('adminInfo')
      router.push('/login')
    }
  }
  
  // 初始化管理员信息
  const initAdminInfo = () => {
    const storedInfo = localStorage.getItem('adminInfo')
    if (storedInfo) {
      try {
        adminInfo.value = JSON.parse(storedInfo)
      } catch (error) {
        console.error('解析管理员信息失败:', error)
      }
    }
  }
  
  return {
    token,
    adminInfo,
    login,
    logout,
    fetchAdminInfo,
    initAdminInfo
  }
})
