<template>
    <div :class="classes">
        <div :class="[prefixCls + '-bar']">
            <div :class="[prefixCls + '-nav-container']">
                <div :class="[prefixCls + '-nav-wrap']">
                    <div :class="[prefixCls + '-nav-scroll']">
                        <div v-if="type !== 'line'" :class="[prefixCls + '-cardnav']" ref="nav">
                            <div @click="moveRight">
                                <Icon type="icon-Leftarrows" v-show="showLeftRightArrows" />
                            </div>
                            <div :class="barClasses" :style="barStyle"></div>
                            <div :class="[prefixCls + '-move']" :style="{marginLeft:marginLeft+'px'}">
                                <div :class="tabCls(item)"  @contextmenu.prevent="showContextMenu(item)" v-for="(item, index) in navList" @click="handleChange(index)">
                                    <Icon v-if="item.icon !== ''" :type="item.icon"></Icon>
                                    <Render v-if="item.labelType === 'function'" :render="item.label"></Render>
                                    <template v-if="item.title !=''"><span :title="item.title">{{ item.label }}</span></template>
                                    <template v-else><span :class="[prefixCls + '-spanW']" >{{ item.label }}</span></template>
                                    <span @mouseenter="changeHb(item)" @mouseleave="changeSb(item)"><Icon v-if="showClose(item)" :type="item.defaultIcon" @click.native.stop="handleRemove(index)"></Icon></span>
                                </div>
                            </div>
                            <div :class="[prefixCls + '-contextmenu']" v-if="contextMenu" id="contextmenulist" v-show="showMenu">
                                <ul>
                                    <li @click="closeOthers()">
                                        <div>
                                            <Icon type="icon-guanbiqita" size="12" />
                                            <span>关闭其他</span>
                                        </div>
                                    </li>
                                    <li @click="closeAll()">
                                        <div>
                                            <Icon type="icon-huaban" size="12" />
                                            <span>关闭全部</span>
                                        </div>
                                    </li>
                                    <li @click="refresh()">
                                        <div>
                                            <Icon type="icon-shuaxin" size="12" />
                                            <span>刷新当前</span>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div @click="moveLeft">
                                <Icon type="icon-Right-arrows" v-show="showLeftRightArrows" />
                            </div>
                        </div>
                        <div v-else :class="[prefixCls + '-nav']" ref="nav">
                            <div :class="barClasses" :style="barStyle"></div>
                            <div :class="tabCls(item)" @contextmenu.prevent="showContextMenu(item)" v-for="(item, index) in navList" @click="handleChange(index)">
                                <Icon v-if="item.icon !== ''" :type="item.icon"></Icon>
                                <Render v-if="item.labelType === 'function'" :render="item.label"></Render>
                                <template v-if="item.title !=''"><span :title="item.title">{{ item.label }}</span></template>
                                <template v-else><span>{{ item.label }}</span></template>
                                <span @mouseenter="changeHb(item)" @mouseleave="changeSb(item)"><Icon v-if="showClose(item)"  :type="item.defaultIcon" @click.native.stop="handleRemove(index)"></Icon></span>
                            </div>
                            <div :class="[prefixCls + '-contextmenu']" v-if="contextMenu" id="contextmenulist2" v-show="showMenu">
                                <ul>
                                    <li @click="closeOthers()">
                                        <div>
                                            <Icon type="icon-guanbiqita" size="12" />
                                            <span>关闭其他</span>
                                        </div>
                                    </li>
                                    <li @click="closeAll()">
                                        <div>
                                            <Icon type="icon-huaban" size="12" />
                                            <span>关闭全部</span>
                                        </div>
                                    </li>
                                    <li @click="refresh()">
                                        <div>
                                            <Icon type="icon-shuaxin" size="12" />
                                            <span>刷新当前</span>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div :class="[prefixCls + '-nav-right']" v-if="showSlot">
                            <slot name="extra"></slot>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div :class="contentClasses" :style="contentStyle">
            <slot></slot>
        </div>
    </div>
