<template>
  <transition :name="transitionName">
    <div class="mc-notify_inner" :class="[typeClass, hasIcon , isCover]" v-show="isShow">
      <i v-if="closable" class="mc-icon-close" @click="handleClose"></i>
      <i v-if="iconClass" :class="['mc-notify_icon',`mc-icon-${iconClass}`]"></i>
      <div class="mc-notify_content" v-html="content"></div>
    </div>
  </transition>
</template>
<script>
export default {
  props: {
    type: {
      type: String,
      default: 'default',
    },
    content: {
      type: String,
      default: '',
    },
    closable: {
      type: Boolean,
      default: true,
    },
    onClose: {
      type: Function,
      default() {},
    },
    duration: {
      type: Number,
      default: 4500,
    },
    placement: {
      type: String,
      default: 'top-center',
    },
    icon: {
      type: String,
    },
    animated: {
      type: Boolean,
      default: false,
    },
    transition: {
      type: String,
    },
    cover: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      isShow: false,
      placementTransition: {
        'top-right': 'slideRight',
        'top-center': 'slideDown',
        'top-left': 'slideLeft',
        'bottom-right': 'slideRight',
        'bottom-center': 'slideUp',
        'bottom-left': 'slideLeft',
      },
    };
  },

  computed: {
    typeClass() {
      return this.type ? `is-${this.type}` : null;
    },
    hasIcon() {
      return this.iconClass ? 'has-icon' : null;
    },
    isCover() {
      return this.cover ? 'is-cover' : null;
    },
    iconClass() {
      if (this.icon) return this.icon;
      if (this.type === 'primary') {
        return 'info';
      } else if (this.type === 'success') {
        return 'success';
      } else if (this.type === 'warning') {
        return 'warning';
      } else if (this.type === 'danger') {
        return 'danger';
      } else {
        return this.icon;
      }
    },
    transitionName() {
      if (this.transition) return this.transition;
      return this.placementTransition[this.placement];
    },
  },

  methods: {
    handleClose() {
      this.isShow = false;
      setTimeout(() => {
        this.$destroy();
        this.$el.remove();
      }, 500);
    },
    close() {
      clearTimeout(this.timer);
      this.isShow = false;
      this.$destroy();
      this.$el.remove();
    },
  },

  beforeMount() {
    let parent;
    parent = document.querySelector(`.mc-notify.${this.placement = this.cover?'top-center':this.placement}`);
    if (!parent) {
      parent = document.createElement('div');
      parent.classList.add('mc-notify', this.placement);
      document.body.appendChild(parent);
    }
    parent.appendChild(this.$el);
  },

  mounted() {
    this.isShow = true;
    this.timer = setTimeout(() => this.close(), this.duration);
  },
};
</script>
