// 模拟数据服务
import { message } from 'ant-design-vue'

// 模拟延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟用户数据
const mockUsers = [
  { id: 1, username: 'admin', nickname: '系统管理员', role: 'admin', status: 'active', createdAt: '2024-01-01' },
  { id: 2, username: 'user1', nickname: '旅行爱好者', role: 'user', status: 'active', createdAt: '2024-01-02' },
  { id: 3, username: 'merchant1', nickname: '花店老板', role: 'merchant', status: 'active', createdAt: '2024-01-03' }
]

// 模拟商家数据
const mockMerchants = [
  { id: 1, name: '鲜花坊', type: 'flower', status: 'approved', contact: '13800138001', createdAt: '2024-01-05' },
  { id: 2, name: '快乐农场', type: 'farm', status: 'approved', contact: '13800138002', createdAt: '2024-01-06' }
]

// 模拟旅行数据
const mockTravels = [
  { id: 1, userId: 2, destination: '西藏', startDate: '2024-06-01', endDate: '2024-06-10', status: 'active', createdAt: '2024-01-10' },
  { id: 2, userId: 2, destination: '云南', startDate: '2024-07-01', endDate: '2024-07-07', status: 'active', createdAt: '2024-01-11' }
]

// 模拟动物数据
const mockAnimals = [
  { id: 1, name: '小白', type: 'sheep', merchantId: 2, status: 'available', price: 500, createdAt: '2024-01-15' },
  { id: 2, name: '小花', type: 'cow', merchantId: 2, status: 'claimed', price: 1000, createdAt: '2024-01-16' }
]

// 模拟订单数据
const mockOrders = [
  { id: 1, userId: 2, merchantId: 1, amount: 199, status: 'completed', createdAt: '2024-01-20' },
  { id: 2, userId: 2, merchantId: 1, amount: 299, status: 'pending', createdAt: '2024-01-21' }
]

// 模拟权限数据
const mockPermissions = [
  { id: 1, name: '用户读取', code: 'user:read', description: '查看用户信息', resource_type: 'user', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 2, name: '用户写入', code: 'user:write', description: '创建/编辑用户信息', resource_type: 'user', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 3, name: '商家读取', code: 'merchant:read', description: '查看商家信息', resource_type: 'merchant', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 4, name: '商家写入', code: 'merchant:write', description: '创建/编辑商家信息', resource_type: 'merchant', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 5, name: '旅行读取', code: 'travel:read', description: '查看旅行信息', resource_type: 'travel', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 6, name: '旅行写入', code: 'travel:write', description: '创建/编辑旅行信息', resource_type: 'travel', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 7, name: '动物读取', code: 'animal:read', description: '查看动物信息', resource_type: 'animal', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 8, name: '动物写入', code: 'animal:write', description: '创建/编辑动物信息', resource_type: 'animal', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 9, name: '订单读取', code: 'order:read', description: '查看订单信息', resource_type: 'order', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 10, name: '订单写入', code: 'order:write', description: '创建/编辑订单信息', resource_type: 'order', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 11, name: '推广读取', code: 'promotion:read', description: '查看推广信息', resource_type: 'promotion', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 12, name: '推广写入', code: 'promotion:write', description: '创建/编辑推广信息', resource_type: 'promotion', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 13, name: '系统读取', code: 'system:read', description: '查看系统信息', resource_type: 'system', created_at: '2024-01-01', updated_at: '2024-01-01' },
  { id: 14, name: '系统写入', code: 'system:write', description: '创建/编辑系统信息', resource_type: 'system', created_at: '2024-01-01', updated_at: '2024-01-01' }
]

