<template>
    <view :class="`easy-tab easy-tab-type-${type}`">
        <slot></slot>
    </view>
</template>

<script>
    import base from './base.extend.js';

    let tabs = [];
    let current = -1;

    export default {
        name: "easy-tab",
        props: {
            selected: {
                type: Number,
                default: 0
            },
            type: {
                type: String,
                default: 'card'
            }
        },
        data() {
            return {
                current: 0,
            };
        },
        created() {
            tabs = [];
            current = this.selected;
        },
        mounted() {
            if (current < tabs.length && current >= 0) {
                tabs[current].select();
            }
        },
        methods: {
            addTab(tab) {
                if (base.isObject(tab)) {
                    tabs.push(tab);
                }
            },

            /**
             * 选择
             * @param {number|object} tab 选项，option 数组下标或者 option 组件本身
             */
            select(tab) {
                let before = current;
                this.change(tab);
                let opt = tabs[current].getTab();
                this.$emit('change', {
                    current: current,
                    before: before,
                    value: opt.value
                });
            },

            /**
             * 选择
             * @param {number | object} item 
             */
            change(tab) {
                let i = 0;
                let before = current;

                if (typeof tab === 'number') {
                    current = tab;
                } else if (typeof tab === 'object') {
                    for (i = 0; i < tabs.length; i++) {
                        if (tabs[i] === tab) {
                            current = i;
                            break;
                        }
                    }
                }
                for (i = 0; i < tabs.length; i++) {
                    if (current === i) {
                        tabs[current].select();
                    } else {
                        tabs[i].unselect();
                    }
                }
                this.isShowPanel = false;
            }
        }
    }
</script>

<style lang="scss">
    .easy-tab {
        position: relative;
        overflow: hidden;
        width: 100%;
        height: 80upx;
        flex-shrink: 0;
        overflow-x: auto;
        white-space: nowrap;
    }
</style>