<template>
  <Dialog v-model="dialogVisible" title="标本图片批量导入" width="500">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      drag
      :action="importUrl + '?updateSupport=' + updateSupport"
      :on-success="submitFormSuccess"
      style="max-width:250px;max-height: 30vh;margin-left: 20px"
      :auto-upload="false"
      :disabled="formLoading"
      :limit="1"
      :on-error="submitFormError"
      :http-request="httpRequest"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        <em>点击批量上传图片</em>
        <span>仅允许导入jpg、png、gif 格式文件。</span>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          <el-checkbox v-model="updateSupport" />
          是否更新已经存在的标本图片
        </div>
      </template>
    </el-upload>
    <template #footer >
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>

</template>
</Dialog>
</template>


<script lang="ts" setup>
import {UploadFilled} from "@element-plus/icons-vue";
import {useUpload} from "@/components/UploadFile/src/useUpload";
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/photosmanage/photo-group/createe'
defineOptions({ name: 'imageImportForm' })
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const message = useMessage() // 消息弹窗
const updateSupport = ref(0) // 是否更新已经存在的用户数据
const fileList = ref([]) // 文件列表
/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  updateSupport.value = 0
  fileList.value = []
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const {  httpRequest } = useUpload()

/** 图片上传成功 */

const submitFormSuccess = (response: any) => {
  console.log('tj',response)
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件

}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }

  formLoading.value = true
  uploadRef.value!.submit()
}

/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formLoading.value = false
  await nextTick()
  uploadRef.value?.clearFiles()
}
</script>
