<script lang="ts" setup>
import type { UploadUserFile } from 'element-plus';

import { ref, unref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { ExcelIcon } from '@vben/icons';

import { UploadFilled } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

import { downLoadTemplate, userImportData } from '#/api/system/user/user';
import { commonDownloadExcel } from '#/utils/file/download';

const emit = defineEmits<{ reload: [] }>();

// 是否更新/覆盖已存在的用户数据
const isUpdateRef = ref<boolean>(false);
// 上传的文件列表
const upFileListRef = ref<UploadUserFile[]>([]);
const [Modal, ModalApi] = useVbenModal({
  async onConfirm() {
    if (upFileListRef.value.length <= 0) {
      ElMessage.error('请上传附件');
      return;
    }
    this.confirmLoading = true;
    // 组装参数
    const data = {
      file: upFileListRef.value[0]!.raw as Blob,
      updateSupport: unref(isUpdateRef),
    };
    try {
      const { code, msg } = await userImportData(data);
      if (code === 200) {
        await ModalApi.close();
        // 更新列表
        emit('reload');
      } else {
        ElMessage.error(msg);
      }
    } catch (error) {
      console.error(error);
    } finally {
      this.confirmLoading = false;
    }
  },
});
// 下载用户模板
function userTemplate() {
  commonDownloadExcel(downLoadTemplate, '用户导入模板');
}
</script>
<template>
  <Modal title="用户导入">
    <el-upload
      drag
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      limit="1"
      :auto-upload="false"
      v-model:file-list="upFileListRef"
    >
      <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
      <div>点击或者拖拽到此处上传文件</div>
    </el-upload>
    <div class="mb-1.5 flex items-center gap-[4px]">
      <span>允许导入xlsx, xls文件</span>
      <ExcelIcon />
      <ElButton link type="primary" @click="userTemplate">下载模板</ElButton>
    </div>
    <div>
      <span class="mr-2" :class="{ 'text-red-500': isUpdateRef }">
        是否更新/覆盖已存在的用户数据
      </span>
      <el-switch v-model="isUpdateRef" />
    </div>
  </Modal>
</template>
