<template>
  <button class="qf-button" @click="handleClick" ref="button" :disabled="disabled" :autofocus="autofocus"
          :type="nativeType" :class="[
      type ? 'qf-button-' + type : '',
        buttonSize ? 'qf-button-' + buttonSize : '',
      {
        'is-disabled': disabled,
        'is-plain': plain,
        'is-round': round
      }
    ]">
    <qf-font-icon v-if="icon" :name="icon" @click="handleInnerClick"></qf-font-icon>
    <span v-if="$slots.default" @click="handleInnerClick">
      <slot></slot>
    </span>
    <qf-font-icon v-if="trigger" :name="trigger" @click="handleInnerClick"></qf-font-icon>
  </button>
</template>
<script>
import KeydownMgr from '../../util/KeydownMgr';
import QfFontIcon from '../../font-icon';

export default {
  name: 'QfButton',
  components: {
    QfFontIcon
  },
  props: {
    code: {
      type: Number | String,
      default: false
    },
    type: {
      type: String,
      default: 'default'
    },
    size: String,
    icon: {
      type: String,
      default: ''
    },
    trigger: String,
    nativeType: {
      type: String,
      default: 'button'
    },
    disabled: Boolean,
    plain: Boolean,
    autofocus: Boolean,
    round: Boolean
  },

  computed: {
    buttonSize() {
      return this.size;
    }
  },

  created() {
    if (this.code) {
      KeydownMgr.bind(this, this.onKeydown);
    }
  },

  beforeDestroy() {
    if (this.code) {
      KeydownMgr.unbind(this, this.onKeydown);
    }
  },

  methods: {
    handleClick(evt) {
      this.$emit('click', evt);
    },
    handleInnerClick(evt) {
      if (this.disabled) {
        evt.stopPropagation();
      }
    },
    focus() {
      this.$el.focus();
    },
    onKeydown(event) {
      if (this.code) {
        let eventKeyCode = KeydownMgr.getKeyCode(event).toString();
        let currentCode = this.code ? this.code.toString() : '';
        if (/^[A-Za-z]{1}$/.test(currentCode)) {
          currentCode = currentCode.toUpperCase().charCodeAt().toString();
        }

        if (eventKeyCode === currentCode) {
          this.$refs.button.click();
          event.stopPropagation();
          event.preventDefault();
          event.returnValue = false;
          event.cancelBubble = true;
        }
      }
    }
  }
};
</script>
