import { ref } from 'vue'
import { taskParamsApi, onInterruptApi, statusApi, logsApi, modelExportApi, getExportModelsApi } from '@/apis/train/index.ts'


export const useMain = () => {

  const getExportModelLoading = ref(false)
  // 获取可导出的模型
  const getExportModels = async (taskId: string) => {
    if (getExportModelLoading.value) return false
    getExportModelLoading.value = true
    const res = await getExportModelsApi(taskId).catch(err => {
      return err
    })
    getExportModelLoading.value = false
    return res
  }

  // 模型导出
  const exportLoading = ref(false)
  const modelExport = async (data: Record<string, any>) => {
    if (exportLoading.value) return false
    exportLoading.value = true
    const res = await modelExportApi(data).catch(err => {
      return err
    })
    console.log('modelExportApi', res)
    exportLoading.value = false
    return res
  }

  // 中断任务
  const onInterruptLoading = ref(false)
  const onInterrupt = async (taskId: string) => {
    if (onInterruptLoading.value) return false
    onInterruptLoading.value = true
    const res = await onInterruptApi(taskId).catch(err => {
      return err
    })
    onInterruptLoading.value = false
    return res
  }

  // 获取任务状态
  const statusLoading = ref(false)
  const getStatus = async (taskId: string) => {
    if (statusLoading.value) return false
    statusLoading.value = true
    const res = await statusApi(taskId).catch(err => {
      return err
    })
    statusLoading.value = false
    return res
  }

  // 获取任务日志
  const logsLoading = ref(false)
  const getLogs = async (taskId: string) => {
    if (logsLoading.value) return false
    logsLoading.value = true
    const res = await logsApi(taskId).catch(err => {
      return err
    })
    logsLoading.value = false
    return res
  }

  // 获取详情
  const taskParamsLoading = ref(false)
  const getTaskParams = async (taskId: string) => {
    if (taskParamsLoading.value) return false
    taskParamsLoading.value = true
    const res = await taskParamsApi(taskId).catch(err => {
      return err
    })
    taskParamsLoading.value = false
    return res
  }

  return {
    taskParamsRequest: {
      request: getTaskParams,
      loading: taskParamsLoading
    },
    interruptRequest: {
      request: onInterrupt,
      loading: onInterruptLoading
    },
    statusRequest: {
      request: getStatus,
      loading: statusLoading
    },
    logsRequest: {
      request: getLogs,
      loading: logsLoading
    },
    modelExportRequest: {
      request: modelExport,
      loading: exportLoading
    },
    getExportModelsRequest: {
      loading: getExportModelLoading,
      request: getExportModels
    }
  }
}
