<template>
    <main :class="skin" ref="content">
        <div ref="box">
            <!-- 头部 -->
            <head-info :info="teacherInfo"></head-info>
            <!-- 消息中心 -->
            <message :message="messageInfo"></message>
            <!-- 导航条 -->
            <nav-bar :list="moduleList" :list-index="navIndex" @tab="tab"></nav-bar>
            <!-- 模块 -->
            <div class="module">
                <div class="item module-item" v-for="(item, index) in moduleList" :key="index">
                    <div class="head vux-1px-b" :class="{active: index === navIndex}">
                        <span class="left">{{item.m_name}}</span>
                        <span class="right" @click="$refs.manage.init(moduleList)" v-if="!index">
                            <i class="iconfont set">&#xe101;</i>管理
                        </span>
                        <span class="right" @click="moduleList[index].isOpen = !item.isOpen, getModuleTop(200)" v-else>
                            {{item.isOpen ? '收起' : '展开'}}
                            <x-icon type="ios-arrow-up" size="24" v-show="item.isOpen"></x-icon>
                            <x-icon type="ios-arrow-down" size="24" v-show="!item.isOpen"></x-icon>
                        </span>
                    </div>
                    <!-- 由于使用了 rem 布局，滚动到页面模块又只能使用 px，所以使用行内样式写高度 -->
                    <ul :style="`height: ${ulHeight(item)}; ${!item.isOpen ? 'padding: 0;' : ''}`">
                        <li
                            v-for="(n, i) in item.childers"
                            :key="i"
                            @click="linkTo(n)"
                        >
                            <i
                                class="icon icon1"
                                :class="n.module_source !== 2 ? n.module_icon : 'icon-wujiaoxingshi'"
                            ></i>
                            <div class="text ellipsis">{{n.module_name}}</div>
                        </li>
                        <div class="empty" v-if="!item.childers.length">无</div>
                    </ul>
                </div>
            </div>
            <!-- 测试切换皮肤 -->
            <!-- <div class="btn btn-success test" @click="isShowSkin = true">测试切换皮肤 {{skin}}</div> -->
        </div>
        <!-- 顶部固定导航条 -->
        <nav-bar :list="moduleList" :list-index="navIndex" :is-fixed="isFixed" v-show="isFixed" @tab="tab" ref="nav"></nav-bar>
        <!-- 回到顶部 -->
        <i class="icon icon-pulldown top" :class="{active: isFixed}" @click="navIndex = 0, scrollTo(0), $refs.nav.scrollTop()"></i>
        <!-- 管理模块 -->
        <modules-manage ref="manage" @startDrag="scroll.disable()" @endDrag="scroll.enable()" @submit="getIndexInfo"></modules-manage>
        <!-- 测试皮肤列表 -->
        <actionsheet v-model="isShowSkin" :menus="skinList" @on-click-menu="(i, n) => { skin = n, getModuleTop(200) }"></actionsheet>
    </main>
</template>

