<template>
  <span @click.stop="open"
    ><slot></slot>
    <a-modal
      v-model:visible="data.visible"
      :title="t('导入数据')"
      :maskClosable="false"
      :width="660"
      @ok="close"
      @cancel="close"
      @click.stop=""
    >
      <div class="my-6">
        <a-upload
          name="file"
          accept=".json,.txt"
          :headers="data.headers"
          :max-count="1"
          :showUploadList="true"
          :action="data.action"
          :loading="true"
          @change="handleChange"
        >
          <img :src="BgImg" class="mx-auto" />
          <div class="a-upload__text"
            ><img :src="upImg" /><div
              >{{ t('将文件拖到此处上传')
              }}<em>{{ t('或者，您可以单击此处选择一个文件') }}</em></div
            ></div
          >
        </a-upload>
      </div>
    </a-modal>
  </span>
</template>

<script setup lang="ts">
  import { reactive } from 'vue';
  import BgImg from '/@/assets/images/import.png';
  import upImg from '/@/assets/images/upload.png';
  import { getAppEnvConfig } from '/@/utils/env';
  import { getToken } from '/@/utils/auth';
  import type { UploadChangeParam } from 'ant-design-vue';
  import { message } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  let emits = defineEmits(['close']);
  const data: {
    visible: boolean;
    action: string;
    headers: { Authorization: string };
  } = reactive({
    visible: false,
    action: '',
    headers: { Authorization: '' },
  });

  async function open() {
    data.visible = true;
    data.action = getAppEnvConfig().VITE_GLOB_API_URL + '/version/datasync/import';
    data.headers.Authorization = `Bearer ${getToken()}`;
    data.enctype = 'multipart/form-data';
  }
  function close() {
    data.visible = false;
    emits('close');
  }
  function handleChange(info: UploadChangeParam) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      if (info.file && info.file.response && info.file.response.code == 0) {
        message.success(t(`{name}导入成功！`, { name: info.file.name }));
        close();
      } else {
        message.error(t('导入数据失败！'));
      }
    } else if (info.file.status === 'error') {
      message.error(t(`{name}上传失败.`, { name: info.file.name }));
    }
  }
</script>
<style lang="less" scoped>
  :deep(.ant-upload.ant-upload-select) {
    display: block;
  }

  .upload-demo {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .a-upload-dragger {
    width: 615px;
    height: 370px;
    border: none;
  }

  .a-upload__text {
    position: absolute;
    bottom: 118px;
    right: 70px;
    color: #333;
    width: 290px;
    text-align: center;

    img {
      display: inline-block;
      margin-bottom: 12px;
    }
  }

  em {
    display: block;
    font-size: 12px;
    color: #91a6d6;
    font-style: normal;
  }
</style>
