<template>
    <div v-transfer-dom :data-transfer="true" :class="prefixCls" 
        :style="{
            'z-index': 9999 + this.tIndex
        }">
        <transition-group name="move-message">
            <MessageItem 
                v-for="message in messages"
                @on-close="close"
                :key="message.name"
                :name="message.name"
                :type="message.type"
                :duration="message.duration"
                :closeable="message.closeable"
                :content="message.content"/>
        </transition-group>
    </div>
</template>
<script>
    import MessageItem from './message-item'
    import TransferDom from '../../../directives/transfer-dom'
    import { transferIndex, transferIncrease } from '../../../utils/transfer-queue'

    let seed = 0
    function getUuid () {
        return 'yyMessage_' + now + '_' + (seed++)
    }

    const prefixCls = 'yy-message'
    const now = Date.now()
    export default {
        name: 'YYMessage',
        data() {
            return {
                prefixCls,
                messages: [],
                tIndex: this.handleGetIndex()
            }
        },
        components: {
            MessageItem
        },
        directives: {
            TransferDom
        },
        methods: {
            add (message) {
                const name = message.name || getUuid()
                let _message = {
                    name: name,
                    ...message
                }
                this.messages.push(_message)
                this.tIndex = this.handleGetIndex()
            },
            close (name) {
                const messages = this.messages
                for (let i = 0; i < messages.length; i++) {
                    if (messages[i].name === name) {
                        this.messages.splice(i, 1)
                        break
                    }
                }
            },
            handleGetIndex () {
                transferIncrease()
                return transferIndex
            }
        }
    }
</script>

