import request from '@/utils/request'
import { getUploadList as mockGetUploadList } from '@/api/mock/version'

// 获取已安装版本列表
export function getInstalledVersions(params) {
  return request({
    url: '/api/devops/versions/installed',
    method: 'get',
    params
  })
}

// 上传安装包
export function uploadPackage(formData) {
  return request({
    url: '/api/devops/versions/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 安装软件包
export function installPackage(params) {
  return request({
    url: '/api/devops/versions/install',
    method: 'post',
    data: params
  })
}

// 卸载软件包
export function uninstallPackage(params) {
  return request({
    url: '/api/devops/versions/uninstall',
    method: 'post',
    data: params
  })
}

// 获取安装进度
export function getInstallProgress(taskId) {
  return request({
    url: `/api/devops/versions/install/progress/${taskId}`,
    method: 'get'
  })
}

// 获取上传文件列表
export function getUploadList(params) {
  return request({
    url: '/api/devops/versions/uploadList',
    method: 'get',
    params
  })
}

// Mock API 兜底实现
const mockApi = {
  async getInstalledVersions(params = {}) {
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const mockData = [
      {
        id: 1,
        name: 'leador-data-analyser',
        version: '192.168.10.10',
        updateTime: '2024-01-15 10:30:25'
      },
      {
        id: 2,
        name: '激光网卡',
        version: '0.3.1',
        updateTime: '2024-01-14 16:45:12'
      },
      {
        id: 3,
        name: 'leador-robot-config-web',
        version: '0.7.133',
        updateTime: '2024-01-13 09:15:30'
      },
      {
        id: 4,
        name: 'ros-kinetic-leador-auto-pursuit-local-planner',
        version: '0.0.1',
        updateTime: '2024-01-12 14:20:45'
      },
      {
        id: 5,
        name: 'ros-kinetic-leador-en-control-msgs',
        version: '1.0.0',
        updateTime: '2024-01-11 11:35:20'
      },
      {
        id: 6,
        name: 'ros-kinetic-leador-ld-sensor-msgs',
        version: '2.0.1',
        updateTime: '2024-01-10 08:50:15'
      }
    ]
    
    // 模拟搜索过滤
    let filteredData = mockData
    if (params.search) {
      const keyword = params.search.toLowerCase()
      filteredData = mockData.filter(item => 
        item.name.toLowerCase().includes(keyword) || 
        item.version.toLowerCase().includes(keyword)
      )
    }
    
    // 模拟分页
    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)
    
    return Promise.resolve({
      code: 200,
      data: {
        list,
        total,
        pageNum,
        pageSize
      },
      message: '获取成功'
    })
  },

  async uploadPackage(formData) {
    await new Promise(resolve => setTimeout(resolve, 1000))
    return Promise.resolve({
      code: 200,
      data: {
        fileId: 'file_' + Date.now(),
        fileName: formData.get('file').name,
        fileSize: formData.get('file').size,
        url: '/temp/upload/' + formData.get('file').name
      },
      message: '上传成功'
    })
  },

  async installPackage(params) {
    await new Promise(resolve => setTimeout(resolve, 2000))
    return Promise.resolve({
      code: 200,
      data: {
        taskId: 'task_' + Date.now(),
        status: 'success'
      },
      message: '安装成功'
    })
  },

  async uninstallPackage(params) {
    await new Promise(resolve => setTimeout(resolve, 1000))
    return Promise.resolve({
      code: 200,
      message: '卸载成功'
    })
  }
}

// 导出带兜底的API函数
export const apiWithFallback = {
  async getInstalledVersions(params) {
    try {
      return await getInstalledVersions(params)
    } catch (error) {
      console.warn('使用Mock API:', error)
      return await mockApi.getInstalledVersions(params)
    }
  },

  async getUploadList(params) {
    try {
      return await getUploadList(params)
    } catch (error) {
      console.warn('使用Mock API:', error)
      return await mockGetUploadList(params)
    }
  },

  async uploadPackage(formData) {
    try {
      return await uploadPackage(formData)
    } catch (error) {
      console.warn('使用Mock API:', error)
      return await mockApi.uploadPackage(formData)
    }
  },

  async installPackage(params) {
    try {
      return await installPackage(params)
    } catch (error) {
      console.warn('使用Mock API:', error)
      return await mockApi.installPackage(params)
    }
  },

  async uninstallPackage(params) {
    try {
      return await uninstallPackage(params)
    } catch (error) {
      console.warn('使用Mock API:', error)
      return await mockApi.uninstallPackage(params)
    }
  }
}
