<template>
    <transition :name="animate"
                @after-leave="handleAfterLeave">
        <div v-show="visible"
             :class="toastClass"
             :style="toastStyle">
            <i v-if="type"
               :class="iconClass" />
            <p :class="`${prefix}-toast__message`">
                {{ message }}
            </p>
        </div>
    </transition>
</template>

<script>
import Color from 'color';
import { prefix, prefixMixins } from 'jdd-design/utils';
export default {
    name: `${prefix}-toast`,
    mixins: [prefixMixins],
    props: {
        position: {
            type: String,
            default: 'center',
            validator(value) {
                return ['top', 'center', 'bottom'].indexOf(value) > -1;
            }
        },
        duration: {
            type: Number,
            default: 1500
        },
        type: String,
        message: String,
        animate: {
            type: String,
            default: 'ani-fade'
        },
        theme: {
            type: String,
            default: 'dark',
            validator(value) {
                return ['dark', 'light', 'custom'].indexOf(value) > -1;
            }
        },
        color: {
            type: String,
            validator(value) {
                return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/g.test(value);
            }
        },
        opacity: {
            type: Number,
            default: 0.6,
            validator(value) {
                return value > 0 && value <= 1;
            }
        },
        onClose: Function
    },
    data() {
        return {
            visible: false
        };
    },
    computed: {
        toastClass() {
            let clsNames = [`${prefix}-toast`];
            this.theme && clsNames.push(`${prefix}-toast--${this.theme}`);
            this.position && clsNames.push(`${prefix}-toast--${this.position}`);
            this.type && clsNames.push('has-icon');
            return clsNames;
        },
        toastStyle() {
            let style = {};
            if (this.color) {
                let color = Color(this.color || '#000');
                style.backgroundColor = `rgba(${color.color.join(',')},${
                    this.opacity
                })`;
            }
            return style;
        },
        iconClass() {
            let clsNames = [`${prefix}-toast__icon`];
            this.type && clsNames.push(`${prefix}-icon-${this.type}`);
            return clsNames;
        }
    },
    mounted() {
        if (this.duration > 0) {
            this.timer = setTimeout(() => {
                if (this.visible) {
                    this.close();
                }
            }, this.duration);
        }
    },
    methods: {
        handleAfterLeave() {
            this.$destroy(true);
            this.$el.parentNode.removeChild(this.$el);
            this.onClose && this.onClose();
        },
        close() {
            this.visible = false;
        }
    }
};
</script>