// 模拟系统日志数据
const mockSystemLogs = [
  { id: '1', level: 'info', message: '用户登录成功 - admin', timestamp: '2024-03-15T14:30:22Z', module: 'auth', userId: '1', ip: '192.168.1.100' },
  { id: '2', level: 'info', message: '数据库备份完成 - 备份文件: backup_20240315.sql', timestamp: '2024-03-15T14:00:00Z', module: 'database', userId: '1', ip: '192.168.1.100' },
  { id: '3', level: 'warn', message: '系统警告 - 内存使用率超过80%', timestamp: '2024-03-15T13:45:18Z', module: 'system', userId: '1', ip: '192.168.1.100' },
  { id: '4', level: 'info', message: '定时任务执行 - 清理过期日志', timestamp: '2024-03-15T13:30:00Z', module: 'task', userId: '1', ip: '192.168.1.100' },
  { id: '5', level: 'error', message: '数据库连接失败 - 连接超时', timestamp: '2024-03-15T12:15:30Z', module: 'database', userId: '1', ip: '192.168.1.100' },
  { id: '6', level: 'info', message: '用户注册成功 - user123', timestamp: '2024-03-15T11:20:45Z', module: 'auth', userId: '2', ip: '192.168.1.101' },
  { id: '7', level: 'debug', message: 'API调用 - 获取用户列表', timestamp: '2024-03-15T10:30:15Z', module: 'api', userId: '1', ip: '192.168.1.100' },
  { id: '8', level: 'info', message: '订单创建成功 - 订单号: ORD20240315001', timestamp: '2024-03-15T09:45:22Z', module: 'order', userId: '3', ip: '192.168.1.102' }
]

// 模拟API响应格式
const createSuccessResponse = (data: any) => ({
  success: true,
  data,
  message: '操作成功'
})

// 模拟分页响应
const createPaginatedResponse = (data: any[], page: number, pageSize: number, total: number) => ({
  success: true,
  data: {
    list: data,
    pagination: {
      current: page,
      pageSize,
      total,
      totalPages: Math.ceil(total / pageSize)
    }
  }
})

// 模拟认证API
export const mockAuthAPI = {
  login: async (credentials: { username: string; password: string }) => {
    await delay(1000)
    
    if (credentials.username === 'admin' && credentials.password === 'admin123') {
      const adminUser = mockUsers.find(u => u.username === 'admin')
      return createSuccessResponse({
        token: 'mock-jwt-token-for-admin',
        admin: adminUser
      })
    }
    
    message.error('用户名或密码错误')
    throw new Error('登录失败')
  },

  getCurrentUser: async () => {
    await delay(500)
    const adminUser = mockUsers.find(u => u.username === 'admin')
    return createSuccessResponse({
      admin: adminUser
    })
  }
}

// 模拟用户API
export const mockUserAPI = {
  getUsers: async (params: any = {}) => {
    await delay(800)
    const { page = 1, pageSize = 10 } = params
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const paginatedData = mockUsers.slice(start, end)
    
    return createPaginatedResponse(paginatedData, page, pageSize, mockUsers.length)
  },

  getUserById: async (id: number) => {
    await delay(500)
    const user = mockUsers.find(u => u.id === id)
    if (user) {
      return createSuccessResponse(user)
    }
    message.error('用户不存在')
    throw new Error('用户不存在')
  }
}

// 模拟商家API
export const mockMerchantAPI = {
  getMerchants: async (params: any = {}) => {
    await delay(800)
    const { page = 1, limit = 10 } = params
    const start = (page - 1) * limit
    const end = start + limit
    const paginatedData = mockMerchants.slice(start, end)
    
    return createPaginatedResponse(paginatedData, page, limit, mockMerchants.length)
  }
}

// 模拟旅行API
export const mockTravelAPI = {
  getTravels: async (params: any = {}) => {
    await delay(800)
    const { page = 1, limit = 10 } = params
    const start = (page - 1) * limit
    const end = start + limit
    const paginatedData = mockTravels.slice(start, end)
    
    return createPaginatedResponse(paginatedData, page, limit, mockTravels.length)
  }
}

// 模拟动物API
export const mockAnimalAPI = {
  getAnimals: async (params: any = {}) => {
    await delay(800)
    const { page = 1, limit = 10 } = params
    const start = (page - 1) * limit
    const end = start + limit
    const paginatedData = mockAnimals.slice(start, end)
    
    return createPaginatedResponse(paginatedData, page, limit, mockAnimals.length)
  }
}

