<template>
  <transition name="qf-message-fade">
    <div
      :class="[
        'qf-message',
        type ? `qf-message-${type}` : '',
        center ? 'is-center' : '',
        showClose ? 'is-closable' : '']"
      v-show="visible"
      @mouseenter="clearTimer"
      @mouseleave="startTimer"
      role="alert"
    >
      <qf-font-icon :name="'ic-ic_' + type"></qf-font-icon>
      <slot>
        <span v-html="message" class="qf-message-content"></span>
      </slot>
      <qf-font-icon v-if="showClose" @click="close" name="ic-ic_close"></qf-font-icon>
    </div>
  </transition>
</template>

<script type="text/babel">
import QfFontIcon from '../font-icon';

export default {
  components: {
    QfFontIcon
  },
  data() {
    return {
      visible: false,
      message: '',
      duration: 2000,
      type: 'info',
      onClose: null,
      showClose: false,
      closed: false,
      timer: null,
      center: false
    };
  },

  watch: {
    closed(newVal) {
      if (newVal) {
        this.visible = false;
        this.$el.addEventListener('transitionend', this.destroyElement);
      }
    }
  },

  methods: {
    destroyElement() {
      this.$el.removeEventListener('transitionend', this.destroyElement);
      this.$destroy(true);
      this.$el.parentNode.removeChild(this.$el);
    },

    close() {
      this.closed = true;
      if (typeof this.onClose === 'function') {
        this.onClose(this);
      }
    },

    clearTimer() {
      clearTimeout(this.timer);
    },

    startTimer() {
      if (this.duration > 0) {
        this.timer = setTimeout(() => {
          if (!this.closed) {
            this.close();
          }
        }, this.duration);
      }
    },

    keydown(e) {
      if (e.keyCode === 27) { // esc关闭消息
        if (!this.closed) {
          this.close();
        }
      }
    }
  },

  mounted() {
    this.startTimer();
    document.addEventListener('keydown', this.keydown);
  },

  beforeDestroy() {
    document.removeEventListener('keydown', this.keydown);
  }
};
</script>
