<template>
    <div id="Main" class="app" :style="{'--subThemeColor': themeColorObj.subThemeColor, '--themeColor': themeColorObj.themeColor,'--middleThemeColor': themeColorObj.middleThemeColor, '--litterThemeColor': themeColorObj.litterThemeColor}">
        <Header v-show="showHeader" />
        <!-- </el-header> -->
        <div v-show="($route.path !== '/nomenu') && judgeEmpty(editableTabsValue) && showMainTab" class="el-tab-list flex-center plr20">
            <el-button v-for="(item, index) in 2" :key="`left-icon${index}`" type="text" class="arrow-icon left-icon el-icon-caret-left c-909399" :class="[index === 1 ? 'last-caret-icon' : '']" :disabled="leftDisabled" @click="changeRouterPage('left')" />
            <el-tabs id="mainTab" v-model="editableTabsValue" class="full-content" type="card" closable @tab-remove="removeTab" @tab-click="chooseTab">
                <el-tab-pane v-for="(item, index) in editableTabs" :key="`${item.name}-${index}`" :label="item.title" :name="item.name" />
            </el-tabs>
            <el-button v-for="(item, index) in 2" :key="`right-icon${index}`" type="text" class="arrow-icon right-icon el-icon-caret-right c-909399" :class="[index === 1 ? 'right-last-caret-icon' : 'ml50']" :disabled="rightDisabled" @click="changeRouterPage('right')" />
        </div>
        <el-container class="container-box over-hidden border-box ptb16">
            <el-aside v-show="$route.path !== '/nomenu' && showSiderMenu" class="app-side app-side-left bgc-fff border-right br12-right ps-r" :class="collapsed ? 'app-side-collapsed' : 'app-side-expanded'">
                <SiderMenu class="border-bottom" :collapsed="collapsed" @toggleSideBar="toggleSideBar" />
                <div class="slider-zoom" :class="{ 'slider-zoom-active': collapsed }" @click="onClickMenuCollapsed">
                    <i class="ft16 slider-icon" :class="collapsed ? 'el-icon-s-unfold' : 'el-icon-s-fold'" />
                </div>
            </el-aside>
            <el-container :class="collapsed ? 'app-side-collapsed' : 'app-side-expanded'" class="full-content">
                <el-main class="full-content border-box main-box">
                    <transition name="fade" mode="out-in">
                        <keep-alive :include="keepAlivePage">
                            <router-view class="main-cont" :class="collapsed ? 'large-width' : 'small-width'" />
                        </keep-alive>
                    </transition>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>
<script>
import Header from './Header';
import SiderMenu from './SiderMenu';
import { notEmpty } from '@/tool/func';
import { NORMAL_TAB } from '@/constant';
import { pageStyleMixin } from '@/mixins';
import { mapActions, mapState } from 'vuex';