// 模拟订单API
export const mockOrderAPI = {
  getOrders: async (params: any = {}) => {
    await delay(800)
    const { page = 1, limit = 10 } = params
    const start = (page - 1) * limit
    const end = start + limit
    const paginatedData = mockOrders.slice(start, end)
    
    return createPaginatedResponse(paginatedData, page, limit, mockOrders.length)
  }
}

// 模拟系统API
export const mockSystemAPI = {
  getSystemStats: async () => {
    await delay(600)
    return createSuccessResponse({
      userCount: mockUsers.length,
      merchantCount: mockMerchants.length,
      travelCount: mockTravels.length,
      animalCount: mockAnimals.length,
      orderCount: mockOrders.length,
      todayUserCount: 5,
      todayOrderCount: 3
    })
  },

  getSystemLogs: async (params: any = {}) => {
    await delay(800)
    const { page = 1, limit = 10, level, module, startDate, endDate } = params
    
    // 根据查询参数过滤日志
    let filteredLogs = mockSystemLogs
    if (level) {
      filteredLogs = mockSystemLogs.filter(log => log.level === level)
    }
    if (module) {
      filteredLogs = filteredLogs.filter(log => log.module === module)
    }
    if (startDate) {
      filteredLogs = filteredLogs.filter(log => new Date(log.timestamp) >= new Date(startDate))
    }
    if (endDate) {
      filteredLogs = filteredLogs.filter(log => new Date(log.timestamp) <= new Date(endDate))
    }
    
    const start = (page - 1) * limit
    const end = start + limit
    const paginatedData = filteredLogs.slice(start, end)
    
    return createPaginatedResponse(paginatedData, page, limit, filteredLogs.length)
  },
  
  getSystemMonitorData: async () => {
    await delay(500)
    return createSuccessResponse({
      cpuUsage: Math.floor(Math.random() * 100),
      memoryUsage: Math.floor(Math.random() * 100),
      networkTraffic: Math.floor(Math.random() * 1000),
      diskUsage: Math.floor(Math.random() * 100),
      timestamp: new Date().toISOString()
    })
  }
}

// 模拟权限API
export const mockPermissionAPI = {
  getPermissions: async (params: any = {}) => {
    await delay(800)
    const { page = 1, pageSize = 10, keyword = '' } = params
    
    // 根据关键词过滤权限
    let filteredPermissions = mockPermissions
    if (keyword) {
      filteredPermissions = mockPermissions.filter(p => 
        p.name.includes(keyword) || 
        p.code.includes(keyword) || 
        p.description.includes(keyword)
      )
    }
    
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const paginatedData = filteredPermissions.slice(start, end)
    
    return createPaginatedResponse(paginatedData, page, pageSize, filteredPermissions.length)
  },

  getPermission: async (id: number) => {
    await delay(500)
    const permission = mockPermissions.find(p => p.id === id)
    if (permission) {
      return createSuccessResponse(permission)
    }
    message.error('权限不存在')
    throw new Error('权限不存在')
  },

  createPermission: async (data: any) => {
    await delay(500)
    const newPermission = {
      id: mockPermissions.length + 1,
      ...data,
      created_at: new Date().toISOString().split('T')[0],
      updated_at: new Date().toISOString().split('T')[0]
    }
    mockPermissions.push(newPermission)
    return createSuccessResponse(newPermission)
  },

  updatePermission: async (id: number, data: any) => {
    await delay(500)
    const index = mockPermissions.findIndex(p => p.id === id)
    if (index !== -1) {
      mockPermissions[index] = {
        ...mockPermissions[index],
        ...data,
        updated_at: new Date().toISOString().split('T')[0]
      }
      return createSuccessResponse(mockPermissions[index])
    }
    message.error('权限不存在')
    throw new Error('权限不存在')
  },

  deletePermission: async (id: number) => {
    await delay(500)
    const index = mockPermissions.findIndex(p => p.id === id)
    if (index !== -1) {
      mockPermissions.splice(index, 1)
      return createSuccessResponse(null)
    }
    message.error('权限不存在')
    throw new Error('权限不存在')
  },

  batchDeletePermissions: async (ids: number[]) => {
    await delay(500)
    const deletedCount = ids.filter(id => {
      const index = mockPermissions.findIndex(p => p.id === id)
      if (index !== -1) {
        mockPermissions.splice(index, 1)
        return true
      }
      return false
    }).length
    
    return createSuccessResponse({
      message: `成功删除${deletedCount}个权限`,
      affectedRows: deletedCount
    })
  }
}

