import { defineComponent, createVNode, createTextVNode } from 'vue';
import { useTheme } from '../_theme/useTheme';
import { UPDATE_MODEL_EVENT, CHANGE_EVENT } from '../_util/constants';
import getPrefixCls from '../_util/getPrefixCls';
import Button from '../button';
import { UploadOutlined } from '../icon';
import { COMPONENT_NAME } from './const';
import { inputFileProps } from './props';
import { useInputFile } from './useInputFile';

const prefixCls = getPrefixCls('input-file');
const cls = appendClass => `${prefixCls}-${appendClass}`;
const InputFile = defineComponent({
  name: COMPONENT_NAME,
  props: inputFileProps,
  emits: [UPDATE_MODEL_EVENT, CHANGE_EVENT],
  slots: Object,
  setup: (props, _ref) => {
    let {
      emit,
      slots,
      attrs
    } = _ref;
    useTheme();
    const {
      currentFiles,
      inputRef,
      disabled,
      multiple,
      acceptStr,
      openFileExplorer,
      handleInputFileChange
    } = useInputFile(props, emit);
    const renderTrigger = () => {
      if (slots.default) {
        return slots.default({});
      }
      return createVNode(Button, {
        "class": cls('trigger-button'),
        "disabled": disabled.value
      }, {
        default: () => [createTextVNode("\u9009\u62E9\u6587\u4EF6")],
        icon: () => createVNode(UploadOutlined, null, null)
      });
    };
    const renderFileList = files => {
      if (files.length === 0) {
        return null;
      }
      if (slots.fileList) {
        return slots.fileList({
          files
        });
      }
      return files.length > 1 ? `${files.length} 个文件` : files[0].name;
    };
    return () => createVNode("div", {
      "class": prefixCls
    }, [createVNode("div", {
      "class": cls('visible-content'),
      "style": attrs.style
    }, [createVNode("div", {
      "class": cls('trigger'),
      "onClick": openFileExplorer
    }, [renderTrigger()]), createVNode("div", {
      "class": cls('file-list')
    }, [renderFileList(currentFiles.value)])]), createVNode("input", {
      "ref": inputRef,
      "class": cls('input'),
      "type": 'file',
      "accept": acceptStr.value,
      "multiple": multiple.value,
      "onChange": handleInputFileChange,
      "onClick": e => e.stopPropagation()
    }, null)]);
  }
});

export { InputFile as default };