export default {
    components: {
        Header,
        SiderMenu
    },
    mixins: [pageStyleMixin],
    data() {
        return {
            collapsed: false,
            logoSrc: 'logo',
            // 头部导航栏
            editableTabs: [],
            editableTabsValue: 'homepage',
            includeList: [],
            leftDisabled: false,
            rightDisabled: false,
            showMainTab: true,
            showSiderMenu: true,
            showHeader: true
        };
    },
    computed: {
        ...mapState({
            keepAlivePage: state => state.common.keepAlivePage
        })
    },
    watch: {
        $route: {
            deep: true,
            immediate: true,
            async handler(newVal, oldVal) {
                if (notEmpty(newVal['meta']) && notEmpty(newVal['meta']['title'])) {
                    const item = { name: newVal.name, title: newVal['meta']['title'], componentName: newVal['meta']['componentName'], ...newVal };
                    await this.addTab(item);
                    this.handleLine();
                    this.handerTabs(this.editableTabs);
                }
            }
        },
        editableTabs(val) {
            this.handerTabs(val);
        }
    },
    created() {
        this.handerTabs(this.editableTabs);
        const query = this.$route.query;
        if (query.embededMode === 'true') {
            this.showMainTab = false;
            this.showSiderMenu = false;
            this.showHeader = false;
        }
    },
    methods: {
        ...mapActions({
            changeSetting: 'setting/changeSetting'
        }),
        handerTabs(val = []) {
            const activeIndex = this.editableTabs.findIndex(item => item.name === this.editableTabsValue);
            this.leftDisabled = val.length <= 1 || activeIndex === 0;
            this.rightDisabled = val.length <= 1 || activeIndex === this.editableTabs.length - 1;
        },
        toggleSideBar(collapsed) {
            this.collapsed = collapsed;
        },
        onClickMenuCollapsed() {
            this.collapsed = !this.collapsed;
            const imgUrl = this.collapsed ? 'logo_collapsed' : 'logo';
            this.logoSrc = imgUrl;
            this.$emit('toggleSideBar', this.collapsed);
        },
        // 判断是否已存在同名页签，否则新增页签，并在缓存数组中新增
        addTab(item) {
            // 当前新增的页签是否存在页签数组中的判断
            const sameIndex = this.editableTabs.findIndex(tabItem => tabItem.name === item.name);
            if (sameIndex === -1) {
                // 如果此时页签数组没有该项，则将它加入到页签数组中，注意将跳转路由以及组件实例名字同步赋值
                this.editableTabs.push({
                    title: item.title,
                    name: item.name,
                    router: {
                        path: item.path,
                        query: item.query
                    },
                    componentName: item.componentName
                });
                // 如果此时页签数组没有该项，则将它加入缓存数组中

                this.includeList.push(item.componentName);
            }
            this.addKeepAlive(this.includeList);
            // 改变当前选中的页签值
            this.editableTabsValue = item.name;
        },
        removeTab(eventName) {
            const index = this.editableTabs.findIndex(({ name }) => name === eventName || eventName === 'homepage');
            this.editableTabs = this.editableTabs.filter(({ name }) => name !== eventName || eventName === 'homepage');
            if (this.editableTabs.length > 0 && index > 0) {
                this.editableTabsValue = this.editableTabs[index - 1].name;
                this.chooseTab(this.editableTabs[index - 1]);
            }
        },
        // 切换路由
        chooseTab(event) {
            const tabIndex = this.editableTabs.findIndex(item => item.name === event.name);
            const tab = this.editableTabs[tabIndex] || {};
            const { router = {}} = tab;
            // 跳转相应路由
            if (tabIndex !== -1 && notEmpty(router['path'])) {
                this.$router.push({ path: router.path });
            }
        },
        // 处理线条样式
        handleLine() {
            this.$nextTick(() => {
                const mainTabDom = document.getElementById('mainTab');
                const activeDoms = mainTabDom.getElementsByClassName('is-active');
                if (activeDoms[0].nextSibling) {
                    const classAll = activeDoms[0].nextSibling.getAttribute('class');
                    activeDoms[0].nextSibling.className = classAll.concat(' no-left-line');
                }
            });
        },
        // 左右切换路由
        changeRouterPage(direct) {
            const activeIndex = this.editableTabs.findIndex(item => item.name === this.editableTabsValue);
            if (direct === 'left' && activeIndex > 0) {
                const e = this.editableTabs[activeIndex - 1];
                this.chooseTab(e);
            } else if (direct === 'right' && activeIndex < this.editableTabs.length) {
                const e = this.editableTabs[activeIndex + 1];
                this.chooseTab(e);
            }
            this.handerTabs(this.editableTabs);
        }
    }
};
</script>

<style scoped lang="less">
.app {
	height: 100%;
	width: 100%;
	background: #f8fafb;

	.header {
		height: 80px;
	}

	// .logo-box {
	// 	height: 80px;
	// 	position: absolute;
	// 	left: 88px;
	// 	top: 0;
	// 	// margin-top: -30px;
	// 	z-index: 999;
	// 	width: 200px;

	// 	.logo {
	// 		width: 60%;
	// 		height: 100%;
	// 	}
	// }

	.slider-zoom {
        position: absolute;
        bottom: 0;
        line-height: 48px;
        left: 50%;
        margin-left: -9px;
        width: 18px;
		z-index: 99;
	}

	.slider-zoom-active {
		left: 43px;
	}

	.logo-box-collapsed {
		left: 30px;
		width: 50px;
	}

	.el-tab-list {
		height: 40px;
		line-height: 40px;
		width: 100%;
		background-color: #fff;
		box-sizing: border-box;
		border-bottom: 1px solid #e4e7ed;
	}

	.container-box {
		height: calc(100% - 120px);
		width: 100%;
	}

    .arrow-icon {
        background: transparent;
    }
    .main-box::-webkit-scrollbar-thumb{
    background-color: var(--middleThemeColor);
    }
    .main-box::-webkit-scrollbar {
        height: 6px !important;
    }
}
</style>
