import { defineStore } from 'pinia'
import { reactive } from 'vue'
import { authAPI } from '@/api'
import type { Admin } from '@/types/user'

// 定义用户权限类型
export interface UserPermission {
  resource: string
  action: string
}

export const useAppStore = defineStore('app', () => {
  // 状态
  const state = reactive({
    user: null as Admin | null,
    permissions: [] as string[], // 添加权限列表
    loading: false,
    initialized: false
  })

  // 设置用户信息和权限
  const setUser = (user: Admin, permissions: string[] = []) => {
    state.user = user
    state.permissions = permissions
  }

  // 检查是否有特定权限
  const hasPermission = (permission: string): boolean => {
    // 如果是超级管理员，拥有所有权限
    if (state.user?.role === 'admin') {
      return true
    }
    
    // 检查是否拥有该权限
    return state.permissions.includes(permission)
  }

  // 检查是否拥有所有指定权限
  const hasAllPermissions = (permissions: string[]): boolean => {
    return permissions.every(permission => hasPermission(permission))
  }

  // 检查是否拥有任意一个指定权限
  const hasAnyPermission = (permissions: string[]): boolean => {
    return permissions.some(permission => hasPermission(permission))
  }

  // 清除用户信息
  const clearUser = () => {
    state.user = null
    state.permissions = []
    localStorage.removeItem('admin_token')
  }

  // 初始化应用
  const initialize = async () => {
    if (state.initialized) return
    
    state.loading = true
    try {
      const token = localStorage.getItem('admin_token')
      if (token) {
        // 获取用户信息
        const response = await authAPI.getCurrentUser()
        
        // 统一处理接口响应格式
        if (!response || typeof response !== 'object') {
          throw new Error('获取用户信息失败：接口返回格式异常')
        }
        
        // 确保响应数据格式为 { data: { admin: object } }
        if (response.data && typeof response.data === 'object' && response.data.admin) {
          // 模拟权限数据 - 实际项目中应该从后端获取
          const mockPermissions = [
            'user:read', 'user:write',
            'merchant:read', 'merchant:write',
            'travel:read', 'travel:write',
            'animal:read', 'animal:write',
            'order:read', 'order:write',
            'promotion:read', 'promotion:write',
            'system:read', 'system:write'
          ]
          state.user = response.data.admin
          state.permissions = mockPermissions
        } else {
          throw new Error('获取用户信息失败：响应数据格式不符合预期')
        }
      }
    } catch (error) {
      console.error('初始化失败:', {
        error: error,
        timestamp: new Date().toISOString(),
        token: localStorage.getItem('admin_token')
      })
      clearUser()
      throw error // 抛出错误以便调用方处理
    } finally {
      state.loading = false
      state.initialized = true
    }
  }

  // 登录
  const login = async (credentials: { username: string; password: string }) => {
    state.loading = true
    try {
      const response = await authAPI.login(credentials)
      
      // 保存token - 修复数据结构访问问题
      if (response?.data?.token) {
        localStorage.setItem('admin_token', response.data.token)
      } else if (response?.token) {
        localStorage.setItem('admin_token', response.token)
      } else {
        throw new Error('登录响应中缺少token')
      }
      
      // 设置用户信息 - 修复数据结构访问问题
      if (response?.data?.admin) {
        // 模拟权限数据 - 实际项目中应该从后端获取
        const mockPermissions = [
          'user:read', 'user:write',
          'merchant:read', 'merchant:write',
          'travel:read', 'travel:write',
          'animal:read', 'animal:write',
          'order:read', 'order:write',
          'promotion:read', 'promotion:write',
          'system:read', 'system:write'
        ]
        state.user = response.data.admin
        state.permissions = mockPermissions
      } else if (response?.admin) {
        // 模拟权限数据 - 实际项目中应该从后端获取
        const mockPermissions = [
          'user:read', 'user:write',
          'merchant:read', 'merchant:write',
          'travel:read', 'travel:write',
          'animal:read', 'animal:write',
          'order:read', 'order:write',
          'promotion:read', 'promotion:write',
          'system:read', 'system:write'
        ]
        state.user = response.admin
        state.permissions = mockPermissions
      } else {
        throw new Error('登录响应中缺少用户信息')
      }
      
      return response
    } catch (error) {
      // 登录失败时清除可能存在的token
      clearUser()
      throw error
    } finally {
      state.loading = false
    }
  }

  // 退出登录
  const logout = () => {
    clearUser()
  }

  return {
    state,
    setUser,
    clearUser,
    initialize,
    login,
    logout,
    hasPermission,
    hasAllPermissions,
    hasAnyPermission
  }
})

export type { Admin }