<script>
import BScroll from 'better-scroll'
import { Actionsheet } from 'vux'
export default {
    name: 'Home',
    components: {
        HeadInfo: () => import('./components/HeadInfo'),
        Message: () => import('./components/Message'),
        NavBar: () => import('./components/NavBar'),
        ModulesManage: () => import('./components/ModulesManage'),
        Actionsheet
    },
    data () {
        return {
            skin: '', // 皮肤
            isShowSkin: false, // 是否显示测试皮肤列表
            skinList: '-default 00 01 02 03 04 05 06 10 20'.split(' ').map(n => 'skin' + n), // 测试皮肤列表，21 22 暂时不做，需求待定
            teacherInfo: {}, // 教师信息
            messageInfo: {}, // 消息中心
            moduleList: [], // 模块列表

            navIndex: 0, // 当前选项卡
            scroll: {}, // 滚动对象
            scrollY: 0, // 页面滚动距离
            boxHeight: innerHeight, // 内容的高度
            moduleTopList: [], // 每个模块距离顶部的距离
            duration: 400, // 滚动动画时间
            isScrollTo: false // 是否使用了 scrollTo
        }
    },
    computed: {
        isFixed: vm => vm.scrollY >= 404 // 是否固定导航条（Head 260 + Message 144 = 404）
    },
    created () {
        try {
            // token 过期则返回登录页，否则获取首页信息
            if (!localStorage.teacherToken || !localStorage.teacherExpireTime || localStorage.teacherExpireTime <= Date.now()) {
                this.$router.replace('/login')
            } else {
                this.getUserinfo()
                this.getIndexInfo(1)
            }
        } catch (e) {}
    },
    methods: {
        // 获取用户信息
        getUserinfo () {
            this.$api.commonApi.getCurrentUserInfo().then(res => {
                if (res.data.Status) this.$store.commit('saveUserinfo', res.data.Data)
            })
        },
        // 获取首页信息
        getIndexInfo (isFirst) {
            this.$api.homeApi.GetTeacherIndexInfo().then(res => {
                if (res.data.Status) {
                    const data = res.data.Data
                    // if (isFirst) this.skin = data.skin // 测试皮肤加了 if ----
                    if (isFirst) this.skin = 'skin-default' // 测试固定默认皮肤 ----
                    this.teacherInfo = data.teacher_info
                    this.messageInfo = data.message
                    // 全部展开，每个模块标记索引便于管理时添加
                    data.modules.forEach((item, index) => {
                        data.modules[index].isOpen = true
                        data.modules.forEach((item, index) => {
                            // 管理常用时系统模块拆分了所以 index - 1
                            if (index) item.childers.forEach((n, i) => { data.modules[index].childers[i].index = [index - 1, i] })
                        })
                    })
                    // 在我的常用中标记系统模块
                    data.modules[0].childers.forEach((myItem, myIndex) => {
                        if (myItem.module_source !== 2) {
                            data.modules.forEach((item, index) => {
                                if (index) {
                                    item.childers.forEach((n, i) => {
                                        if (n.id === myItem.id) {
                                            data.modules[index].childers[i].isSelect = true
                                            data.modules[0].childers[myIndex].index = [index - 1, i] // 管理常用时系统模块拆分了所以 index - 1
                                        }
                                    })
                                }
                            })
                        }
                    })
                    this.moduleList = data.modules
                }
                isFirst ? setTimeout(this.scrollInit) : this.getModuleTop(200)
            })
        },
        // 获取每个模块距离顶部的距离
        getModuleTop (delay = 0) {
            setTimeout(() => {
                this.boxHeight = this.$refs.box.offsetHeight
                this.moduleTopList = [...document.querySelectorAll('.module-item')].map(item => item.offsetTop)
            }, delay)
        },
        // 初始化滚动
        scrollInit () {
            this.getModuleTop()
            // 初始化滚动
            this.scroll = new BScroll(this.$refs.content, {
                probeType: 3,
                click: true
            })
            // 滚动监听，获取和滚动距离最接近的元素
            this.scroll.on('scroll', pos => {
                this.scrollY = Math.abs(Math.round(pos.y))
                if (!this.isScrollTo) {
                    for (let i = 0; i < this.moduleTopList.length; i++) {
                        // 如果当前模块滚动距离大于页面滚动距离，则上一个模块为当前模块，否则是最后一个模块
                        if (this.moduleTopList[i] > this.scrollY + 44) {
                            this.navIndex = i && i - 1
                            break
                        }
                        this.navIndex = i
                    }
                }
            })
        },
        // 点击导航条滚动到指定模块
        tab (index) {
            this.navIndex = index
            this.scrollTo(this.moduleTopList[index] - 44)
        },
        // 使用 scroll.scrollTo 时不用改变 navIndex
        scrollTo (top) {
            // 如果当前是往下滚动并且页面已经到底了就不能滚动
            if (top > this.scrollY && this.boxHeight <= this.scrollY + innerHeight) return false
            this.isScrollTo = true
            this.scrollY = Math.min(top, this.boxHeight - innerHeight)
            this.scroll.scrollTo(0, -this.scrollY, this.duration)
            setTimeout(() => { this.isScrollTo = false }, this.duration + 100) // 滚动结束后有一帧大概 23 毫秒的延迟监听, 所以 + 100
        },
        // 跳转链接
        linkTo (item) {
            if (item.module_source !== 2) {
                this.$router.push(item.gatewy_module_url)
            } else {
                location.href = item.module_url
            }
        },
        // 每类模块的高度
        ulHeight (item) {
            const liHeight = this.skin !== 'skin20' ? 100 : 110
            const padding = this.skin === 'skin10' ? 0 : this.skin === 'skin20' ? 10 : 20
            return item.isOpen ? (Math.ceil(item.childers.length / 3) * liHeight || 30) + padding + 'px' : 0
        }
    }
}
</script>

