<template>
    <div :class="prefixCls">
        <YYScroller  v-if="scrollable">
            <div :class="`${prefixCls}-nav ${prefixCls}-scrollable`">
                <div v-for="(item, index) in navList" 
                    :key="index"
                    :class="classes(item)"
                    @click="handleChange(index)">
                    {{item.label}}
                </div>
                <div :class="`${prefixCls}-extra`" v-if="showSlot"><slot name="extra"></slot></div>
            </div>
        </YYScroller>
        <div :class="`${prefixCls}-nav`" v-else>
            <div v-for="(item, index) in navList" 
                :key="index"
                :class="classes(item)"
                @click="handleChange(index)">
                {{item.label}}
            </div>
            <div :class="`${prefixCls}-extra`" v-if="showSlot"><slot name="extra"></slot></div>
        </div>
        <div :class="`${prefixCls}-content`" ref="panes">
            <slot></slot>
        </div>
    </div>
</template>
<script>
    const prefixCls = "yy-tabs"
    export default {
        name: 'YYTabs',
        props: {
            value: {
                type: [String, Number]
            },
            scrollable: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                prefixCls: prefixCls,
                navList: [],
                activeKey: this.value,
                showSlot: false
            }
        },
        methods: {
            classes(item) {
                return [
                    `${prefixCls}-tab`,
                    {
                        [`${prefixCls}-tab-active`]: item.name === this.activeKey
                    }
                ]
            },
            getTabs() {
                return this.$children.filter(item => item.$options.name === 'YYTabPane')
            },
            updateNav() {
                this.showSlot = this.$slots.extra !== undefined;
                this.navList = this.getTabs().map((pane, index) => {
                    if (!pane.currentName) pane.currentName = index
                    if (index === 0 && !this.activeKey) {
                        this.activeKey = pane.currentName || index
                    }
                    return {
                        label: pane.label,
                        name: pane.currentName || index
                    }
                })
            },
            updateVisibility() {
                [...this.$children].forEach(pane => pane.show = pane.name === this.activeKey)
            },
            handleChange(index) {
                const nav = this.navList[index]
                this.activeKey = nav.name
                this.updateVisibility(index)
                this.$emit('input', nav.name)
                this.$emit('on-change', nav.name)
            }
        },
        mounted() {
            this.updateVisibility()
        }
    }
</script>
