import { defineStore } from 'pinia'
import { ref } from 'vue'
import type {
  Permission,
  Role,
  UserRole,
  PermissionQueryParams,
  RoleQueryParams,
  PermissionStatistics,
  AuditLog
} from '../../types/permission'

// 模拟数据 - 权限列表
const mockPermissions: Permission[] = [
  {
    id: 1,
    name: '用户管理',
    code: 'user:manage',
    description: '管理用户信息的权限',
    type: 'module',
    parentId: null,
    level: 1,
    status: 'active',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    children: [
      {
        id: 101,
        name: '查看用户',
        code: 'user:view',
        description: '查看用户列表和详情的权限',
        type: 'action',
        parentId: 1,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      },
      {
        id: 102,
        name: '编辑用户',
        code: 'user:edit',
        description: '编辑用户信息的权限',
        type: 'action',
        parentId: 1,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      },
      {
        id: 103,
        name: '删除用户',
        code: 'user:delete',
        description: '删除用户的权限',
        type: 'action',
        parentId: 1,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      }
    ]
  },
  {
    id: 2,
    name: '活动管理',
    code: 'activity:manage',
    description: '管理活动信息的权限',
    type: 'module',
    parentId: null,
    level: 1,
    status: 'active',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    children: [
      {
        id: 201,
        name: '查看活动',
        code: 'activity:view',
        description: '查看活动列表和详情的权限',
        type: 'action',
        parentId: 2,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      },
      {
        id: 202,
        name: '创建活动',
        code: 'activity:create',
        description: '创建新活动的权限',
        type: 'action',
        parentId: 2,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      },
      {
        id: 203,
        name: '审核活动',
        code: 'activity:audit',
        description: '审核活动内容的权限',
        type: 'action',
        parentId: 2,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      }
    ]
  },
  {
    id: 3,
    name: '动物管理',
    code: 'animal:manage',
    description: '管理动物信息的权限',
    type: 'module',
    parentId: null,
    level: 1,
    status: 'active',
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    children: [
      {
        id: 301,
        name: '查看动物',
        code: 'animal:view',
        description: '查看动物列表和详情的权限',
        type: 'action',
        parentId: 3,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      },
      {
        id: 302,
        name: '编辑动物',
        code: 'animal:edit',
        description: '编辑动物信息的权限',
        type: 'action',
        parentId: 3,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      },
      {
        id: 303,
        name: '认养管理',
        code: 'animal:adopt',
        description: '管理动物认养流程的权限',
        type: 'action',
        parentId: 3,
        level: 2,
        status: 'active',
        createTime: '2024-01-01 10:00:00',
        updateTime: '2024-01-01 10:00:00'
      }
    ]
  }
]

// 模拟数据 - 角色列表
const mockRoles: Role[] = [
  {
    id: 1,
    name: '超级管理员',
    code: 'super_admin',
    description: '拥有系统所有权限的最高权限角色',
    type: 'system',
    status: 'active',
    permissionIds: [1, 101, 102, 103, 2, 201, 202, 203, 3, 301, 302, 303],
    userCount: 3,
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    permissions: mockPermissions.flatMap(p => p.children || []).filter(p => 
      [101, 102, 103, 201, 202, 203, 301, 302, 303].includes(p.id)
    )
  },
  {
    id: 2,
    name: '内容管理员',
    code: 'content_admin',
    description: '负责内容审核和管理的角色',
    type: 'system',
    status: 'active',
    permissionIds: [2, 201, 203, 3, 301],
    userCount: 5,
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    permissions: mockPermissions.flatMap(p => p.children || []).filter(p => 
      [201, 203, 301].includes(p.id)
    )
  },
  {
    id: 3,
    name: '用户管理员',
    code: 'user_admin',
    description: '负责用户管理和支持的角色',
    type: 'system',
    status: 'active',
    permissionIds: [1, 101, 102],
    userCount: 8,
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00',
    permissions: mockPermissions.flatMap(p => p.children || []).filter(p => 
      [101, 102].includes(p.id)
    )
  }
]

