import { useDatasetHooks } from '@/views/dataManage/index/hooks/dataset.ts'
import { ref } from 'vue'
import { downloadFile } from '@/utils/download/index.ts'

export const useDatasetServer = () => {
  const { testDatasetListRequest, trainDatasetListRequest, deleteRequest, updateRequest, downloadRequest } = useDatasetHooks()

  const testDataset = ref([])
  const getTestDataset = async () => {
    const res = await testDatasetListRequest.request()
    if (res?.code == 200) {
      testDataset.value = res.data?.datasets
    }
    return res
  }

  const trainDataset = ref([])
  const getTrainDataset = async () => {
    const res = await trainDatasetListRequest.request()
    if (res?.code == 200) {
      trainDataset.value = res.data?.datasets
    }
    return res
  }

  const deleteDataset = async (id: string) => {
    const res = await deleteRequest.request(id)
    return res
  }

  const updateDataset = async (params: Record<string, any>) => {
    const res = await updateRequest.request(params)
    return res
  }

  const onDatasetDownload = async (data: Record<string, any>) => {
    const { fileName, type, id } = data

    const res = await downloadRequest.request(data)
    console.log('onDatasetDownload', res)
    // if (res.status != 200) return res
    const blob = await res.blob()
    const hrefUrl = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadFile(hrefUrl, fileName);

    return res

  }


  const state = {
    testDataset,
    trainDataset,
  }

  const api = {
    getTestDataset,
    getTrainDataset,
    deleteDataset,
    updateDataset,
    onDatasetDownload
  }

  const requestMap = {
    testDatasetListRequest,
    trainDatasetListRequest,
    deleteRequest,
    updateRequest
  }

  return {
    state,
    api,
    requestMap,
  }
}
