<!--
使用方法：
与学生的一致。。。
只是将所有student字符改为class字符
-->
<template>
    <div class="container" v-if="show">
        <header class="bar bar-nav">
            <h1 class="title">选择班级</h1>
            <a href="javascript:void(0)" class="pull-right icon" @click="handleSubmitClick">关闭</a>
        </header>
        <div class="search-wrapper" @click="handleShowSearchPanelClick">
            <div>搜索</div>
        </div>
        <div class="checkbox-wrapper" @click="handleChangeAllCheck" v-if="isMultiple">
            <span  class="item-checkbox" :class="{ 'icon-uncheck':!isAllCheck,'icon-check':isAllCheck }"></span>
            <span class="item-label">全选</span>
        </div>
        <div class="content" ref="scrollWrapper" style="margin-top:10px">
            <vue-tree
              :is-multiple="isMultiple"
                :eventBus="eventBus"
                :tree-data="treeData">
            </vue-tree>
        </div>
        <div class="selector-bottom">
            <span>已选{{ selectedClassListArr.length  }}班级</span>
            <a @click="handleSubmitClick" class="submit-btn" href="javascript:void(0)">确定</a>
        </div>

        <div class="search-panel" v-show="showSearchPanel">
            <div style="width:100%;height:10px"></div>
            <form class="search-top" action="javascript:return true;">
                <input
                    v-model="searchVal"
                    @keyup.enter="handleSearchEvent"
                    @input="handleSearchEvent"
                    id="searchVal"
                    type="text"
                    placeholder="搜索" >
                    <a @click="showSearchPanel = false" href="javascript:void(0);">取消</a>
            </form>
            <div class="search-list" ref="searchScroll">
                <div>
                    <div v-for="(item,index) in searchList" :key="index" class="checkbox-wrapper" @click="handleSelectedSearchClick(index)">
                        <span class="item-checkbox" :class="item.checked ? 'icon-check' : 'icon-uncheck'"></span>
                        <span class="item-label">{{item.className}}</span>
                    </div>
                </div>
            </div>
            <div class="selector-bottom">
                <a @click="searchSubmit" class="submit-btn" href="javascript:void(0)">确定</a>
            </div>
        </div>
    </div>
</template>

