<template>
    <div class="layout-wrapper">
        <layout-header
            :init-nav-id="currentNavId"
            :nav-data="navListArr"
            @change="handleNavTabClick"
        ></layout-header>
        <layout-sidebar
            :current-menu-route="currentMenuRoute"
            :current-nav-bar="currentNavBar"
            @handleMenuClick="handleSubMenuClick"
            v-show="currentNavBar.category !== 'System'"
        ></layout-sidebar>
        <div
            class="layout-main"
            :class="{ 'collapse': collapse }"
            :style="currentNavBar.category === 'System' ? 'left: 0;' : ''"
        >
            <layout-tags
                :tag-data="tagsList"
                @handleTagOptionClose="handleTagOptionClose"
                @change="handleTagClick"
                @close="handleCloseTagClick"
            ></layout-tags>
            <!-- <layout-breadcrumb></layout-breadcrumb> -->
            <div class="main-box">
                <div class="container">
                    <div
                        class="panel"
                        v-for="(item,index) in tagsList"
                        :key="index"
                        :style="!item.visiable ? 'display:none' : ''"
                    >
                        <iframe
                            scrolling="auto"
                            frameborder="0"
                            style="width:100%;height:100%;"
                            :src="item.path | handleSrc"
                        ></iframe>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import LayoutHeader from './components/LayoutHeader'
