<template>
  <component
    :is="modalName"
    :wrapClassName="props.isDefaultModal ? '' : 'modal-box'"
    @register="registerModal"
    :title="title"
    @cancel="emit('success')"
  >
    <div class="import-box">
      <a-upload-dragger
        v-model:file-list="fileList"
        name="file"
        :multiple="true"
        :action="action"
        :beforeUpload="beforeUpload"
        :data="data"
        :accept="accept"
        :headers="{ Authorization: `Bearer ${getToken()}` }"
        :showUploadList="{ showRemoveIcon: false }"
        @change="handleChange"
      >
        <img src="/src/assets/images/import.png" />
        <img src="/src/assets/images/upload.png" class="upload-icon" />
        <span class="upload-text">将文件拖到此处上传</span>
        <span class="upload-tip">或者，您可以单击此处选择一个文件</span>
      </a-upload-dragger>
      <a-button size="large" @click="downLoadTemplate" v-if="templateApi || downLoadUrl"
        >下载模板</a-button
      >
    </div>
  </component>
</template>
<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import type { UploadChangeParam } from 'ant-design-vue';
  import { BasicModal, useModalInner, BasicModalExcel } from '/@/components/Modal';
  import { getAppEnvConfig } from '/@/utils/env';
  import { getToken } from '/@/utils/auth';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { downloadFile } from '/@/api/sys/download';
  import { downloadByData } from '/@/utils/file/download';
  import { message } from 'ant-design-vue';

  const props = defineProps({
    importUrl: String,
    data: Object,
    isDefaultModal: {
      type: Boolean,
      default: true,
    },
    accept: {
      type: String,
      default:
        '.csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    },
  });

  const title = ref('');
  const fileList = ref();
  const importType = ref('');
  const { notification } = useMessage();

  const emit = defineEmits(['success', 'register']);
  let downLoadUrl;
  let templateApi;
  let templateTitle;

  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    title.value = data.title;
    downLoadUrl = data.downLoadUrl;
    importType.value = data.type;
    templateApi = data.api;
    templateTitle = data.templateTitle;
    fileList.value = [];
    setModalProps({
      destroyOnClose: true,
      maskClosable: false,
      footer: null,
      width: 800,
      height: 500,
      imgSrc: data.imgSrc || '',
    });
  });
  const action = computed(() => {
    return getAppEnvConfig().VITE_GLOB_API_URL + props.importUrl;
  });

  const modalName = computed(() => {
    return props.isDefaultModal ? BasicModal : BasicModalExcel;
  });

  const beforeUpload = (file) => {
    const isFile1000M = file.size / 1024 / 1024 > 1000;
    if (isFile1000M) {
      notification.error({
        message: 'Tip',
        description: '文件大小不能超过1G！',
      });
      return false;
    }
  };

  const downLoadTemplate = async () => {
    const method = importType.value || 'GET';
    let res;
    if (templateApi) {
      res = await templateApi();
    } else {
      res = await downloadFile(downLoadUrl, { isTemplate: true, ...props.data }, method);
    }
    downloadByData(
      res.data,
      `${templateTitle || '模板'}.xlsx`,
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
  };

  const handleChange = (info: UploadChangeParam) => {
    if (info.file.status === 'done') {
      if (info.file && info.file.response && info.file.response.code == 0) {
        message.success('导入成功');
      } else {
        fileList.value = fileList.value.filter((x) => x.uid !== info.file.uid);
        message.error(info.file.response.msg || '导入失败');
      }
    } else if (info.file.status === 'error') {
      fileList.value = fileList.value.filter((x) => x.uid !== info.file.uid);
      message.error('导入失败');
    }
  };
</script>
<style lang="less" scoped>
  .import-box {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    margin: 0 15px 15px;

    img {
      cursor: pointer;
    }

    .upload-icon {
      position: absolute;
      bottom: 112px;
      right: 165px;
    }

    .upload-tip {
      position: absolute;
      bottom: 58px;
      right: 79px;
      font-size: 13px;
      color: #91a6d6;
    }

    .upload-text {
      position: absolute;
      bottom: 80px;
      right: 111px;
      font-weight: 600;
      font-size: 16px;
      color: #000;
    }
  }

  :deep(.ant-upload.ant-upload-drag) {
    background: #fff;
    border: none;
  }

  :deep(.ant-btn-lg) {
    width: 82px;
    height: 32px;
    background: #1c8dff;
    border-radius: 4px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
