<template>
  <Dialog v-model="dialogVisible" title="物资导入" width="400">
    <el-upload
      ref="uploadRef"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="upload.headers"
      :action="upload.url + '?updateSupport=' + upload.updateSupport"
      :disabled="upload.isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <Icon icon="ep:upload" class="el-icon--upload" />
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </div>
      </template>
    </el-upload>

    <template #footer>
      <el-button type="primary" @click="submitFileForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { getAccessToken } from '@/utils/auth'

defineOptions({ name: 'ImportDialog' })

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

// 弹窗状态
const dialogVisible = ref(false) // 弹窗的是否展示
const uploadRef = ref() // 上传组件 Ref

// 上传参数
const upload = reactive({
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getAccessToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/iscs/materials/importMaterials'
})

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 下载模板操作 */
const importTemplate = () => {
  window.open(import.meta.env.VITE_APP_BASE_API + '/iscs/materials/importTemplate')
}

/** 文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const handleFileSuccess = (response: any) => {
  upload.isUploading = false
  uploadRef.value.clearFiles()
  dialogVisible.value = false
  message.success(response.msg)
  emit('success')
}

/** 提交上传文件 */
const submitFileForm = () => {
  uploadRef.value.submit()
}
</script>
