<template>
  <n-modal
    v-model:show="props.visible"
    preset="dialog"
    style="width: 450px"
    @close="dialogClose"
    positive-text="确定"
    negative-text="取消"
    @positive-click="dialogSubmit"
    @negative-click="dialogClose"
  >
    <template #header>
      {{ dialogTitle }}
    </template>
    <n-upload
      action="/api/level/import"
      :headers="uploadHeaders"
      name="file"
      ref="uploadRef"
      :default-upload="false"
      @change="handleChange"
      @before-upload="beforeUpload"
      v-model:file-list="fileList"
      :max="1"
      v-perm="['sys:level:import']"
    >
      <n-upload-dragger>
        <n-icon size="60" color="#165df">
          <CloudUploadOutlined />
        </n-icon>
        <div> 点击或将文件拖拽到这里上传</div>
      </n-upload-dragger>
    </n-upload>
    <div style="margin-top: 20px">
      <span>只能上传 xls、xlsx 文件</span>
    </div>
  </n-modal>
</template>

<script lang="ts" setup>
  import { getTemplateByCode } from '@/api/system/user';
  import { computed, reactive, ref } from 'vue';
  import { CloudUploadOutlined } from '@vicons/antd';
  import { useMessage } from 'naive-ui';
  import { useUserStore } from '@/store/modules/user';

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

  /**
   * 定义参数变量
   */
  const uploadHeaders = reactive({
    authorization: useUserStore().getToken,
  });
  const message = useMessage();
  const uploadRef = 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 }) => {
    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);
  };

  const dialogSubmit = async () => {
    uploadRef.value?.submit();
  };
</script>
