import { defineComponent, inject, ref, computed, createVNode } from 'vue';
import { useTheme } from '../_theme/useTheme';
import { useLocale } from '../config-provider/useLocale';
import FMessage from '../message';
import { key } from './const';
import { matchType } from './utils';

const uploadDraggerProps = {
  onFileTypeInvalid: {
    type: Function
  }
};
var uploadDragger = defineComponent({
  name: 'FUploadDragger',
  props: uploadDraggerProps,
  emits: [],
  setup(props, ctx) {
    useTheme();
    const {
      t
    } = useLocale();
    const {
      prefixCls,
      onUploadFiles,
      isDragger,
      accept,
      multiple,
      disabled // 组件本身的disabled 状态
    } = inject(key);
    isDragger.value = true;
    const isHovering = ref(false);
    const classList = computed(() => {
      return [`${prefixCls}-dragger`, isHovering.value && 'is-hovering', disabled.value && 'is-disabled'].filter(Boolean);
    });
    const handleEnter = event => {
      if (disabled.value) {
        return;
      }
      // 阻止事件的默认行为
      event.preventDefault();
      isHovering.value = true;
    };
    const handleLeave = event => {
      if (disabled.value) {
        return;
      }
      // 阻止事件的默认行为
      event.preventDefault();
      isHovering.value = false;
    };
    const handleOver = event => {
      if (disabled.value) {
        return;
      }
      // 阻止事件的默认行为
      event.preventDefault();
    };
    const handleDrop = event => {
      if (disabled.value) {
        return;
      }
      // 阻止事件的默认行为
      event.preventDefault();
      isHovering.value = false;
      let postFiles = Array.from(event.dataTransfer.files);
      if (!postFiles.length) {
        return;
      }
      if (!multiple.value) {
        postFiles = postFiles.slice(0, 1);
      }
      const filterFiles = accept.value.length ? postFiles.filter(file => {
        return matchType(file.name, file.type, accept.value);
      }) : postFiles;
      if (filterFiles.length !== postFiles.length) {
        if (props.onFileTypeInvalid) {
          props.onFileTypeInvalid(postFiles.filter(file => {
            return !matchType(file.name, file.type, accept.value);
          }));
        } else {
          FMessage.error(t('upload.fileTypeInvalidTip'));
        }
      }
      onUploadFiles(filterFiles);
    };
    return () => {
      var _ctx$slots, _ctx$slots$default;
      return createVNode("div", {
        "class": classList.value,
        "onDragenter": handleEnter,
        "onDragleave": handleLeave,
        "onDrop": handleDrop,
        "onDragover": handleOver
      }, [(_ctx$slots = ctx.slots) === null || _ctx$slots === void 0 || (_ctx$slots$default = _ctx$slots.default) === null || _ctx$slots$default === void 0 ? void 0 : _ctx$slots$default.call(_ctx$slots)]);
    };
  }
});

export { uploadDragger as default, uploadDraggerProps };
