<template>

    <div :class="bem()">
        <slot/>
    </div>

</template>

<script>
import { componentMixin, createComponentName } from '../_utils/component.js';
import Waterfail from './Waterfall.js';
import Item from './Item';

export default {
    name: createComponentName('waterfall'),
    Item,
    provide() {
        return {
            waterfail: this
        };
    },
    mixins: [componentMixin],
    props: {
        transition: {
            type: String,
            default: 'waterfall-fade'
        },
        grid: {
            type: Number,
            default: 1,
        },
        getKey: {
            type: Function,
            default: undefined,
        },
        margin: {
            type: Number,
            default: 10,
        },
    },
    watch: {
        margin() {
            this.$nextTick(() => {
                this.update();
            });
        },
    },
    mounted() {
        window.addEventListener('resize', this.update);
    },
    methods: {
        resize() {
            this.update();
        },
        async update() {
            if (this.$update) {
                await this.$update;
                return;
            };

            this.$update = new Promise((resolve) => {
                setTimeout(() => {
                    this.waterfail = new Waterfail({ width: this.$el.clientWidth, margin: this.margin, grid: this.grid });
                    this.lastClientWidth = this.$el.clientWidth;
                    const children = Array.from(this.$el.children).filter(n => n.getAttribute('class').indexOf('leave') === -1);

                    let maxHeight = 0;
                    for (let index = 0; index < children.length; index++) {
                        const el = children[index];

                        const { left, top } = this.waterfail.getPostion(el.clientWidth, el.clientHeight);

                        el.style.left = left + 'px';
                        el.style.top = top + 'px';

                        let height = top + el.clientHeight;
                        if (height > maxHeight) {
                            maxHeight = height;
                        }
                    }
                    this.$el.style.height = maxHeight + 'px';

                    resolve();
                    this.$update = undefined;
                }, 200);
            });
            await this.$update;
        }
    }
};
</script>

<style lang="less">
@import "../_styles/base.less";
@b: ~"@{prefix}-waterfall";


.@{b} {
    position: relative;
    will-change: height;
    width: 1200px;

    &__item {
        top: 0;
        left: 0;
        position: absolute;
    }
}


</style>