</template>
<script>
    import Icon from '../icon/icon.vue';
    import { oneOf, getStyle } from '../../utils/assist';
    import Emitter from '../../mixins/emitter';
    import Render from '../base/render';

    const prefixCls = 'ivu-tabs';
    const ARROW_BAR_WIDTH = 28;

    export default {
        name: 'Tabs',
        mixins: [Emitter],
        components: { Icon, Render },
        props: {
            value: {
                type: [String, Number]
            },
            type: {
                validator(value) {
                    return oneOf(value, ['line', 'card']);
                },
                default: 'line'
            },
            size: {
                validator(value) {
                    return oneOf(value, ['small', 'default']);
                },
                default: 'default'
            },
            animated: {
                type: Boolean,
                default: true
            },
            closable: {
                type: Boolean,
                default: false
            },
            contextMenu: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                prefixCls: prefixCls,
                navList: [],
                barWidth: 0,
                barOffset: 0,
                activeKey: this.value,
                showSlot: false,
                showMenu: false,
                showLeftRightArrows: false,
                marginLeft: 0,
                currentItem: '',
                countRight: 0,
                containerWidth: 0,
                first:true,
                icon:'icon-chuyidong'
            };
        },
        computed: {
            classes() {
                return [
                    `${prefixCls}`,
                    {
                        [`${prefixCls}-card`]: this.type === 'card',
                        [`${prefixCls}-mini`]: this.size === 'small' && this.type === 'line',
                        [`${prefixCls}-no-animation`]: !this.animated
                    }
                ];
            },
            contentClasses() {
                return [
                    `${prefixCls}-content`,
                    {
                        [`${prefixCls}-content-animated`]: this.animated
                    }
                ];
            },
            barClasses() {
                return [
                    `${prefixCls}-ink-bar`,
                    {
                        [`${prefixCls}-ink-bar-animated`]: this.animated
                    }
                ];
            },
            contentStyle() {
                const x = this.navList.findIndex((nav) => nav.name === this.activeKey);
                const p = x === 0 ? '0%' : `-${x}00%`;

                let style = {};
                if (x > -1) {
                    style = {
                        transform: `translateX(${p}) translateZ(0px)`
                    };
                }
                return style;
            },
            barStyle() {
                let style = {
                    display: 'none',
                    width: `${this.barWidth}px`
                };
                if (this.type === 'line') style.display = 'block';
                if (this.animated) {
                    style.transform = `translate3d(${this.barOffset}px, 0px, 0px)`;
                } else {
                    style.left = `${this.barOffset}px`;
                }

                return style;
            }
        },
        methods: {
            getTabs() {
                return this.$children.filter(item => item.$options.name === 'TabPane');
            },
            updateNav() {
                this.navList = [];
                this.getTabs().forEach((pane, index) => {
                    let param ={
                        labelType: typeof pane.label,
                        label: pane.label,
                        icon: pane.icon || '',
                        title:'',
                        name: pane.currentName || index,
                        disabled: pane.disabled,
                        closable: pane.closable,
                        defaultIcon:'icon-chuyidong'
                    }
                    if(param.label.length>4){
                        param.title=param.label;
                        param.label = param.label.substring(0, 4) + "...";
                    }
                    this.navList.push(param);
                   /* this.navList.push({
                        labelType: typeof pane.label,
                        label: pane.label,
                        icon: pane.icon || '',
                        name: pane.currentName || index,
                        disabled: pane.disabled,
                        closable: pane.closable,
                        defaultIcon:'icon-chuyidong'
                    });*/

                    if (!pane.currentName) pane.currentName = index;
                    if (index === 0) {
                        if (!this.activeKey) this.activeKey = pane.currentName || index;
                    }
                });
                this.countRight = this.navList.length - 1;
                this.updateStatus();
                this.updateBar();
            },
            updateBar() {
                this.$nextTick(() => {
                    const index = this.navList.findIndex((nav) => nav.name === this.activeKey);
                    if(index<0){
                        return ;
                    }
                    const prevTabs = this.$refs.nav.querySelectorAll(`.${prefixCls}-tab`);
                    const tab = prevTabs[index];
                    this.barWidth = parseFloat(getStyle(tab, 'width'));

                    if (index > 0) {
                        let offset = 0;
                        //const gutter = this.size === 'small' ? 0 : 16;
                        const gutter = this.size === 'small' ? 0 : 0;
                        for (let i = 0; i < index; i++) {
                            offset += parseFloat(getStyle(prevTabs[i], 'width')) + gutter;
                        }

                        this.barOffset = offset;
                    } else {
                        this.barOffset = 0;
                    }
                    this.containerWidth = document.getElementsByClassName("ivu-tabs-nav-container")[0].offsetWidth;
                    const tabsWidth = document.getElementsByClassName("ivu-tabs-move")[0].clientWidth;
                    if (tabsWidth > this.containerWidth) {
                        if(this.first){
                            this.marginLeft = ARROW_BAR_WIDTH;
                            this.first=false;
                        }
                        this.showLeftRightArrows = true;
                    } else {
                        this.marginLeft = 0
                        this.showLeftRightArrows = false;
                    }

                });
            },
            updateStatus() {
                const tabs = this.getTabs();
                tabs.forEach(tab => tab.show = (tab.currentName === this.activeKey) || this.animated);
            },
            tabCls(item) {
                return [
                    `${prefixCls}-tab`,
                    {
                        [`${prefixCls}-tab-disabled`]: item.disabled,
                        [`${prefixCls}-tab-active`]: item.name === this.activeKey
                    }
                ];
            },
            handleChange(index) {
                const nav = this.navList[index];
                if (nav.disabled) return;
                this.activeKey = nav.name;
                this.$emit('input', nav.name);
                this.$emit('on-click', nav.name);
            },
            handleRemove(index) {
                const tabs = this.getTabs();
                const tab = tabs[index];
                if (tab) {
                    tab.$destroy();
                }
                if (tab.currentName === this.activeKey) {
                    const newTabs = this.getTabs();
                    let activeKey = -1;

                    if (newTabs.length) {
                        const leftNoDisabledTabs = tabs.filter((item, itemIndex) => !item.disabled && itemIndex < index);
                        const rightNoDisabledTabs = tabs.filter((item, itemIndex) => !item.disabled && itemIndex > index);

                        if (rightNoDisabledTabs.length) {
                            activeKey = rightNoDisabledTabs[0].currentName;
                        } else if (leftNoDisabledTabs.length) {
                            activeKey = leftNoDisabledTabs[leftNoDisabledTabs.length - 1].currentName;
                        } else {
                            activeKey = newTabs[0].currentName;
                        }
                    }
                    this.activeKey = activeKey;
                    this.$emit('input', activeKey);
                }
                this.$emit('on-tab-remove', tab.currentName);
                this.updateNav();
                this.moveRight();
            },
            showClose(item) {
                if (this.type === 'card') {
                    if (item.closable !== null) {
                        return item.closable;
                    } else {
                        return this.closable;
                    }
                } else {
                    return false;
                }
            },
            moveLeft() {
                var tabs = document.getElementsByClassName("ivu-tabs-tab");
                const initial = this.showLeftRightArrows ? ARROW_BAR_WIDTH : 0;
                const realWidth = this.containerWidth - initial;
                if (tabs.length > 0) {
                    let minWidth = 0;
                    const lastVisible = Array.from(tabs)
                        .findIndex((tab) => {
                            minWidth += tab.offsetWidth;
                            return minWidth > realWidth - this.marginLeft
                        });
                    if (lastVisible === -1) return;
                    const showHasNext = lastVisible < tabs.length - 1 ? 15 : 0;
                    this.marginLeft = realWidth - minWidth - showHasNext
                }
            },
            moveRight() {
                var tabs = document.getElementsByClassName("ivu-tabs-tab");
                const initial = this.showLeftRightArrows ? ARROW_BAR_WIDTH : 0;
                if (tabs.length > 0) {
                    let maxWidth = 0;
                    const firstVisible = Array.from(tabs)
                        .findIndex((tab, index) => {
                            maxWidth += tab.offsetWidth;
                            return maxWidth > -1 * this.marginLeft
                        });
                    if (this.marginLeft === initial) return;
                    const showHasPrev = firstVisible > 0 ? 15 : 0;
                    const firstCompleteVisibleRequire = tabs[firstVisible].offsetWidth - (maxWidth + this.marginLeft);
                    this.marginLeft = this.marginLeft + firstCompleteVisibleRequire + showHasPrev + initial;
                    this.marginLeft = Math.min(this.marginLeft, initial)
                }
            },
            showContextMenu(item) {
                var getCon;
                if(this.$props.type=="card" && this.contextMenu){
                    getCon = document.getElementById("contextmenulist");
                }else if(this.$props.type=="line" && this.contextMenu) {
                    getCon = document.getElementById("contextmenulist2");
                }
                if (getCon) {
                    getCon.style.left = window.event.clientX + "px"; //之前写法event.x 数值计算错误
                    getCon.style.top = window.event.clientY + "px";
                    getCon.style.display = "block";
                    this.currentItem = item;
                }
            },
            refresh() {
                this.$emit('refresh', this.currentItem);
            },
            closeOthers() {
                for (var i = this.navList.length - 1; i >= 0; i--) {
                    if (this.navList[i].label != this.currentItem.label) {
                        this.handleRemove(i);
                    } else {
                        continue;
                    }
                }
                this.$emit('closeOthers', this.currentItem);
            },
            closeAll() {
                for (var i = this.navList.length - 1; i >= 0; i--) {
                    this.handleRemove(i);
                }
                this.$emit("closeAll", '');
            },
            changeHb(item){
                item.defaultIcon="icon-shibai";

            },
            changeSb(item){
                item.defaultIcon="icon-chuyidong";
            }
        },
        watch: {
            value(val) {
                this.activeKey = val;
            },
            activeKey() {
                this.updateBar();
                this.updateStatus();
                this.broadcast('Table', 'on-visible-change', true);
            }
        },
        mounted() {
            var that=this;
            window.addEventListener('resize', this.updateBar);
            this.showSlot = this.$slots.extra !== undefined;
            document.onclick = function() {
                var getCon;
                if(that.$props.type=="card"){
                    getCon = document.getElementById("contextmenulist");
                }else {
                    getCon = document.getElementById("contextmenulist2");
                }
                if (getCon) {
                    getCon.style.display = "none";
                }
            }
        }
    };
</script>
