<template>
  <a-modal
    v-model:visible="props.visible"
    :title="dialogTitle"
    width="450"
    :okText="''"
    @cancel="dialogClose"
  >
    <a-upload-dragger
      style="width: 400px; padding: 40px"
      action="/api/user/import"
      :headers="uploadHeaders"
      name="file"
      ref="upload"
      @change="handleChange"
      :before-upload="beforeUpload"
      :showUploadList="false"
      v-model:file-list="fileList"
      :maxCount="1"
      v-perm="['sys:user:import']"
    >
      <CloudUploadOutlined style="color: #165dff; font-size: 60px" />
      <div class="el-upload__text"> 点击或将文件拖拽到这里上传</div>
    </a-upload-dragger>
    <div style="margin-top: 20px">
      <span>只能上传 xls、xlsx 文件</span>
      <a-button type="link" @click="handleDownload">下载模板</a-button>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { getTemplateByCode } from '@/api/system/user';
  import { computed, reactive, ref } from 'vue';
  import { CloudUploadOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import { useUserStore } from '@/store/modules/user';
  import type { UploadChangeParam } from 'ant-design-vue';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    id: {
      type: Number,
      required: true,
      default: 0,
    },
  });

  /**
   * 定义参数变量
   */
  const uploadHeaders = reactive({
    authorization: useUserStore().getToken,
  });
  const upload = ref();
  const fileList = ref([]);
  const emit = defineEmits(['success', 'update:visible']);

  /**
   * 定义弹窗标题
   */
  const dialogTitle = computed(() => {
    return '导入用户';
  });

  /**
   * 关闭窗体
   */
  const dialogClose = () => {
    emit('update:visible', false);
  };

  /**
   * 上传文件之前验证
   */
  const beforeUpload = (file) => {
    const isLt2M = file.size / 1024 / 1024 < 200;
    if (!isLt2M) {
      message.warning('大小不能超过200MB!');
      return false;
    }
    if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
      message.warning('请上传.xlsx .xls');
      return false;
    }
    return true;
  };

  /**
   * 执行上传文件
   * @param param0 参数
   */
  const handleChange = ({ file }: UploadChangeParam) => {
    const status = file.status;
    if (status === 'done') {
      let data = file.response;
      if (data.code != 0) {
        message.error(data.msg || '导入失败');
      } else {
        message.success('导入成功');
        emit('update:visible', false);
        emit('success');
      }
    } else if (status === 'error') {
      message.error('导入失败');
    }
  };

  /**
   * 执行下载文件
   */
  const handleDownload = async () => {
    const res = await getTemplateByCode('user_import');
    window.open(res.filePath);
  };
</script>
