<template>
  <transition-group tag="div" class="n-toast" name="n-toast" appear @after-leave="onAfterLeave">
    <template v-for="data in dataList">
      <div :key="data.id" class="n-toast-position">
        <div class="n-toast-box" :class="'n-toast-' + data.type">
          <n-icon class="n-toast-icon" size="16" :type="data.type | icon"></n-icon>
          <div class="n-toast-content">{{data.info}}</div>
        </div>
      </div>
    </template>
  </transition-group>
</template>
<script>
import NIcon from '@uif/next/lib/components/icon'
import { delay, spliceBy } from '@uif/next/lib/utils/tools'

const icons = new Map([
  ['info', 'circle-info'],
  ['success', 'circle-info'],
  ['warning', 'circle-info'],
  ['error', 'circle-info']
])

let count = 0

export default {
  name: 'n-toast',
  filters: {
    icon: (type) => icons.get(type)
  },
  components: {NIcon},
  data () {
    return {
      dataList: []
    }
  },
  beforeDestroy () {
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },
  methods: {
    async show ({type, info, duration}) {
      if (this.dataList.length) {
        this.dataList.forEach(data => data.timer && clearTimeout(this.timer))
        this.dataList = []
        await delay(100)
      }
      const data = {type, info, duration, id: count++}
      this.dataList.push(data)
      if (duration) {
        data.timer = setTimeout(() => {
          data.timer = null
          spliceBy(this.dataList, ({id}) => id !== data.id)
        }, duration * 1000)
      }
    },
    async onAfterLeave () {
      await delay(200)
      if (!this.dataList.length) {
        this.$emit('destroy', this)
      }
    }
  }
}
</script>
