<template>
  <Dialog v-model="dialogVisible" :title="t('action.import')" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl + '?updateSupport=' + updateSupport"
      :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">{{t('mall.dragFileHereOr')}}<em>{{t('mall.clickToUpload')}}</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>{{t('mall.onlyAllowImportXlsXlsxFiles')}}</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
          {{t('mall.downloadTemplate')}}
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{t('common.confirm')}}</el-button>
      <el-button @click="dialogVisible = false">{{t('common.cancel')}}</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="SystemUserImportForm" setup>
import * as ShopDeskApi from '@/api/mall/desk/shopDesk'
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'
const { t } = useI18n()

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

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/desk/shop-desk/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的用户数据

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

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error(t('mall.pleaseUploadFile'))
    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 = t('mall.uploadSuccessCount') + data.createDeskNames.length + ';'
  for (let desk of data.createDeskNames) {
    text += '< ' + desk + ' >'
  }
  text += t('mall.updateSuccessCount') + data.updateDeskNames.length + ';'
  for (const desk of data.updateDeskNames) {
    text += '< ' + desk + ' >'
  }
  text += t('mall.updateFailureCount') + Object.keys(data.failureDeskNames).length + ';'
  for (const desk in data.failureDeskNames) {
    console.log('desk:',desk)
    text += '< ' + desk + ': ' + data.failureDeskNames[desk] + ' >'
  }
  message.alert(text)
  // 发送操作成功的事件
  emits('success')

}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error(t('mall.uploadFailedPleaseReupload'))
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  console.log('clearFiles:')
  fileList.value = []
  formLoading.value = false
  uploadRef.value!.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error(t('mall.maxOneFileCanBeUploaded'))
}

/** 下载模板操作 */
const importTemplate = async () => {
  const data = await ShopDeskApi.exportShopDeskTemplate()
  download.excel(data, t('mall.batchImportTableNumberTemplateXls'))
}
</script>
