<template>
    <div class="bgo-flex-item" :style="itemStyle">
        <slot />
    </div>
</template>

<script>
import { ChildrenMixin } from "../../mixins/relation";

export default {
    name: "BgoFlexItem",
    inject: { gap: "gap" },
    mixins: [ChildrenMixin("FlexBox")],
    props: {
        weight: {
            type: Number,
            default: 1
        },
        backgroundColor: {
            type: String,
            default: "transparent"
        }
    },
    data() {
        return {
            itemStyle: {}
        };
    },
    watch: {
        weight() {
            this.parent.calcChildrenStyle();
        },
        backgroundColor(newVal) {
            this.itemStyle.backgroundColor = newVal;
        }
    },
    methods: {
        calcItemStyle() {
            const itemCount = this.parent.children.length;
            // flex item 尺寸权重比例
            const ratio =
                this.weight /
                this.parent.children.reduce(
                    (sum, item) => sum + item.weight,
                    0
                );
            const index = this.parent.children.indexOf(this);
            const style = {
                backgroundColor: this.backgroundColor
            };

            const gap = index < itemCount - 1 ? this.gap : "0";
            const itemSize = `calc(100% * ${ratio} - ${itemCount - 1} * ${
                this.gap
            } / ${itemCount})`;

            if (this.parent.direction === "row") {
                style["width"] = itemSize;
                style["marginRight"] = gap;
            } else if (this.parent.direction === "column") {
                style["height"] = itemSize;
                style["marginBottom"] = gap;
            }

            this.itemStyle = style;
        }
    }
};
</script>

<style lang="scss" scoped>
.bgo-flex-item {
    height: 100%;
}
</style>
