import { defineComponent, h, resolveDirective, withDirectives, ref, onMounted, computed } from 'vue';
import { directives } from '../sunken';
import Icon from '../icon';
const prefixCls = 'x-btn';
const Button = defineComponent({
  name: 'x-button',
  props: {
    type: {
      type: String,
      default: 'default'
    },
    dashed: Boolean,
    circle: Boolean,
    round: Boolean,
    ghost: Boolean,
    link: Boolean,
    block: Boolean,
    disabled: Boolean,
    href: String,
    target: String,
    autofocus: Boolean,
    loading: Boolean
  },
  emits: ['click'],
  directives,

  setup(props, {
    slots,
    emit
  }) {
    const btnRef = ref(); // autofocus

    if (props.autofocus) {
      onMounted(() => {
        btnRef.value.focus();
      });
    }

    const disabledRef = computed(() => props.disabled || props.loading);

    function onClick(e) {
      // 原生 button disabled 状态仍然可以通过 Enter 触发click事件，所以这里需要判断
      if (disabledRef.value) {
        e.preventDefault();
        return;
      }

      emit('click', e);
    }

    return () => {
      var _slots$default;

      const {
        href,
        target,
        loading
      } = props;
      const disabled = disabledRef.value;
      const buttonProps = {
        ref: btnRef,
        class: ['x-btn', {
          [`${prefixCls}-` + props.type]: true,
          [`${prefixCls}-dashed`]: props.dashed,
          [`${prefixCls}-circle`]: props.circle,
          [`${prefixCls}-round`]: props.round,
          [`${prefixCls}-ghost`]: props.ghost || props.dashed,
          [`${prefixCls}-link`]: props.link,
          [`${prefixCls}-block`]: props.block,
          [`${prefixCls}-disabled`]: disabled
        }],
        type: "button",
        disabled,
        onClick
      };
      const content = (_slots$default = slots.default) === null || _slots$default === void 0 ? void 0 : _slots$default.call(slots);
      const children = [loading ? h(Icon, {
        type: 'loading',
        spin: true,
        class: `${prefixCls}_icon`
      }) : undefined, content ? h('span', content) : undefined];
      let button = !href ? h('button', buttonProps, children) : h('a', { ...buttonProps,
        href,
        target
      }, children);
      const dir = resolveDirective('sunken');
      return withDirectives(button, [[dir]]);
    };
  }

});

Button.install = app => {
  app.component(Button.name, Button);
};

export default Button;