<template>
  <div class="comp-drag-uploader" @dragover="dragoverFun">
    <slot />
    <div v-if="uploading" class="cover">
      <el-upload
        class="upload"
        drag
        :show-file-list="false"
        multiple
        :before-upload="beforeUploadFun"
      >
        <div class="tips">将文件拖到此处上传</div>
      </el-upload>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const emit = defineEmits(['beforeUpload']);
const uploading = ref(false);
const draging = ref(false);

let timeOut: any = null;
const dragoverFun = (event: any) => {
  event.preventDefault();
  if (!uploading.value) {
    uploading.value = true;
  }
  draging.value = true;
  if (timeOut) {
    clearTimeout(timeOut);
    timeOut = null;
  }
  // 拖拽区域内嵌套div时会触发dragleave
  timeOut = setTimeout(() => {
    draging.value = false;
    uploading.value = false;
  }, 200);
};

const beforeUploadFun = (file: any) => {
  emit('beforeUpload', file);
  return false;
};
</script>

<style lang="scss">
.comp-drag-uploader {
  position: relative;
  width: 100%;
  height: 100%;
  .cover {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 9;
    .upload {
      width: 100%;
      height: 100%;
      .tips {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        color: var(--el-color-primary);
        font-size: 14px;
      }
      .el-upload {
        width: 100%;
        height: 100%;
        .el-upload-dragger {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
