<template>
  <transition-group name="uif-notice" appear tag="div" class="uif-notice-wrap"
                    @before-leave="beforeLeave" @after-leave="afterLeave">
    <div v-for="notice in notices" :key="notice.key">
      <u-notice-instance v-bind="notice" @close="handleClose(notice.key)"></u-notice-instance>
    </div>
  </transition-group>
</template>
<script>
import UNoticeInstance from './notice-instance'
import {getRandom} from '@uif/core/lib/utils/util'
import {px} from '@uif/core/lib/utils/assist'
import {assign} from '@uif/core/lib/utils/object'
import {filter} from '@uif/core/lib/utils/array'

export default {
  name: 'u-notice',
  components: {UNoticeInstance},
  data () {
    return {
      cb: null,
      notices: []
    }
  },
  methods: {
    insertNotice (config) {
      this.notices.push(assign({}, config, {key: getRandom()}))
    },
    handleClose (key) {
      this.notices = filter(this.notices, n => n.key !== key)
    },
    beforeLeave (el) {
      el.style.display = 'flex'
      el.style.height = px(el.offsetHeight)
    },
    afterLeave () {
      if (this.notices.length < 1) {
        if (this.cb) this.cb()
        this.$root.destroy()
      }
    },
    beforeDestroy (cb) {
      this.cb = cb
    }
  }
}
</script>