// 模拟数据 - 用户角色关联
const mockUserRoles: UserRole[] = [
  { id: 1, userId: 1, roleId: 1, assignTime: '2024-01-01 10:00:00', assignBy: 'system' },
  { id: 2, userId: 2, roleId: 2, assignTime: '2024-01-01 10:00:00', assignBy: 'admin' },
  { id: 3, userId: 3, roleId: 2, assignTime: '2024-01-01 10:00:00', assignBy: 'admin' },
  { id: 4, userId: 4, roleId: 3, assignTime: '2024-01-01 10:00:00', assignBy: 'admin' }
]

// 模拟数据 - 权限统计
const mockPermissionStats: PermissionStatistics = {
  totalPermissions: 12,
  activePermissions: 12,
  inactivePermissions: 0,
  totalRoles: 3,
  activeRoles: 3,
  inactiveRoles: 0,
  totalUsersWithRoles: 4,
  permissionUsage: {
    'user:view': 15,
    'user:edit': 8,
    'user:delete': 3,
    'activity:view': 25,
    'activity:create': 12,
    'activity:audit': 18,
    'animal:view': 20,
    'animal:edit': 10,
    'animal:adopt': 15
  },
  roleDistribution: {
    'super_admin': 3,
    'content_admin': 5,
    'user_admin': 8
  },
  userPermissionStats: {
    averagePermissionsPerUser: 6.5,
    maxPermissionsPerUser: 9,
    minPermissionsPerUser: 2,
    usersWithExcessivePermissions: 1
  },
  auditLogs: {
    totalLogs: 156,
    permissionChanges: 45,
    roleChanges: 32,
    userRoleChanges: 79
  }
}

// 模拟数据 - 审计日志
const mockAuditLogs: AuditLog[] = [
  {
    id: 1,
    action: 'assign_role',
    targetType: 'user',
    targetId: 2,
    targetName: 'user2',
    performerId: 1,
    performerName: 'admin',
    details: '分配角色: content_admin',
    ipAddress: '192.168.1.100',
    userAgent: 'Mozilla/5.0',
    timestamp: '2024-01-15 14:30:00',
    status: 'success'
  },
  {
    id: 2,
    action: 'update_permission',
    targetType: 'permission',
    targetId: 101,
    targetName: 'user:view',
    performerId: 1,
    performerName: 'admin',
    details: '更新权限描述',
    ipAddress: '192.168.1.100',
    userAgent: 'Mozilla/5.0',
    timestamp: '2024-01-15 14:25:00',
    status: 'success'
  },
  {
    id: 3,
    action: 'create_role',
    targetType: 'role',
    targetId: 3,
    targetName: 'user_admin',
    performerId: 1,
    performerName: 'admin',
    details: '创建新角色',
    ipAddress: '192.168.1.100',
    userAgent: 'Mozilla/5.0',
    timestamp: '2024-01-15 14:20:00',
    status: 'success'
  }
]

