<template>
  <el-dialog
    v-model="state.visible"
    draggable
    append-to-body
    :title="title"
    width="50%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="onClose"
  >
    <div class="import-tips">
      <p>{{ tips }}</p>
      <el-button v-if="templateUrl" type="primary" icon="download" text @click="emit('on-download', templateUrl)">下载模板</el-button>
    </div>
    <el-upload ref="uploadRef" drag action="#" :show-file-list="true" accept=".xlsx,.xls" :limit="1" :http-request="onUploadExcel">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件放在此处或单击上传</div>
      <template #tip>
        <div class="el-upload__tip">仅允许导入xls、xlsx格式文件，excel文件大小小于500kb</div>
      </template>
    </el-upload>
    <template #footer>
      <el-button type="primary" @click="onConfirm"> 确定导入</el-button>
      <el-button @click="onClose"> 取消</el-button>
    </template>
  </el-dialog>
</template>
<script setup name="custom-import-excel">
import { reactive, ref, shallowRef } from 'vue';
import { isEmpty } from '@/utils';
const props = defineProps({
  title: {
    type: String,
    default: '文件导入',
  },
  tips: {
    type: String,
    default: '提示：导入前请先下载模板填写信息，然后再导入！',
  },
  templateUrl: {
    type: [String, URL],
    default: '',
  },
  // options: {
  //   type: Object,
  //   default: () => {
  //     return {
  //       tips: '提示：导入前请先下载模板填写信息，然后再导入！',
  //     };
  //   },
  // },
});
const emit = defineEmits(['on-confirm', 'on-close', 'on-download']);

const uploadRef = ref(null);
const formDate = shallowRef(null);
const state = reactive({
  visible: false,
  loading: false,
});

const onUploadExcel = ({ file }) => {
  if (isEmpty(file.name)) return;
  formDate.value = new FormData();
  formDate.value.append('file', file);
};

const onConfirm = () => {
  emit('on-confirm', formDate.value);
};

const onClose = () => {
  uploadRef?.value && uploadRef.value.clearFiles();
  state.visible = false;
};

defineExpose({
  show: () => {
    formDate.value = null;
    state.visible = true;
  },
  hide: () => {
    onClose();
  },
  clear: () => {
    uploadRef?.value && uploadRef.value.clearFiles();
  },
});
</script>
<style lang="scss" scoped>
.import {
  &-tips {
    @include flex-row;

    align-items: center;
    margin-bottom: 20px;
    font-size: 14px;
    color: #979797;
    p {
      flex: 3;
    }
  }
}
</style>
