/**
 * 地图列表 Mock API
 */

// 模拟延迟
const delay = (min = 300, max = 800) => {
  const time = Math.random() * (max - min) + min
  return new Promise(resolve => setTimeout(resolve, time))
}

// 模拟地图数据
const mockMaps = [
  {
    id: '1',
    name: '上海办公楼一层',
    status: 'ok',
    thumbUrl: 'http://192.168.1.183:9006/test/218/map/GSY-06/shanghai01/tilemap/thumbnail.png',
    remark: '办公楼主要区域地图，包含接待区、办公区、会议室等',
    updatedAt: '2024-01-15T10:30:00Z',
    starred: true,
    createdBy: '张三',
    tags: ['办公', '室内'],
    size: '2.5MB'
  },
  {
    id: '2', 
    name: '工厂车间A区',
    status: 'scanning',
    thumbUrl: '',
    remark: '生产车间A区域，正在进行地图扫描更新',
    updatedAt: '2024-01-14T16:20:00Z',
    starred: false,
    createdBy: '李四',
    tags: ['工厂', '车间'],
    size: '4.1MB'
  },
  {
    id: '3',
    name: '仓库主区域',
    status: 'down',
    thumbUrl: 'http://192.168.1.183:9006/test/216/YF-01/lantu21/tilemap/thumbnail.png',
    remark: '仓库主要存储区域，当前地图数据异常需要重新构建',
    updatedAt: '2024-01-13T09:15:00Z',
    starred: false,
    createdBy: '王五',
    tags: ['仓库', '存储'],
    size: '1.8MB'
  },
  {
    id: '4',
    name: '研发中心二楼',
    status: 'ok',
    thumbUrl: '',
    remark: '研发中心实验室区域，包含多个实验室和会议室',
    updatedAt: '2024-01-12T14:45:00Z',
    starred: true,
    createdBy: '赵六',
    tags: ['研发', '实验室'],
    size: '3.2MB'
  },
  {
    id: '5',
    name: '停车场地下一层',
    status: 'ok',
    thumbUrl: '',
    remark: '地下停车场区域图，包含车位信息和通道标识',
    updatedAt: '2024-01-11T11:20:00Z',
    starred: false,
    createdBy: '钱七',
    tags: ['停车场', '地下'],
    size: '1.5MB'
  },
  {
    id: '6',
    name: '食堂餐厅区域',
    status: 'ok',
    thumbUrl: '',
    remark: '员工食堂及餐厅区域，包含用餐区和厨房区域',
    updatedAt: '2024-01-10T08:30:00Z',
    starred: false,
    createdBy: '孙八',
    tags: ['食堂', '餐厅'],
    size: '2.1MB'
  },
  {
    id: '7',
    name: '户外园区',
    status: 'scanning',
    thumbUrl: '',
    remark: '公司户外园区，包含步行道、休息区和绿化带',
    updatedAt: '2024-01-09T15:10:00Z',
    starred: true,
    createdBy: '周九',
    tags: ['户外', '园区'],
    size: '5.8MB'
  },
  {
    id: '8',
    name: '会议中心',
    status: 'ok',
    thumbUrl: '',
    remark: '多功能会议中心，包含大型会议厅和小型讨论室',
    updatedAt: '2024-01-08T13:25:00Z',
    starred: false,
    createdBy: '吴十',
    tags: ['会议', '中心'],
    size: '2.9MB'
  }
]

// 当前数据（模拟数据库）
let currentMaps = [...mockMaps]

/**
 * 获取地图列表
 * @param {Object} params - 查询参数
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页数量
 * @param {string} params.keyword - 搜索关键字
 * @param {string} params.status - 状态筛选 ('all'|'ok'|'down'|'scanning')
 * @param {string} params.sort - 排序方式 ('updated'|'name'|'status')
 * @param {string} params.order - 排序顺序 ('asc'|'desc')
 */
export const listMaps = async (params = {}) => {
  await delay()
  
  const {
    page = 1,
    pageSize = 12,
    keyword = '',
    status = 'all',
    sort = 'updated',
    order = 'desc'
  } = params

  // 模拟错误（5% 概率）
  if (Math.random() < 0.05) {
    throw new Error('网络连接异常，请重试')
  }

  let filteredMaps = [...currentMaps]

  // 关键字搜索
  if (keyword.trim()) {
    const searchKey = keyword.toLowerCase().trim()
    filteredMaps = filteredMaps.filter(map => 
      map.name.toLowerCase().includes(searchKey) ||
      (map.remark && map.remark.toLowerCase().includes(searchKey)) ||
      (map.tags && map.tags.some(tag => tag.toLowerCase().includes(searchKey)))
    )
  }

  // 状态筛选
  if (status !== 'all') {
    filteredMaps = filteredMaps.filter(map => map.status === status)
  }

  // 排序
  filteredMaps.sort((a, b) => {
    let aVal, bVal
    
    switch (sort) {
      case 'name':
        aVal = a.name.toLowerCase()
        bVal = b.name.toLowerCase()
        break
      case 'status':
        // 状态优先级：ok > scanning > down
        const statusOrder = { ok: 2, scanning: 1, down: 0 }
        aVal = statusOrder[a.status] || 0
        bVal = statusOrder[b.status] || 0
        break
      case 'updated':
      default:
        aVal = new Date(a.updatedAt).getTime()
        bVal = new Date(b.updatedAt).getTime()
        break
    }

    if (order === 'asc') {
      return aVal > bVal ? 1 : aVal < bVal ? -1 : 0
    } else {
      return aVal < bVal ? 1 : aVal > bVal ? -1 : 0
    }
  })

  // 分页
  const total = filteredMaps.length
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const list = filteredMaps.slice(start, end)

  return {
    code: 200,
    message: '获取成功',
    data: {
      total,
      list,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    }
  }
}