import LayoutSidebar from './components/LayoutSidebar'
import LayoutTags from './components/LayoutTags'
import bus from '@/assets/bus'
export default {
    name: 'Home',
    data () {
        return {
            href: location.href.slice(0, -1),
            collapse: false,
            currentNavId: '684cb18f-9e03-4009-84b1-931ac5f9e671', // 默认办公管理
            currentNavBar: {}, // 当前导航栏对象,用于侧边栏数据展示
            navListArr: [],
            currentMenuRoute: '', // 当前菜单栏路由
            tagsList: [
                {
                    visiable: true,
                    path: '/desktop',
                    title: '工作台'
                }
            ]
        }
    },
    components: {
        // LayoutHeader: () => import('./components/LayoutHeader'),
        // LayoutSidebar: () => import('./components/LayoutSidebar'),
        // LayoutTags: () => import('./components/LayoutTags'),
        // LayoutBreadcrumb: () => import('./components/LayoutBreadcrumb')
        LayoutHeader,
        LayoutSidebar,
        LayoutTags
    },
    filters: {
        handleSrc (value) {
            if (!value) return
            const reg = /^https?:\/\//
            const href = location.href.slice(0, -1)
            return reg.test(value) ? value : `${href}${value}`
        }
    },
    created () {
        try {
            // token 过期则返回登录页，否则获取首页信息
            if (!localStorage.token || !localStorage.expireTime || localStorage.expireTime <= Date.now()) {
                this.$router.replace('/login')
            } else {
                this.getCurrentUserInfo()
                this.getPlatFormModuleTree()
                bus.$on('collapse', collapse => {
                    this.collapse = collapse
                })
            }
        } catch (e) { }
    },
    mounted () {
        window.addEventListener('storage', ({ key, newValue }) => {
            if (key === 'modules' && newValue) {
                const { name, url } = JSON.parse(newValue)
                let { tagsList } = this
                let index = this.hasPropertyToObj(tagsList, 'title', name)
                if (index > -1) {
                    if (url === tagsList[index].path) {
                        // 如何url一样 直接显示
                        this.getIframeTagInfo(JSON.parse(newValue))
                    } else {
                        // url 不一样 先删除 再显示重新加载
                        new Promise((resolve, reject) => {
                            this.tagsList.splice(index, 1)
                            resolve()
                        }).then(() => {
                            this.getIframeTagInfo(JSON.parse(newValue))
                        })
                    }
                } else {
                    this.getIframeTagInfo(JSON.parse(newValue))
                }
            }
            localStorage.removeItem('modules')
        })
    },
    methods: {
        getCurrentUserInfo () {
            this.$api.commonApi.getCurrentUserInfo().then(res => {
                if (res.data.Status) this.$store.commit('saveUserinfo', res.data.Data)
            })
        },

        getPlatFormModuleTree () {
            this.$api.commonApi.getPlatFormModuleTree().then(res => {
                let data = res.data
                if (data.Status) {
                    this.navListArr = data.Data
                    let currentNavBar = data.Data.filter((item) => { return this.currentNavId === item.item_id })
                    this.currentNavBar = currentNavBar[0]
                    console.log(this.navListArr)
                } else {
                    this.navListArr = []
                }
            }).catch(err => {
                console.log(err)
            })
        },

        /**
         * iframe内模块打开新标签页处理
         * 数据格式 { name: '模块命', url: '路由路径' }
         */
        getIframeTagInfo (params) {
            let { tagsList } = this
            let index = this.hasPropertyToObj(tagsList, 'title', params.name)
            if (index > -1) {
                tagsList.map(item => { item.visiable = false })
                tagsList[index].visiable = true
            } else {
                tagsList.map(item => { item.visiable = false })
                tagsList.push({
                    title: params.name,
                    path: params.url || '/error',
                    visiable: true
                })
            }
        },

        // 一级栏目
        handleNavTabClick (index) {
            this.currentNavId = this.navListArr[index].item_id
            this.currentNavBar = this.navListArr[index]
            if (this.currentNavBar.children.length && this.currentNavBar.children[0].children.length) {
                this.currentMenuRoute = this.currentNavBar.children[0].children[0].mvc_url
            }
            if (this.currentNavBar.category === 'System') {
                this.handleSubMenuClick({
                    item_name: this.currentNavBar.item_name,
                    mvc_url: '/systemConfig'
                })
            }
        },
        // 侧边栏
        handleSubMenuClick (menuItem) {
            let { tagsList } = this
            let index = this.hasPropertyToObj(tagsList, 'title', menuItem.item_name)
            if (index > -1) {
                tagsList.map(item => { item.visiable = false })
                tagsList[index].visiable = true
            } else {
                tagsList.map(item => { item.visiable = false })
                tagsList.push({
                    title: menuItem.item_name,
                    path: menuItem.mvc_url || '/error',
                    visiable: true
                })
            }
        },
        // 标签
        handleCloseTagClick (index) {
            let { visiable } = this.tagsList[index]
            if (visiable) {
                this.tagsList[index - 1].visiable = true
                this.tagsList.splice(index, 1)
            } else {
                this.tagsList.splice(index, 1)
            }
        },
        handleTagClick (index) {
            this.tagsList.map(item => { item.visiable = false })
            this.tagsList[index].visiable = true
            this.currentMenuRoute = index !== 0 ? this.tagsList[index].path : ''
        },
        // 标签选项
        handleTagOptionClose (command) {
            let { tagsList } = this
            let index = this.hasPropertyToObj(tagsList, 'visiable', true)
            if (index > -1) {
                switch (command) {
                case 'current':
                    if (index > -1 && index !== 0) {
                        this.tagsList[index - 1].visiable = true
                        this.tagsList.splice(index, 1)
                    }
                    break
                case 'other':
                    if (index === 0) {
                        this.tagsList.splice(1, this.tagsList.length - 1)
                    } else {
                        this.tagsList = [tagsList[0], tagsList[index]]
                    }
                    break
                case 'all':
                    this.tagsList.splice(1, this.tagsList.length - 1)
                    this.tagsList[0].visiable = true
                    break
                }
            }
        },
        // 判断数组对象是存在某个值，返回索引
        hasPropertyToObj (arr, key, value) {
            let index = -1
            if (!arr.length) {
                return index
            }
            for (let i = 0; i < arr.length; i++) {
                if (arr[i][key] === value) {
                    index = i
                    break
                }
            }
            return index
        }

    }

}
</script>

<style lang="less" scoped>
.layout-wrapper {
    // position: relative;
    height: 100%;
    min-width: 1200px;
    .layout-main {
        position: absolute;
        left: 200px;
        right: 0;
        top: 64px;
        bottom: 0;
        display: flex;
        flex-direction: column;
        min-width: 1000px;
        // -webkit-transition: left .3s ease-in-out;
        transition: left 0.3s ease-in-out;
        background-color: #f0f0f0;
        &.layout-main.collapse {
            left: 64px;
            min-width: 1136px;
        }
        .main-box {
            padding: 15px;
            flex: 1;
            .container {
                height: 100%;
                background: #fff;
                .panel {
                    height: 100%;
                }
            }
        }
    }
}
// .content {
//   width: auto;
//   height: 100%;
//   padding: 10px 10px 15px;
//   overflow-y: scroll;
//   box-sizing: border-box;
//   .container {
//     background: #fff;
//     padding-bottom: 10px;
//     min-height: 100%;
//     position: relative;
//   }
// }
</style>