<style lang="less" scoped>
main {
    height: 100%;
    overflow: hidden;
}
.module, /deep/ .module {
    color: #333;
    .item {
        background-color: #fff;
        &:not(:first-child) {
            margin-top: 8px;
        }
        .head {
            height: 44px;
            line-height: 44px;
            padding-left: 15px;
            display: flex;
            justify-content: space-between;
            .left::before {
                content: '';
                display: inline-block;
                width: 0;
                height: 10px;
                border-radius: 50%;
                background-color: #409eff;
                transition-duration: 0.2s;
            }
            &.active .left::before {
                width: 10px;
                margin-right: 5px;
            }
            .right {
                color: #666;
                padding: 0 15px;
                padding-left: 50px;
                .set {
                    vertical-align: -1px;
                    margin-right: 5px;
                    font-size: 18px;
                }
                .vux-x-icon {
                    fill: #333;
                    height: 44px;
                    vertical-align: top;
                }
            }
        }
        ul {
            overflow: hidden;
            transition-duration: 0.2s;
            font-size: 0;
            padding: 10px;
            li {
                width: 33.33%;
                height: 100px; /*no*/
                padding: 0 5px;
                padding-top: 6px; /*no*/
                padding-bottom: 5px; /*no*/
                display: inline-block;
                vertical-align: top;
                text-align: center;
                .icon {
                    width: 60px; /*no*/
                    height: 60px; /*no*/
                    line-height: 60px; /*no*/
                    border-radius: 10px;
                    vertical-align: top;
                }
                .text {
                    font-size: 14px;
                    margin-top: 5px;
                    line-height: 20px;
                }
            }
            .empty {
                text-align: center;
                line-height: 30px;
                font-size: 14px;
                color: #999;
            }
        }
    }
}
.skin-default, .skin21, .skin22{
    &, /deep/ .popup {
        .icon { font-size: 32px; color: #fff; }
        .item:nth-child(2n + 1) .icon { background-color: #409eff; }
        .item:nth-child(2n) .icon { background-color: #e6a214; }
        .item .icon.plus { border: 1px solid #aaa; background-color: #fff; }
    }
}
.skin00 {
    /deep/ .banner { background-image: url(https://static.vschool100.com/Teacher/skin/koolau.jpg) }
    &, /deep/ .popup { .icon { font-size: 40px; color: #14120D; } }
}
.skin01 {
    /deep/ .banner { background-image: url(https://static.vschool100.com/Teacher/skin/blue01.jpg) }
    &, /deep/ .popup { .icon { font-size: 40px; color: #1a8fdf; } }
}
.skin02 {
    /deep/ .banner { background-image: url(https://static.vschool100.com/Teacher/skin/2270.jpg) }
    &, /deep/ .popup { .icon { font-size: 40px; color: #1d4e79; } }
}
.skin03 {
    /deep/ .banner { background-image: url(https://static.vschool100.com/Teacher/skin/28730.jpg) }
    &, /deep/ .popup { .icon { font-size: 40px; color: #507cae; } }
}
.skin04 {
    /deep/ .banner { background-image: url(https://static.vschool100.com/Teacher/skin/97489.jpg) }
    &, /deep/ .popup { .icon { font-size: 40px; color: #d05058; } }
}
.skin05 {
    /deep/ .banner { background-image: url(https://static.vschool100.com/Teacher/skin/98868.jpg) }
    &, /deep/ .popup { .icon { font-size: 40px; color: #543131; } }
}
.skin06 {
    /deep/ .banner { background-image: url(https://static.vschool100.com/Teacher/skin/2111.jpg) }
    &, /deep/ .popup { .icon { font-size: 40px; color: #22532d; } }
}
.skin10, .skin20 {
    /deep/ .head {
        background-color: transparent;
        .banner { background: none }
        .name, .attendance, .tips { color: #fff !important; }
        .vux-x-icon { fill: #fff !important; }
    }
    /deep/ .message {
        .weui-cells { color: #000; background-color: rgba(#fff, 0.6); }
        .weui-cell_access .weui-cell__ft:after { border-color: #666; }
        .marquee { background-color: transparent; }
        .text, .time, .empty { color: #fff; }
    }
    .module .item, /deep/ .module .item {
        margin-top: 0;
        background-color: transparent;
        .head {
            background-color: rgba(#fff, 0.6);
            .right { color: #333; }
        }
    }
    /deep/ .popup {
        background-color: transparent;
        .head {
            .left i, .right .cancel { color: #333; }
            .right .done { color: #08f; }
        }
        .item-title { color: #fff; padding-bottom: 8px; }
        li {
            position: relative;
            .icon:not(.plus) {
                position: static;
                i { top: 5px; right: 5px; }
            }
            .plus::before, .plus::after { background-color: #fff; }
        }
    }
    &, /deep/ .popup {
        .icon { font-size: 40px; color: #fff; }
        .text { color: #fff; }
    }
}
.skin10 {
    &, .vux-popup-dialog { background: url(https://static.vschool100.com/Teacher/skin/2223.jpg) no-repeat center / cover; }
    .module ul, /deep/ .module ul {
        padding: 0;
        li:nth-child(2n + 1) { background-color: rgba(#fff, 0.3); }
        li:not(:nth-child(3n)) { border-right: 1px solid #fff; }
        li { border-bottom: 1px solid #fff; }
    }
}
.skin20 {
    & > div:first-child, .vux-popup-dialog { background-image: linear-gradient(45deg,#17917a 0,#236ba5 100%); }
    .module ul, /deep/ .module ul {
        padding: 5px;
        li {
            width: calc(33.33% - 10px);
            margin: 5px;
        }
        li:nth-child(8n + 1) { background-color: rgba(54, 161, 219, 0.9); }
        li:nth-child(8n + 2) { background-color: #678ce1; }
        li:nth-child(8n + 3) { background-color: #8c67df; }
        li:nth-child(8n + 4) { background-color: #84d018; }
        li:nth-child(8n + 5) { background-color: #14c760; }
        li:nth-child(8n + 6) { background-color: #f3b613; }
        li:nth-child(8n + 7) { background-color: #ff8a4a; }
        li:nth-child(8n + 8) { background-color: #fc5366; }
    }
}
// .content.skin21 .banner {
//     background: linear-gradient(45deg,#17917a 0,#236ba5 100%)
// }
// .content.skin22 .banner {
//     background: linear-gradient(45deg,#009688 0,#17917a 100%)
// }
.top {
    position: fixed;
    right: 15px;
    bottom: -50px;
    opacity: 0;
    width: 48px;
    line-height: 48px;
    text-align: center;
    border-radius: 50%;
    font-size: 32px !important;
    color: #fff !important;
    background-color: rgba(#000, 0.3);
    transform: rotate(180deg);
    transition-duration: 0.2s;
    &.active {
        opacity: 1;
        bottom: 15px;
    }
    &::after {
        content: '\e588'
    }
}
.test {
    position: absolute;
    top: 0;
    right: 0;
    width: auto;
    font-size: 12px;
}
</style>
