<template>
    <el-tabs class="syswin-top-tabs" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane v-for="item in tabs" :key="item.name" :label="item.label" :name="item.name"></el-tab-pane>
    </el-tabs>
</template>
<script>
export default {
    name: 'SyTopTabs',
    props: {
        value: {
            type: [Number, String],
            default: ''
        },
        props: {
            type: Object,
            default() {
                return {}
            }
        },
        data: {
            type: Array,
            default() {
                return []
            }
        }
    },
    data() {
        return {
            activeName: ''
        }
    },
    computed: {
        defaultProps() {
            return Object.assign({
                label: 'label',
                name: 'name'
            }, this.props)
        },
        tabs() {
            const { name, label } = this.defaultProps
            return this.data.map(item => {
                return {
                    name: item[name],
                    label: item[label]
                }
            })
        }
    },
    watch: {
        value(name) {
            this.updateValue(name)
        }
    },
    created() {
        this.updateValue(this.value)
    },
    methods: {
        updateValue(name) {
            if (name !== this.activeName) {
                const tab = this.data.find(it => it.name === name)
                if (tab) {
                    this.click(tab)
                }
            }
        },
        handleClick(tab) {
            const { name } = this.defaultProps
            const item = this.data.find(it => it[name] === tab.name)
            this.click(item)
        },
        click(tab) {
            this.activeName = tab.name
            this.$emit('input', tab.name)
            this.$emit('tab-click', tab)
        }
    }
}
</script>
