import { defineStore } from 'pinia'
import { getCurrentUser, logout } from '../api/user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => {
    // 从本地存储中获取用户信息
    const storedUser = localStorage.getItem('user')
    const token = localStorage.getItem('token')

    return {
      user: storedUser ? JSON.parse(storedUser) : null,
      isLoggedIn: !!token,
      token: token || ''
    }
  },

  getters: {
    getUser: (state) => state.user,
    getLoginStatus: (state) => state.isLoggedIn,
    isAdmin: (state) => state.user?.role === 1
  },

  actions: {
    // 登录
    login(userData) {
      // 确保 userData 包含 user 属性
      if (userData && userData.user) {
        this.user = userData.user
        this.isLoggedIn = true
        this.token = userData.token || ''

        // 打印登录数据，便于调试
        console.log('登录数据:', userData)

        // 存储到本地
        localStorage.setItem('user', JSON.stringify(userData.user))
        localStorage.setItem('token', this.token)
        localStorage.setItem('tokenName', userData.tokenName || 'satoken')
        localStorage.setItem('tokenPrefix', userData.tokenPrefix || '')
        localStorage.setItem('isAdmin', userData.user.role === 1 ? 'true' : 'false')

        // 打印存储的信息，便于调试
        console.log('存储的token:', localStorage.getItem('token'))
        console.log('存储的tokenName:', localStorage.getItem('tokenName'))
        console.log('存储的tokenPrefix:', localStorage.getItem('tokenPrefix'))
        console.log('存储的isAdmin:', localStorage.getItem('isAdmin'))
      } else {
        console.error('登录数据格式错误:', userData)
      }
    },

    // 登出
    async logout() {
      try {
        // 调用登出API
        await logout()

        // 重置状态
        this.user = null
        this.isLoggedIn = false
        this.token = ''

        // 清除本地存储
        localStorage.removeItem('user')
        localStorage.removeItem('token')
        localStorage.removeItem('tokenName')
        localStorage.removeItem('tokenPrefix')
        localStorage.removeItem('isAdmin')

        ElMessage.success('登出成功')
      } catch (error) {
        console.error('登出失败:', error)
      }
    },

    // 获取当前用户信息
    async fetchCurrentUser() {
      const token = localStorage.getItem('token')
      if (!token) {
        console.warn('没有token，无法获取用户信息')
        return
      }

      // 确保存储在store中的token与localStorage中的一致
      this.token = token

      console.log('开始获取用户信息，token:', token)

      try {
        // 尝试从本地存储中获取用户信息
        const userStr = localStorage.getItem('user')
        if (userStr) {
          try {
            const user = JSON.parse(userStr)
            if (user && user.id) {
              this.user = user
              this.isLoggedIn = true
              console.log('从本地存储中获取用户信息成功:', user)
              return
            }
          } catch (e) {
            console.warn('解析本地存储的用户信息失败:', e)
          }
        }

        // 如果本地存储中没有用户信息，则从服务器获取
        const res = await getCurrentUser()
        console.log('获取用户信息响应:', res)

        if (res.code === 200) {
          // 如果返回的数据中有user属性，说明是登录接口返回的数据格式
          if (res.data && res.data.user) {
            this.user = res.data.user
          } else {
            // 否则是获取当前用户接口返回的数据格式
            this.user = res.data
          }

          this.isLoggedIn = true
          localStorage.setItem('user', JSON.stringify(this.user))
          localStorage.setItem('isAdmin', this.user.role === 1 ? 'true' : 'false')
          console.log('用户信息已更新:', this.user)
        } else {
          console.error('获取用户信息失败，响应码非200:', res.code, res.msg)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，可能是token已过期，清除本地存储
        if (error.message && (error.message.includes('token') || error.message.includes('登录'))) {
          console.warn('可能是token已过期，清除本地存储')
          this.user = null
          this.isLoggedIn = false
          this.token = ''
          localStorage.removeItem('user')
          localStorage.removeItem('token')
          localStorage.removeItem('tokenName')
          localStorage.removeItem('tokenPrefix')
          localStorage.removeItem('isAdmin')
        }
        throw error // 将错误向上抛出，以便调用者可以处理
      }
    }
  }
})
