import { useMain as useDataExportMain } from '@/views/dataManage/index/hooks/dataExport.ts'
import TemplateFile from '@/assets/files/dataExport/导入标注模板文件.csv?url'
import { downloadFile } from '@/utils/download/index.ts'
import _ from "lodash";
import { ref } from 'vue'

export const useMain = () => {

  const { listRequest, updateRequest, exportUrlRequest, importLabelRequest } = useDataExportMain()

  const exportData = ref<Record<string, any>>([])
  const exportListParams = ref({
    date_str: null,
    label_info: null,
    track_id: null
  })

  const createListParams = () => {
    const raw = exportListParams.value
    const params = {} as Record<string, any>
    if (raw.date_str) params.date_str = raw.date_str
    if (raw.label_info) params.label_info = raw.label_info
    if (raw.track_id) params.label_info = raw.track_id
    // if (raw)
    return params
  }

  // 获取导出数据
  const getExportData = async (params?: Record<string, any>) => {
    const customParams = params ?? createListParams()
    const res = await listRequest.request(customParams)
    if (res?.code == 200) {
      exportData.value = res.data
      console.log('exportData', exportData)
    }
    return res
  }

  const onExportDataSearch = _.debounce((params?: Record<string, any>) => {
    getExportData(params)
  }, 1000)

  const onUpdateLabel = async (params: Record<string, any>) => {
    const res = await updateRequest.request(params)
    // if (res?.code == 200) {
    //   exportData.value = res.data
    //   console.log('exportData', exportData)
    // }
    return res
  }

  // 获取导出文件地址
  const getExportFileUrl = async (params: Record<string, any>) => {
    const res = await exportUrlRequest.request(params)
    return res
  }

  // 下载导入标注数据模板
  const onDownloadLabelTemplate = () => {
    downloadFile(TemplateFile, '导入标注模板文件.csv')
  }

  // 导入标注数据
  const onImportLabel = async (params: Record<string, any>) => {
    const res = await importLabelRequest.request(params)
    return res
  }

  const state = {
    exportListParams: exportListParams,
    exportData: exportData
  }

  return {
    state,
    api: {
      getExportData,
      onExportDataSearch,
      onUpdateLabel,
      onDownloadLabelTemplate,
      getExportFileUrl,
      onImportLabel
    },
    requestMap: {
      listRequest,
      updateRequest,
      exportUrlRequest,
      importLabelRequest
    }
  }
}
