<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="选择方式" prop="inputType">
        <el-radio-group v-model="inputType">
          <el-radio label="path">选择路径</el-radio>
          <el-radio label="upload">上传文件</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="inputType === 'path'" label="路径" prop="path">
        <el-input v-model="formData.path" placeholder="请输入路径" />
      </el-form-item>
      <el-form-item v-if="inputType === 'upload'" label="上传文件">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :auto-upload="false"
          accept=".zip,image/*"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          drag
          multiple
        >
          <Icon icon="ep:upload" class="el-icon--upload" />
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持上传 zip 压缩包或多张图片，上传后路径将自动生成
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DatasetApi, DatasetVO } from '@/api/annotation/dataset'
import { UploadFile, UploadUserFile } from 'element-plus'

/** 识别数据集 表单 */
defineOptions({ name: 'DatasetForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const inputType = ref('path') // 选择方式：path-路径，upload-上传文件
const formData = ref({
  id: undefined as number | undefined,
  name: undefined as string | undefined,
  path: undefined as string | undefined,
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  path: [{ required: true, message: '路径不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const uploadRef = ref()
const fileList = ref<UploadUserFile[]>([]) // 上传文件列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  inputType.value = 'path'
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DatasetApi.getDataset(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 文件变化时 */
const handleFileChange = (uploadFile: UploadFile) => {
  if (uploadFile.name) {
    const fileName = uploadFile.name.replace(/\.[^/.]+$/, '') // 移除扩展名
    formData.value.path = `/dataset/${fileName}`
  }
}

/** 移除文件时 */
const handleFileRemove = () => {
  fileList.value = []
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 如果选择上传文件但没有选择文件，提示错误
  if (inputType.value === 'upload' && fileList.value.length === 0) {
    message.error('请选择要上传的文件')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DatasetVO
    if (formType.value === 'create') {
      // 如果选择路径模式，提交 name 和 path
      if (inputType.value === 'path') {
        await DatasetApi.createDataset(data)
      } else {
        // 如果选择上传文件模式，只提交 name
        const createData = { name: data.name, path: '' }
        console.log('创建数据集:', createData)
        const result = await DatasetApi.createDataset(createData)
        console.log('创建结果:', result)
        console.log('文件列表:', fileList.value)
        // 再上传文件
        const files = fileList.value.map((file: any) => file.raw)
        console.log('要上传的文件:', files)
        await DatasetApi.addImages({ id: result, files })
      }
      message.success(t('common.createSuccess'))
    } else {
      await DatasetApi.updateDataset(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    path: undefined,
  }
  fileList.value = []
  formRef.value?.resetFields()
}
</script>