<template>
    <transition :name="transitionName">
        <div
            :class="bem()"
            role="tab-panel"
            :data-name="name"
            :data-active="active"
            v-show="active">
            <Portal :target="target">
                <slot name="label" :active="active" :active-value="rootTabs.currentValue">
                    <span>{{label}}</span>
                </slot>
            </Portal>
            <slot v-if="rendered" :active="active" :actie-value="rootTabs.currentValue"/>
        </div>
    </transition>
</template>

<script>
import { componentMixin, createComponentName } from '../_utils/component';
import Portal from '../Portal';

let id = 0;

export default {
    name: createComponentName('tab-panel'),
    components: {
        Portal,
    },
    mixins: [componentMixin],
    inject: ['rootTabs'],
    props: {
        label: {
            type: String,
            default: '',
        },
        name: {
            type: [String, Number],
            required: true,
        },
        closable: Boolean,
        disabled: Boolean,
        transitionName: {
            type: String,
            default: '',
        },
    },
    data() {
        id += 1;
        this.id = id;
        return {
            rendered: false,
        };
    },
    computed: {
        active() {
            if (!this.name) return false;
            return this.name === this.rootTabs.currentValue;
        },
        target() {
            if (this.rootTabs.isMounted && this.rootTabs.$refs.tabList) {
                const index = this.rootTabs.getIndex(this);
                return this.rootTabs.$refs.tabList.children[index];
            }
            return '';
        },
    },
    watch: {
        active(v) {
            if (this.active && !this.rendered) {
                this.rendered = true;
                this.$emit('loaded');
            }
            if (v) {
                // 打开
                this.$emit('open');
            }
            else {
                // 关闭
                this.$emit('close');
            }
        },
        label() {
            this.rootTabs.$forceUpdate();
        },
    },
    mounted() {
        this.rootTabs.addPanel(this);
        if (this.active) {
            this.rendered = true;
            this.$emit('loaded');
        }
    },
    destroyed() {
        if (this.rootTabs) this.rootTabs.removePanel(this);
    },
    methods: {
        onClick() {
            this.rootTabs.changeValue(this.value);
        },
    },
};
</script>

<style lang="less">
@import '../_styles/base.less';
.@{tab-panel} {
    .scrollbar();
}
</style>