/**
 * 获取单个地图信息
 * @param {string} id - 地图ID
 */
export const getMap = async (id) => {
  await delay(200, 400)
  
  const map = currentMaps.find(m => m.id === id)
  if (!map) {
    throw new Error('地图不存在')
  }

  return {
    code: 200,
    message: '获取成功',
    data: map
  }
}

/**
 * 创建地图
 * @param {Object} mapData - 地图数据
 */
export const createMap = async (mapData) => {
  await delay(500, 1000)
  
  // 模拟错误
  if (Math.random() < 0.1) {
    throw new Error('创建失败，请重试')
  }

  const newMap = {
    id: String(Date.now()),
    name: mapData.name || '新建地图',
    status: 'scanning',
    thumbUrl: '',
    remark: mapData.remark || '',
    updatedAt: new Date().toISOString(),
    starred: false,
    createdBy: '当前用户',
    tags: mapData.tags || [],
    size: '0MB'
  }

  currentMaps.unshift(newMap)

  return {
    code: 200,
    message: '创建成功',
    data: newMap
  }
}

/**
 * 更新地图
 * @param {string} id - 地图ID
 * @param {Object} updateData - 更新数据
 */
export const updateMap = async (id, updateData) => {
  await delay(300, 600)
  
  const mapIndex = currentMaps.findIndex(m => m.id === id)
  if (mapIndex === -1) {
    throw new Error('地图不存在')
  }

  currentMaps[mapIndex] = {
    ...currentMaps[mapIndex],
    ...updateData,
    updatedAt: new Date().toISOString()
  }

  return {
    code: 200,
    message: '更新成功',
    data: currentMaps[mapIndex]
  }
}

/**
 * 删除地图
 * @param {string|string[]} ids - 地图ID或ID数组
 */
export const deleteMap = async (ids) => {
  await delay(400, 700)
  
  const idArray = Array.isArray(ids) ? ids : [ids]
  
  // 模拟删除失败
  if (Math.random() < 0.05) {
    throw new Error('删除失败，请重试')
  }

  currentMaps = currentMaps.filter(map => !idArray.includes(map.id))

  return {
    code: 200,
    message: `成功删除 ${idArray.length} 个地图`,
    data: { deletedCount: idArray.length }
  }
}

/**
 * 批量发布地图
 * @param {string[]} ids - 地图ID数组
 */
export const publishMaps = async (ids) => {
  await delay(800, 1200)
  
  const updatedMaps = []
  
  ids.forEach(id => {
    const mapIndex = currentMaps.findIndex(m => m.id === id)
    if (mapIndex !== -1) {
      currentMaps[mapIndex] = {
        ...currentMaps[mapIndex],
        status: 'ok',
        updatedAt: new Date().toISOString()
      }
      updatedMaps.push(currentMaps[mapIndex])
    }
  })

  return {
    code: 200,
    message: `成功发布 ${updatedMaps.length} 个地图`,
    data: { publishedMaps: updatedMaps }
  }
}

/**
 * 复制地图
 * @param {string} id - 原地图ID
 * @param {string} newName - 新地图名称
 */
export const copyMap = async (id, newName) => {
  await delay(600, 1000)
  
  const originalMap = currentMaps.find(m => m.id === id)
  if (!originalMap) {
    throw new Error('原地图不存在')
  }

  const newMap = {
    ...originalMap,
    id: String(Date.now()),
    name: newName || `${originalMap.name}_副本`,
    status: 'scanning',
    updatedAt: new Date().toISOString(),
    starred: false
  }

  currentMaps.unshift(newMap)

  return {
    code: 200,
    message: '复制成功',
    data: newMap
  }
}

/**
 * 下载地图
 * @param {string} id - 地图ID
 * @param {string[]} components - 下载组件类型
 */
export const downloadMap = async (id, components = []) => {
  await delay(1000, 2000)
  
  const map = currentMaps.find(m => m.id === id)
  if (!map) {
    throw new Error('地图不存在')
  }

  // 模拟生成下载链接
  const downloadUrl = `https://example.com/downloads/map_${id}_${Date.now()}.zip`

  return {
    code: 200,
    message: '下载链接生成成功',
    data: {
      downloadUrl,
      components,
      estimatedSize: map.size,
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
    }
  }
}

export default {
  listMaps,
  getMap,
  createMap,
  updateMap,
  deleteMap,
  publishMaps,
  copyMap,
  downloadMap
}
