import { defineStore } from 'pinia'
import axios from 'axios'

// 定义用户类型
interface User {
  id: string
  username: string
  email: string
  role: string
  status: string
}

// 定义登录请求类型
interface LoginRequest {
  username: string
  password: string
}

// 定义注册请求类型
interface RegisterRequest {
  username: string
  password: string
  email: string
  role: string
}

// 定义用户存储
export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    token: localStorage.getItem('token') || null,
    loading: false,
    error: null as string | null
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.user?.role === 'admin'
  },
  
  actions: {
    // 登录
    async login(credentials: LoginRequest) {
      this.loading = true
      this.error = null

      try {
        console.log('开始登录请求...', credentials)
        const response = await axios.post('/api/users/login', credentials)
        console.log('登录响应:', response.data)
        const { access_token } = response.data

        // 保存token到本地存储
        localStorage.setItem('token', access_token)
        this.token = access_token

        // 获取用户信息
        await this.fetchUser()

        return true
      } catch (error: any) {
        console.error('登录失败:', error)
        this.error = error.response?.data?.detail || '登录失败，请检查用户名和密码'
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 注册
    async register(userData: RegisterRequest) {
      this.loading = true
      this.error = null

      try {
        console.log('开始注册请求...', userData)
        const response = await axios.post('/api/users/register', userData)
        console.log('注册响应:', response.data)
        console.log('响应状态:', response.status)
        return true
      } catch (error: any) {
        console.error('注册失败:', error)
        console.error('错误详情:', error.response?.data)
        console.error('错误状态:', error.response?.status)

        // 提取详细的错误信息
        const detail = error.response?.data?.detail
        if (detail) {
          this.error = detail
        } else if (error.response?.status === 400) {
          this.error = '请求参数错误，请检查输入信息'
        } else {
          this.error = '注册失败，请稍后重试'
        }

        return false
      } finally {
        this.loading = false
      }
    },
    
    // 获取用户信息
    async fetchUser() {
      this.loading = true
      this.error = null

      try {
        const response = await axios.get('/api/users/me')
        this.user = response.data

        // 保存用户信息到本地存储
        localStorage.setItem('user', JSON.stringify(response.data))

        return true
      } catch (error: any) {
        this.error = error.response?.data?.detail || '获取用户信息失败'
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 登出
    logout() {
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      
      // 清除状态
      this.token = null
      this.user = null
      this.error = null
    },
    
    // 初始化用户状态
    init() {
      const token = localStorage.getItem('token')
      const userStr = localStorage.getItem('user')
      
      if (token) {
        this.token = token
      }
      
      if (userStr) {
        try {
          this.user = JSON.parse(userStr)
        } catch {
          this.logout()
        }
      }
    }
  }
})
