import { ref } from 'vue'
import { listApi, deleteApi, createTaskApi, onInterruptApi, statusApi, logsApi } from '@/apis/train/index.ts'


export const useMain = () => {
  // 获取列表
  const listLoading = ref(false)
  const getList = async () => {
    if (listLoading.value) return false
    listLoading.value = true
    const res = await listApi().catch(err => {
      return err
    })
    listLoading.value = false
    return res
  }

  // 删除任务
  const deleteLoading = ref(false)
  const deleteTask = async (taskId: string) => {
    if (deleteLoading.value) return false
    deleteLoading.value = true
    const res = await deleteApi(taskId).catch(err => {
      return err
    })
    deleteLoading.value = false
    return res
  }

  // 创建任务
  const createTaskLoading = ref(false)
  const createTask = async (params: Record<string, any>) => {
    if (createTaskLoading.value) return false
    createTaskLoading.value = true
    const res = await createTaskApi(params).catch(err => {
      return err
    })
    createTaskLoading.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
  }

  return {
    listRequest: {
      request: getList,
      loading: listLoading
    },
    deleteRequest: {
      request: deleteTask,
      loading: deleteLoading
    },
    createTaskRequest: {
      request: createTask,
      loading: createTaskLoading
    },
    onInterruptRequest: {
      request: onInterrupt,
      loading: onInterruptLoading
    },
    statusRequest: {
      request: getStatus,
      loading: statusLoading
    },
    logsRequest: {
      request: getLogs,
      loading: logsLoading
    }
  }
}
