<template>
  <button
    class="el-button"
    :disabled="buttonDisabled || loading"
    :autofocus="autofocus"
    :type="nativeType"
    :class="[
      (type ? 'el-button--' + type : ''),
      (buttonSize ? 'el-button--' + buttonSize : ''),
      {
        'is-disabled': buttonDisabled,
        'is-loading': _loading,
        'is-plain': plain,
        'is-round': round,
        'is-circle': circle
      }
    ]"
    @click="handleClick"
  >
    <i v-if="_loading" class="el-icon-loading" />
    <i v-if="icon && !_loading" :class="icon" />
    <span v-if="$slots.default"><slot /></span>
  </button>
</template>
<script>
export default {
  name: 'ElButton',

  inject: {
    elForm: {
      default: ''
    },
    elFormItem: {
      default: ''
    }
  },

  props: {
    type: {
      type: String,
      default: 'default'
    },
    size: {
      type: String,
      default: undefined
    },
    icon: {
      type: String,
      default: ''
    },
    nativeType: {
      type: String,
      default: 'button'
    },
    loading: {
      type: Boolean,
      default: undefined
    },
    disabled: {
      type: Boolean,
      default: undefined
    },
    plain: {
      type: Boolean,
      default: undefined
    },
    autofocus: {
      type: Boolean,
      default: undefined
    },
    round: {
      type: Boolean,
      default: undefined
    },
    circle: {
      type: Boolean,
      default: undefined
    },
    loadingClick: {
      type: Function,
      default: undefined
    }
  },
  data() {
    return {
      exloading: false
    }
  },
  computed: {
    _elFormItemSize() {
      return (this.elFormItem || {}).elFormItemSize
    },
    buttonSize() {
      return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size
    },
    buttonDisabled() {
      return this.disabled || (this.elForm || {}).disabled
    },
    _loading() {
      return this.loading || this.exloading
    }
  },
  created() {
    this.$on('click', () => {
      if (typeof this.loadingClick === 'function') {
        const promise = this.loadingClick()
        if (promise instanceof Promise) {
          this.exloading = true
          promise.finally(() => {
            this.exloading = false
          })
        } else {
          this.$message.warning('loadingClick result is not Promise')
        }
      }
    })
  },

  methods: {
    handleClick(evt) {
      this.$emit('click', evt)
    }
  }
}
</script>