<script>
import Vue from 'vue'
import BScroll from 'better-scroll'
import VHeader from '@/common/header/VHeader'
import VueTree from '@/common/selector/VueTree.vue'
export default {
    name: 'ClassSelector',
    components: {
        VHeader,
        VueTree
    },
    props: {
        show: {
            type: Boolean,
            default: false
        },
        initData: {
            type: Array,
            default: () => {
                return []
            }
        },
        isMultiple: {
            type: Boolean,
            default: true
        }
    },
    data () {
        return {
            eventBus: new Vue(),
            scroll: null,
            scrollSearch: null,
            treeData: [],
            classList: [],
            selectedClassListArr: [],
            // 是否全选
            isAllCheck: false,
            // 搜索列表
            searchList: [],
            searchVal: '',
            showSearchPanel: false
        }
    },
    watch: {
        show (newValue, oldValue) {
            if (newValue) {
                this.handleInitTreeData(this.treeData, this.initData)
                this.selectedClassListArr = []
                this.getSelectedClass(this.treeData)
                this.$nextTick(() => {
                    this.scroll = new BScroll(this.$refs.scrollWrapper, {
                        click: true
                    })
                })
                this.$nextTick(() => {
                    this.scrollSearch = new BScroll(this.$refs.searchScroll, {
                        click: true
                    })
                })
            }
        }
    },
    methods: {
        getClassList () {
            this.$api.platBaseApi.getGradeClassList().then(res => {
                let data = res.data
                if (data.Status) {
                    this.renderClassList(data.Data)
                }
            })
        },
        renderClassList (list) {
            for (var i in list) {
                this.treeData.push({
                    id: list[i].id,
                    name: list[i].fullname,
                    type: 'grade',
                    checked: false,
                    indeterminate: false,
                    children: []
                })
                for (var j in list[i].children) {
                    this.treeData[i].children.push({
                        id: list[i].children[j].id,
                        name: list[i].children[j].fullname,
                        gradeId: list[i].id,
                        gradeName: list[i].fullname,
                        type: 'class',
                        checked: false,
                        indeterminate: false
                    })
                    this.classList.push({
                        classId: list[i].children[j].id,
                        className: list[i].children[j].fullname,
                        gradeId: list[i].id,
                        gradeName: list[i].fullname,
                        checked: false
                    })
                }
            }
        },
        // 初始化数据
        handleInitTreeData (treeData, classList) {
            if (classList.length) {
                if (treeData.length) {
                    for (let i = 0; i < treeData.length; i++) {
                        let item = treeData[i]
                        if (treeData[i].type == 'class') {
                            for (let j = 0; j < classList.length; j++) {
                                let user = classList[j]
                                if (user.classId == item.id) {
                                    item.checked = true
                                }
                            }
                        } else {
                            if (item.children && item.children.length) {
                                this.handleInitTreeData(item.children, classList)
                            }
                        }
                    }
                }
                this.handleSetIndeterminate(this.treeData)
            } else {
                this.setChildChecked(false, this.treeData)
            }
        },
        // 全选
        handleChangeAllCheck () {
            this.isAllCheck = !this.isAllCheck
            this.setChildChecked(this.isAllCheck, this.treeData)
            this.selectedClassListArr = []
            this.getSelectedClass(this.treeData)
        },

        // 节点被点击
        /**
         * node 被点击的节点
         * checked 选中的状态
         * data 需要传递的数据，暂时为空
         */
        handleCheckChange (node, checked, data) {
            if (node.checked !== checked) {
                this.handleSetChecked(node, checked, this.treeData)
            }
            this.handleSetIndeterminate(this.treeData)
            this.selectedClassListArr = []
            this.getSelectedClass(this.treeData)
        },
        // 获取选中的用户
        getSelectedClass (treeData) {
            if (treeData.length) {
                for (let i = 0; i < treeData.length; i++) {
                    let item = treeData[i]
                    if (item.children && item.children.length) {
                        this.getSelectedClass(item.children)
                    } else {
                        if (item.checked && item.type === 'class') {
                            this.selectedClassListArr.push({
                                gradeId: item.gradeId,
                                gradeName: item.gradeName,
                                classId: item.id,
                                className: item.name
                            })
                        }
                    }
                }
            }
        },
        // 设置节点选中/不选中
        handleSetChecked (node, checked, children) {
            if (children && children.length) {
                for (let i = 0; i < children.length; i++) {
                    let child = children[i]
                    if (!this.isMultiple) {
                        child.checked = false
                    }
                    if (child.id == node.id) {
                        child.checked = checked
                        child.indeterminate = false
                        if (child.children && child.children.length) {
                            this.setChildChecked(checked, child.children)
                        }
                    } else {
                        this.handleSetChecked(node, checked, child.children)
                    }
                }
            }
        },
        // 设置子节点全部选中
        setChildChecked (checked, children) {
            for (let i = 0; i < children.length; i++) {
                let item = children[i]
                item.checked = checked
                item.indeterminate = false
                if (item.children && item.children.length) {
                    this.setChildChecked(checked, item.children)
                }
            }
        },
        // 设置选中/半选状态
        handleSetIndeterminate (treeData) {
            // 循环 children
            const loop = obj => {
                // 如果子元素还有有子元素就继续循环
                obj.children.map(item => item.children && item.children.length ? loop(item) : item)
                // 根据子元素的状态判断自身，如果子元素全选中则本身也选中，如果子元素有些全选或半选则本身半选，否则就是都没选
                obj.children.every(item => item.checked) ? (obj.checked = true, obj.indeterminate = false)
                    : obj.children.some(item => item.checked || item.indeterminate) ? (obj.checked = false, obj.indeterminate = true)
                        : (obj.checked = obj.indeterminate = false)
                return obj
            }
            treeData = treeData.map(item => loop(item))
        },
        handleSubmitClick () {
            this.$emit('handleSubmit', this.selectedClassListArr)
        },
        // 显示搜索框
        handleShowSearchPanelClick () {
            this.searchList = []
            this.searchVal = ''
            this.classList.map(item => item.checked = false)
            this.showSearchPanel = true
            setTimeout(() => {
                document.getElementById('searchVal').focus()
            }, 0)
        },
        // 搜索
        handleSearchEvent () {
            if (this.searchVal) {
                this.searchList = this.renderSearchList()
            }
        },
        renderSearchList () {
            return this.classList.filter(item => item.className.indexOf(this.searchVal) !== -1)
        },
        handleSelectedSearchClick (index) {
            if (!this.isMultiple) {
                this.searchList.map(item => { item.checked = false })
            }
            this.searchList[index].checked = !this.searchList[index].checked
        },
        // 确定提交搜索结果
        searchSubmit () {
            let classList = this.searchList.filter(item => item.checked)
            this.$nextTick(() => {
                this.handleInitTreeData(this.treeData, classList)
                this.getSelectedClass(this.treeData)
                this.showSearchPanel = false
            })
        }

    },
    created () {
        this.eventBus.$on('checked-change', this.handleCheckChange)
        this.getClassList()
    }
}
</script>

<style lang="less" scoped>
.container{
    position: fixed;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
    background: #efeff4
}
.selector-bottom{
    border-top: 1px solid #ccc;
    height: 50px;
    line-height: 50px;
    padding: 0 15px;
}
.submit-btn{
    float: right;
    margin-top:6px;
    width: 72px;
    height: 36px;
    line-height: 36px;
    text-align: center;
    background: #1296db;
    color: #fff;
    border-radius: 5px;
}
.checkbox-wrapper{
    background: #fff;
    padding: 10px 27px;
    span{
        display: inline-block;
        vertical-align: middle;
    }
}
.search-wrapper{
    width: 100%;
    background: #efeff4;
    div{
        background: #fff;
        margin: 10px;
        height: 32px;
        line-height: 32px;
        border-radius: 5px;
        color: #ccc;
        text-indent: 12px;
        font: 14px;
    }
}
.search-panel{
    width: 100%;
    position: fixed;
    top:0;left: 0;
    height: 100%;
    background: #efeff4;
    z-index: 10;
    display: flex;
    flex-direction:column;
    .search-top{
        display: flex;
        margin: 0 10px 10px;
        input{
            flex:1;
            background: #fff;
            height: 32px !important;
            line-height: 32px !important;
            border-radius: 5px;
            text-indent: 12px;
            font: 14px;
            border: 0px;
        }
        a{
            height: 32px;
            line-height: 32px;
            padding: 0 5px 0 10px;
            color: #1296db
        }
    }
    .search-list{
        flex:1;
        overflow: hidden;
    }
}
</style>