export const usePermissionStore = defineStore('permission', () => {
  // 状态
  const permissions = ref<Permission[]>(mockPermissions)
  const roles = ref<Role[]>(mockRoles)
  const userRoles = ref<UserRole[]>(mockUserRoles)
  const permissionStats = ref<PermissionStatistics>(mockPermissionStats)
  const auditLogs = ref<AuditLog[]>(mockAuditLogs)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 获取权限列表
  const fetchPermissions = async (params: PermissionQueryParams) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      
      let filteredPermissions = mockPermissions.flat()
      
      if (params.keyword) {
        filteredPermissions = filteredPermissions.filter(permission => 
          permission.name.includes(params.keyword!) || 
          permission.code.includes(params.keyword!) ||
          permission.description.includes(params.keyword!)
        )
      }
      
      if (params.status) {
        filteredPermissions = filteredPermissions.filter(permission => permission.status === params.status)
      }
      
      if (params.type) {
        filteredPermissions = filteredPermissions.filter(permission => permission.type === params.type)
      }
      
      if (params.parentId !== undefined) {
        filteredPermissions = filteredPermissions.filter(permission => permission.parentId === params.parentId)
      }
      
      // 分页
      const start = (params.page - 1) * params.pageSize
      const paginatedPermissions = filteredPermissions.slice(start, start + params.pageSize)
      
      permissions.value = paginatedPermissions
      
      return {
        permissions: paginatedPermissions,
        total: filteredPermissions.length,
        page: params.page,
        pageSize: params.pageSize
      }
    } catch (err) {
      error.value = '获取权限列表失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取角色列表
  const fetchRoles = async (params: RoleQueryParams) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      
      let filteredRoles = mockRoles
      
      if (params.keyword) {
        filteredRoles = filteredRoles.filter(role => 
          role.name.includes(params.keyword!) || 
          role.code.includes(params.keyword!) ||
          role.description.includes(params.keyword!)
        )
      }
      
      if (params.status) {
        filteredRoles = filteredRoles.filter(role => role.status === params.status)
      }
      
      if (params.type) {
        filteredRoles = filteredRoles.filter(role => role.type === params.type)
      }
      
      // 分页
      const start = (params.page - 1) * params.pageSize
      const paginatedRoles = filteredRoles.slice(start, start + params.pageSize)
      
      roles.value = paginatedRoles
      
      return {
        roles: paginatedRoles,
        total: filteredRoles.length,
        page: params.page,
        pageSize: params.pageSize
      }
    } catch (err) {
      error.value = '获取角色列表失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取用户角色
  const fetchUserRoles = async (userId: number) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 300))
      
      const userRoles = mockUserRoles.filter(ur => ur.userId === userId)
      const roleIds = userRoles.map(ur => ur.roleId)
      const userRolesWithDetails = mockRoles
        .filter(role => roleIds.includes(role.id))
        .map(role => ({
          ...role,
          assignTime: userRoles.find(ur => ur.roleId === role.id)?.assignTime,
          assignBy: userRoles.find(ur => ur.roleId === role.id)?.assignBy
        }))
      
      return userRolesWithDetails
    } catch (err) {
      error.value = '获取用户角色失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 分配用户角色
  const assignUserRole = async (userId: number, roleId: number, assignBy: string) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 400))
      
      // 检查是否已分配
      const existingAssignment = mockUserRoles.find(ur => ur.userId === userId && ur.roleId === roleId)
      if (existingAssignment) {
        throw new Error('用户已拥有该角色')
      }
      
      const newAssignment: UserRole = {
        id: Math.max(...mockUserRoles.map(ur => ur.id)) + 1,
        userId,
        roleId,
        assignTime: new Date().toISOString(),
        assignBy
      }
      
      mockUserRoles.push(newAssignment)
      
      // 更新角色用户计数
      const role = mockRoles.find(r => r.id === roleId)
      if (role) {
        role.userCount += 1
      }
      
      return newAssignment
    } catch (err) {
      error.value = '分配用户角色失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 移除用户角色
  const removeUserRole = async (userId: number, roleId: number) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 400))
      
      const index = mockUserRoles.findIndex(ur => ur.userId === userId && ur.roleId === roleId)
      if (index === -1) {
        throw new Error('用户角色关联不存在')
      }
      
      mockUserRoles.splice(index, 1)
      
      // 更新角色用户计数
      const role = mockRoles.find(r => r.id === roleId)
      if (role && role.userCount > 0) {
        role.userCount -= 1
      }
      
      return true
    } catch (err) {
      error.value = '移除用户角色失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 创建角色
  const createRole = async (roleData: Omit<Role, 'id' | 'createTime' | 'updateTime'>) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      
      const newRole: Role = {
        ...roleData,
        id: Math.max(...mockRoles.map(r => r.id)) + 1,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        permissions: mockPermissions.flatMap(p => p.children || []).filter(p => 
          roleData.permissionIds.includes(p.id)
        )
      }
      
      mockRoles.push(newRole)
      roles.value = [...mockRoles]
      
      return newRole
    } catch (err) {
      error.value = '创建角色失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 更新角色
  const updateRole = async (roleId: number, roleData: Partial<Omit<Role, 'id' | 'createTime'>>) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 500))
      
      const index = mockRoles.findIndex(r => r.id === roleId)
      if (index === -1) {
        throw new Error('角色不存在')
      }
      
      mockRoles[index] = {
        ...mockRoles[index],
        ...roleData,
        updateTime: new Date().toISOString(),
        permissions: roleData.permissionIds 
          ? mockPermissions.flatMap(p => p.children || []).filter(p => 
              roleData.permissionIds!.includes(p.id)
            )
          : mockRoles[index].permissions
      }
      
      roles.value = [...mockRoles]
      
      return mockRoles[index]
    } catch (err) {
      error.value = '更新角色失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 删除角色
  const deleteRole = async (roleId: number) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 400))
      
      const index = mockRoles.findIndex(r => r.id === roleId)
      if (index === -1) {
        throw new Error('角色不存在')
      }
      
      // 检查是否有用户使用该角色
      const usersWithRole = mockUserRoles.filter(ur => ur.roleId === roleId)
      if (usersWithRole.length > 0) {
        throw new Error('无法删除有用户使用的角色')
      }
      
      mockRoles.splice(index, 1)
      roles.value = [...mockRoles]
      
      return true
    } catch (err) {
      error.value = '删除角色失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取权限统计
  const fetchPermissionStatistics = async () => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 800))
      
      // 模拟实时数据更新
      const stats = {
        ...mockPermissionStats,
        totalUsersWithRoles: mockUserRoles.length,
        userPermissionStats: {
          ...mockPermissionStats.userPermissionStats,
          averagePermissionsPerUser: Math.round(
            mockUserRoles.reduce((sum, ur) => {
              const role = mockRoles.find(r => r.id === ur.roleId)
              return sum + (role ? role.permissionIds.length : 0)
            }, 0) / mockUserRoles.length
          )
        }
      }
      
      permissionStats.value = stats
      return stats
    } catch (err) {
      error.value = '获取权限统计失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取审计日志
  const fetchAuditLogs = async (page: number, pageSize: number) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 600))
      
      const start = (page - 1) * pageSize
      const paginatedLogs = mockAuditLogs.slice(start, start + pageSize)
      
      auditLogs.value = paginatedLogs
      
      return {
        logs: paginatedLogs,
        total: mockAuditLogs.length,
        page,
        pageSize
      }
    } catch (err) {
      error.value = '获取审计日志失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 检查用户权限
  const checkUserPermission = async (userId: number, permissionCode: string) => {
    loading.value = true
    error.value = null
    
    try {
      await new Promise(resolve => setTimeout(resolve, 200))
      
      const userRoles = mockUserRoles.filter(ur => ur.userId === userId)
      const roleIds = userRoles.map(ur => ur.roleId)
      
      const hasPermission = mockRoles.some(role => 
        roleIds.includes(role.id) && 
        role.permissions.some(p => p.code === permissionCode)
      )
      
      return hasPermission
    } catch (err) {
      error.value = '检查用户权限失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 重置错误
  const clearError = () => {
    error.value = null
  }

  return {
    // 状态
    permissions,
    roles,
    userRoles,
    permissionStats,
    auditLogs,
    loading,
    error,
    
    // 操作
    fetchPermissions,
    fetchRoles,
    fetchUserRoles,
    assignUserRole,
    removeUserRole,
    createRole,
    updateRole,
    deleteRole,
    fetchPermissionStatistics,
    fetchAuditLogs,
    checkUserPermission,
    clearError
  }
})