import { defineComponent } from 'vue';
import {
  getEditorEmits,
  getUploadProps,
  useNamespace,
} from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/editor/ibiz-file-upload/ibiz-file-upload.scss';
import { useIViewUpload } from '../use/use-iview-upload';

export const IBizFileUpload = defineComponent({
  name: 'IBizFileUpload',
  props: getUploadProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('file-upload');
    const c = props.controller;

    const {
      uploadUrl,
      headers,
      files,
      onDownload,
      onError,
      onRemove,
      onSuccess,
      beforeUpload,
    } = useIViewUpload(
      props,
      value => {
        emit('change', value);
      },
      c,
    );

    return {
      ns,
      c,
      uploadUrl,
      headers,
      files,
      onDownload,
      onError,
      onRemove,
      onSuccess,
      beforeUpload,
    };
  },
  render(h) {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {h(
          'IUpload',
          {
            ref: 'fileUpload',
            props: {
              action: this.uploadUrl,
              headers: this.headers,
              disabled: this.disabled,
              'default-file-list': this.files,
              multiple: this.c.model.multiple,
              type: this.c.model.isDrag ? 'drag' : 'select',
              accept: this.c.model.accept,
              'before-upload': this.beforeUpload,
              'on-success': this.onSuccess,
              'on-error': this.onError,
              'on-remove': this.onRemove,
              'on-preview': this.onDownload,
            },
          },
          [
            this.c.model.isDrag ? (
              <div class={this.ns.b('drag-box')}>
                <i-icon type='md-cloud-upload' />
                <div class={this.ns.be('drag-box', 'text')}>
                  <span>将文件拖到此处，或</span>
                  <span>点击上传</span>
                </div>
              </div>
            ) : (
              <i-button
                icon='ios-cloud-upload-outline'
                class={this.ns.b('button')}
              >
                上传文件
              </i-button>
            ),
          ],
        )}
      </div>
    );
  },
});
