<template>
  <el-dialog v-model="dialogVisible" title="字体导入" width="500px" :close-on-click-modal="false">
    <div class="import-dialog-content">
      <div class="import-section">
        <h4>上传字体文件</h4>
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          @change="handleFileChange"
          @exceed="handleExceed"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip"> 仅支持字体格式文件 </div>
          </template>
        </el-upload>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="importLoading" @click="handleImport">
          开始导入
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- <Dialog v-model="dialogVisible" title="物料导入" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </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 { getAccessToken, getTenantId } from '@/utils/auth'
import { importFont } from '@/api/print/font'

defineOptions({ name: 'MaterialImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const importLoading = ref(false)
const selectedFile = ref<File | null>(null)
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL +
  import.meta.env.VITE_API_URL +
  '/print/material-base-info/export-import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的物料数据

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

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    formLoading.value = false
    return
  }
  // 拼接提示语
  // const data = response.data
  // let text = '上传成功数量：' + data.createMaterials?.length + ';'
  // if (data.createMaterials) {
  //   for (let materialNo of data.createMaterials) {
  //     text += '< ' + materialNo + ' >'
  //   }
  // }
  // text += '更新成功数量：' + data.updateMaterials?.length + ';'
  // if (data.updateMaterials) {
  //   for (const materialNo of data.updateMaterials) {
  //     text += '< ' + materialNo + ' >'
  //   }
  // }
  // text += '更新失败数量：' + Object.keys(data.failureMaterials || {}).length + ';'
  // if (data.failureMaterials) {
  //   for (const materialNo in data.failureMaterials) {
  //     text += '< ' + materialNo + ': ' + data.failureMaterials[materialNo] + ' >'
  //   }
  // }
  // message.alert(text)
  formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success')
}

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

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

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
}

const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }
  importLoading.value = true
  try {
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('fileName', selectedFile.value.name)

    await importFont(formData)
    dialogVisible.value = false
    selectedFile.value = null
    uploadRef.value?.clearFiles()
    emits('success')
  } catch (error) {
    ElMessage.error('导入失败:' + error)
  } finally {
    importLoading.value = false
  }
}
</script>
<style scoped>
.import-dialog-content {
  padding: 0;
}

.import-section {
  margin-bottom: 24px;
}
.import-section:last-child {
  margin-bottom: 0;
}
.import-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}
.template-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
</style>
