<template>
  <div class="uif-notice-container" :style="{top: top + 'px'}">
    <transition name="uif-notice" @after-leave="afterLeave">
      <div v-if="show" class="uif-notice" :class="'uif-notice-' + type">
        <u-icon class="uif-notice-icon" :type="icons[type]"></u-icon>
        <span class="uif-notice-title">{{desc || title}}</span>
      </div>
    </transition>
  </div>
</template>
<script>
import {oneOf} from '@uif/hq/src/utils/assist'
import UIcon from '@uif/hq/src/components/icon'

const icons = {
  info: 'alert-circle',
  success: 'circle-checked',
  warning: 'alert-circle',
  error: 'circle-x'
}

export default {
  name: 'u-notice',
  components: {UIcon},
  props: {
    iTop: {
      type: Number,
      default: 0
    },
    onClose: {
      type: Function,
      default: null
    },
    type: {
      validator (value) {
        return oneOf(value, ['info', 'success', 'warning', 'error'])
      },
      default: 'success'
    },
    title: {
      type: String,
      default: ''
    },
    desc: {
      type: String,
      default: ''
    },
    duration: {
      type: Number,
      default: 2.5
    }
  },
  data () {
    return {
      top: this.iTop,
      show: false,
      icons
    }
  },
  mounted () {
    this.show = true
    this.timer = setTimeout(() => {
      this.timer = 0
      this.close()
    }, this.duration * 1000)
  },
  beforeDestroy () {
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },
  methods: {
    close () {
      this.show = false
      if (this.onClose) {
        this.onClose()
      }
    },
    afterLeave () {
      this.$root.destroy()
    }
  }
}
</script>
