<template>
  <button :class="classes" :style="styles" :disabled="disabled" @click="handleClickLink">
    <u-icon class="uif-loading" type="spinner" scene="none" v-if="loading"></u-icon>
    <u-icon class="uif-btn-icon" v-if="icon" :type="icon"></u-icon><span v-if="$slots.default"><slot></slot></span><u-icon class="uif-btn-icon" v-if="suffixIcon" :type="suffixIcon"></u-icon>
  </button>
</template>
<script>
import UIcon from '@uif/core/lib/components/icon'
import { oneOf } from '@uif/core/lib/utils/assist'

export default {
  name: 'u-button',
  components: {UIcon},
  props: {
    size: {
      validator (value) {
        return oneOf(value, ['small', 'middle', 'large'])
      },
      default: 'middle'
    },
    type: {
      validator (value) {
        return oneOf(value, ['default', 'normal', 'primary', 'danger', 'success', 'dark', 'text'])
      },
      default: 'default'
    },
    outline: {
      type: Boolean,
      default: false
    },
    shape: {
      validator (value) {
        return oneOf(value, ['radius', 'circle'])
      },
      default: 'radius'
    },
    spacing: {
      type: [String, Number],
      default: 0
    },
    hover: {
      type: Boolean,
      default: false
    },
    active: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    loading: {
      type: Boolean,
      default: false
    },
    icon: {
      type: String,
      default: ''
    },
    // 后置Icon
    suffixIcon: {
      type: String,
      default: ''
    },
    long: {
      type: Boolean,
      default: false
    },
    // 反馈时间 s
    feedback: {
      type: [Number, String],
      default: 0
    }
  },
  data () {
    return {
      feedStatus: false
    }
  },
  computed: {
    classes () {
      return [
        'uif-btn',
        'uif-btn-' + this.size,
        'uif-btn-' + this.type,
        'uif-btn-' + this.shape,
        {
          hover: this.hover,
          active: this.active,
          'uif-btn-outline': this.outline,
          'uif-btn-long': this.long,
          'uif-btn-loading': this.loading,
          'uif-btn-spacing': this.spacing,
          'uif-btn-center': this.loading || this.icon || this.suffixIcon,
          'uif-btn-feedback': this.feedback,
          'uif-btn-feedback-ok': this.feedStatus
        }
      ]
    },
    styles () {
      const style = {}
      if (this.spacing) {
        style['letter-spacing'] = this.spacing + 'px'
        style['text-indent'] = this.spacing + 'px'
      }
      return style
    }
  },
  mounted () {
  },
  methods: {
    handleClickLink (event) {
      if (this.feedback && this.feedStatus) {
        return false
      }
      this.$emit('click', event)
      this.setFeedback()
    },
    setFeedback () {
      if (this.feedback) {
        this.feedStatus = true
        setTimeout(() => {
          this.feedStatus = false
        }, Number(this.feedback) * 1000)
      }
    }
  }
}
</script>
