// 版本管理相关的 Mock API

// 模拟上传文件列表数据
const mockUploadList = [
  {
    id: 'upload_001',
    fileName: 'leador-navigation-system_v2.1.3.deb',
    size: 45678912, // 约43.5MB
    status: '待安装'
  },
  {
    id: 'upload_002', 
    fileName: 'ros-kinetic-sensor-driver_v1.5.2.tar',
    size: 23456789, // 约22.4MB
    status: '待安装'
  },
  {
    id: 'upload_003',
    fileName: 'lidar-config-tool_v3.0.1.zip',
    size: 12345678, // 约11.8MB
    status: '失败'
  },
  {
    id: 'upload_004',
    fileName: 'vehicle-control-module_v1.8.7.deb',
    size: 67890123, // 约64.7MB
    status: '失败'
  },
  {
    id: 'upload_005',
    fileName: 'map-processor_v2.3.0.tar',
    size: 34567890, // 约33.0MB
    status: '待安装'
  }
]

// 获取上传文件列表
export function getUploadList(params = {}) {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟搜索过滤
      let filteredData = [...mockUploadList]
      if (params.search) {
        const keyword = params.search.toLowerCase()
        filteredData = mockUploadList.filter(item => 
          item.fileName.toLowerCase().includes(keyword) || 
          item.version.toLowerCase().includes(keyword)
        )
      }

      // 模拟状态过滤
      if (params.status && params.status !== 'all') {
        filteredData = filteredData.filter(item => item.status === params.status)
      }

      // 模拟分页
      const pageNum = params.pageNum || 1
      const pageSize = params.pageSize || 10
      const total = filteredData.length
      const startIndex = (pageNum - 1) * pageSize
      const endIndex = startIndex + pageSize
      const list = filteredData.slice(startIndex, endIndex)

      resolve({
        code: 200,
        data: {
          list,
          total,
          pageNum,
          pageSize
        },
        message: '获取成功'
      })
    }, 300) // 模拟网络延迟
  })
}

// 上传文件
export function uploadFile(file) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const newUpload = {
        id: 'upload_' + Date.now(),
        fileName: file.name,
        size: file.size,
        version: extractVersion(file.name),
        status: '待安装',
        progress: 0
      }
      
      // 添加到mock数据中
      mockUploadList.unshift(newUpload)
      
      resolve({
        code: 200,
        data: newUpload,
        message: '上传成功'
      })
    }, 1000)
  })
}

// 安装文件
export function installFile(params) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const { id } = params
      const uploadItem = mockUploadList.find(item => item.id === id)
      
      if (!uploadItem) {
        reject({
          code: 404,
          message: '文件不存在'
        })
        return
      }

      // 模拟安装成功/失败
      const isSuccess = Math.random() > 0.2 // 80%成功率
      
      if (isSuccess) {
        uploadItem.status = '已安装'
        uploadItem.progress = 100
        resolve({
          code: 200,
          data: uploadItem,
          message: '安装成功'
        })
      } else {
        uploadItem.status = '失败'
        uploadItem.progress = 0
        reject({
          code: 500,
          message: '安装失败：系统版本不兼容'
        })
      }
    }, 2000)
  })
}

// 删除上传文件
export function deleteUploadFile(params) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { id } = params
      const index = mockUploadList.findIndex(item => item.id === id)
      
      if (index !== -1) {
        mockUploadList.splice(index, 1)
      }
      
      resolve({
        code: 200,
        message: '删除成功'
      })
    }, 500)
  })
}

// 批量安装
export function batchInstall(params) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { ids } = params
      const results = []
      
      ids.forEach(id => {
        const uploadItem = mockUploadList.find(item => item.id === id)
        if (uploadItem && uploadItem.status === '待安装') {
          // 模拟安装结果
          const isSuccess = Math.random() > 0.2
          uploadItem.status = isSuccess ? '已安装' : '失败'
          uploadItem.progress = isSuccess ? 100 : 0
          results.push({
            id,
            success: isSuccess,
            message: isSuccess ? '安装成功' : '安装失败'
          })
        }
      })
      
      resolve({
        code: 200,
        data: results,
        message: '批量安装完成'
      })
    }, 3000)
  })
}

// 清空上传列表
export function clearUploadList() {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 只清空待安装和失败的文件
      const activeStatuses = ['安装中']
      mockUploadList.splice(0, mockUploadList.length, 
        ...mockUploadList.filter(item => activeStatuses.includes(item.status))
      )
      
      resolve({
        code: 200,
        message: '清空成功'
      })
    }, 500)
  })
}

// 更新文件状态（用于模拟安装进度）
export function updateFileStatus(params) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const { id, status, progress } = params
      const uploadItem = mockUploadList.find(item => item.id === id)
      
      if (uploadItem) {
        uploadItem.status = status
        uploadItem.progress = progress || uploadItem.progress
      }
      
      resolve({
        code: 200,
        data: uploadItem,
        message: '状态更新成功'
      })
    }, 100)
  })
}

// 辅助函数：从文件名提取版本号
function extractVersion(filename) {
  const versionMatch = filename.match(/[vV]?(\d+\.\d+\.\d+)/)
  return versionMatch ? versionMatch[1] : '-'
}

// 导出所有API函数
export default {
  getUploadList,
  uploadFile,
  installFile,
  deleteUploadFile,
  batchInstall,
  clearUploadList,
  updateFileStatus
}