// 模拟仪表板数据
const mockDashboardData = {
  stats: {
    userCount: 1280,
    newUserCount: 25,
    activeUserCount: 860,
    merchantCount: 42,
    newMerchantCount: 3,
    activeMerchantCount: 38,
    travelCount: 156,
    newTravelCount: 8,
    animalCount: 89,
    newAnimalCount: 5,
    orderCount: 342,
    newOrderCount: 12,
    orderAmount: 25680,
    onlineUserCount: 142,
    systemLoad: 45
  },
  userGrowth: [
    { date: '2024-03-01', count: 1200 },
    { date: '2024-03-02', count: 1210 },
    { date: '2024-03-03', count: 1225 },
    { date: '2024-03-04', count: 1235 },
    { date: '2024-03-05', count: 1248 },
    { date: '2024-03-06', count: 1262 },
    { date: '2024-03-07', count: 1280 }
  ],
  orderStats: [
    { date: '2024-03-01', count: 28, amount: 2100 },
    { date: '2024-03-02', count: 32, amount: 2450 },
    { date: '2024-03-03', count: 25, amount: 1890 },
    { date: '2024-03-04', count: 35, amount: 2680 },
    { date: '2024-03-05', count: 42, amount: 3200 },
    { date: '2024-03-06', count: 38, amount: 2890 },
    { date: '2024-03-07', count: 45, amount: 3420 }
  ],
  activities: [
    {
      id: 1,
      title: '新用户注册',
      description: '用户"旅行爱好者"完成了注册',
      avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=1',
      time: '2分钟前'
    },
    {
      title: '旅行计划创建',
      description: '用户"探险家"发布了西藏旅行计划',
      avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=2',
      time: '5分钟前'
    },
    {
      title: '动物认领',
      description: '用户"动物之友"认领了一只羊驼',
      avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=3',
      time: '10分钟前'
    },
    {
      title: '订单完成',
      description: '花店"鲜花坊"完成了一笔鲜花订单',
      avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=4',
      time: '15分钟前'
    }
  ]
}

// 模拟仪表板API
export const mockDashboardAPI = {
  getDashboardData: async () => {
    await delay(800)
    return createSuccessResponse(mockDashboardData)
  },

  getUserGrowthData: async (days: number = 7) => {
    await delay(500)
    // 根据天数返回相应的数据
    const data = mockDashboardData.userGrowth.slice(-days)
    return createSuccessResponse(data)
  },

  getOrderStatsData: async (days: number = 7) => {
    await delay(500)
    // 根据天数返回相应的数据
    const data = mockDashboardData.orderStats.slice(-days)
    return createSuccessResponse(data)
  },

  getRecentActivities: async () => {
    await delay(500)
    return createSuccessResponse(mockDashboardData.activities)
  }
}

// 导出所有模拟API
export const mockAPI = {
  auth: mockAuthAPI,
  user: mockUserAPI,
  merchant: mockMerchantAPI,
  travel: mockTravelAPI,
  animal: mockAnimalAPI,
  order: mockOrderAPI,
  system: mockSystemAPI,
  permission: mockPermissionAPI,
  dashboard: mockDashboardAPI  // 添加仪表板API
}

export default mockAPI