<!--
使用方法：
与学生的一致。。。
只是将所有student字符改为teacher字符
-->
<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="group-tab" >
            <div class="tab-item" :class="isShowOrganize ? 'current' : ''" @click="handleOrganizeTabChange(true)">组织架构</div>
            <div class="tab-item" :class="!isShowOrganize ? 'current' : ''" @click="handleOrganizeTabChange(false)">自定义分组</div>
        </div>
        <div onselectstart="return false;" class="checkbox-wrapper"  v-if="isMultiple">
            <span @click="handleChangeAllCheck" 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" v-if="isShowOrganize">
            <vue-tree
        :is-multiple="isMultiple"
              :eventBus="eventBus"
                :tree-data="treeData">
            </vue-tree>
        </div>
        <div class="content" ref="scrollWrapper" style="margin-top:10px" v-else>
            <vue-tree
        :is-multiple="isMultiple"
                :eventBus="eventBus"
                :tree-data="customTreeData">
            </vue-tree>
        </div>
        <div class="selector-bottom">
            <span>已选{{ isShowOrganize ? selectedTeacherListArr.length : selectedCustomTeacherLsitArr.length }}人</span>
            <a @click="handleSubmitClick" class="submit-btn" href="javascript:void(0)">确定</a>
        </div>
        <!-- search-panel -->
        <div class="search-panel" v-show="showSearchPanel">
            <div style="width:100%;height:10px"></div>
            <form class="search-top">
                <input
                    v-model="searchVal"
                    id="searchVal"
                    @keyup.enter="handleSearchEvent"
                    @input="handleSearchEvent"
                    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.teacherName }}</span>
                    </div>
                </div>
            </div>
            <div class="selector-bottom">
                <a @click="searchSubmit" class="submit-btn" href="javascript:void(0)">确定</a>
            </div>
        </div>

        <div v-transfer-dom>
            <loading :show="showLoad" :text="'加载中...'"></loading>
        </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'
import { Loading, TransferDomDirective as TransferDom } from 'vux'
export default {
    name: 'TeacherSelector',
    directives: {
        TransferDom
    },
    components: {
        VHeader,
        VueTree,
        Loading
    },
    props: {
        show: {
            type: Boolean,
            default: false
        },
        userlist: {
            type: Array,
            default: () => {
                return []
            }
        },
        isMultiple: { // 默认多选
            type: Boolean,
            default: true
        }
    },
    data () {
        return {
            eventBus: new Vue(),
            close: true,
            scroll: null,
            scrollSearch: null,
            treeData: [],
            customTreeData: [],
            singleTeacher: {}, // 单选时，单个老师对象
            // 设置项
            // options: {
            //     // String,节点显示字段
            //     label: 'name',
            //     // Boolean,是否显示选择框
            //     checkbox: true,
            //     // Boolean,选中时是否展开节点
            //     checkedOpen: true,
            //      // Boolean,目录是否加粗显示
            //     folderBold: true,
            //     // Boolean,获取复选项目是否包含目录,默认`true`,如果只获取叶子节点设置为`false`
            //     idsWithParent: false,
            //     // Number,初始化时展开层级,根节点为0,默认0
            //     depthOpen: 0
            // },
            // 是否全选
            isAllCheck: false,
            // 搜索列表
            searchList: [],
            searchVal: '',
            showLoad: false,
            showSearchPanel: false,

            teacherListArr: [],
            selectedBranchListArr: [],
            selectedTeacherListArr: [],
            selectedCustomBranchListArr: [],
            selectedCustomTeacherLsitArr: [],
            isShowOrganize: true,
            isGetOrganize: false,
            isGetCustomOrganize: false
        }
    },
    methods: {
    // 获取组件架构
        getOrganizeTreeWithUser () {
            // 新平台的接口
            this.$api.platBaseApi.getOrganizeTreeWithUser().then(res => {
                let data = res.data
                if (data.Status) {
                    // var list = item.Data.children;
                    if (data.Data.children && data.Data.children.length) {
                        this.treeData = this.loopTreeItem(data.Data, 'organize')
                    }
                }
                this.isGetOrganize = true
            })
        },
        // 自定义分组
        getCustomGroupWithPeople () {
            // 新平台的接口
            this.$api.platBaseApi.getCustomGroupWithPeople().then(res => {
                let data = res.data
                if (data.Status) {
                    if (data.Data.length) {
                        this.customTreeData = this.loopTreeItem({ children: data.Data }, 'custom')
                    }
                }
                this.isGetCustomOrganize = true
            })
        },
        loopTreeItem (res, type) {
            const loop = res => {
                var treeData = []
                res.children.forEach(item => {
                    let obj = {}
                    obj.id = item.id
                    obj.name = item.fullname
                    obj.checked = false
                    obj.type = 'branch'
                    obj.indeterminate = false
                    obj.children = item.children && item.children.length ? (item.children.map(child => {
                        return {
                            id: child.id,
                            name: child.fullname,
                            type: 'branch',
                            checked: false,
                            indeterminate: false,
                            children: child.chidlren
                        }
                    }), loop(item)) : []
                    if (item.users && item.users.length) {
                        item.users.forEach(item2 => {
                            obj.children.push({
                                type: 'user',
                                id: item2.user_id,
                                name: item2.real_name,
                                checked: false,
                                indeterminate: false,
                                departmentId: item.id,
                                departmentName: item.fullname
                            })
                            if (type == 'organize') {
                                this.teacherListArr.push({
                                    teacherId: item2.user_id,
                                    teacherName: item2.real_name,
                                    departmentId: item.id,
                                    departmentName: item.fullname,
                                    checked: false
                                })
                            }
                        })
                    }
                    treeData.push(obj)
                })
                return treeData
            }
            return loop(res)
        },
        // 分组切换
        handleOrganizeTabChange (flag) {
            if (!flag && !this.isGetCustomOrganize) {
                this.getCustomGroupWithPeople()
            }
            if (this.isShowOrganize == flag) { return }
            this.isShowOrganize = flag
            if (this.isShowOrganize) {
                this.isAllCheck = this.selectedBranchListArr.length > 0 && this.selectedBranchListArr.length == this.treeData.length
            } else {
                this.isAllCheck = this.selectedCustomBranchListArr.length > 0 && this.selectedCustomBranchListArr.length == this.customTreeData.length
            }
        },
        // 初始化数据
        handleInitTreeData (treeData, userList) {
            if (userList.length) {
                if (treeData.length) {
                    for (let i = 0; i < treeData.length; i++) {
                        let item = treeData[i]
                        if (treeData[i].type == 'user') {
                            for (let j = 0; j < userList.length; j++) {
                                let user = userList[j]
                                if (user.teacherId == item.id) {
                                    item.checked = true
                                }
                            }
                        } else {
                            if (item.children && item.children.length) {
                                this.handleInitTreeData(item.children, userList)
                            }
                        }
                    }
                }
                this.handleSetIndeterminate(this.treeData)
            } else {
                this.setChildChecked(false, this.treeData)
            }
        },
        // 全选
        handleChangeAllCheck (checked) {
            this.isAllCheck = !this.isAllCheck
            if (this.isShowOrganize) {
                this.setChildChecked(this.isAllCheck, this.treeData)
                this.selectedTeacherListArr = []
                this.getSelectedUser(this.treeData)
            } else {
                this.setChildChecked(this.isAllCheck, this.customTreeData)
                this.selectedCustomTeacherLsitArr = []
                this.getSelectedUser(this.customTreeData)
            }
        },
        // 获取选中的第一级数据
        getSelectedBranch (treeData) {
            if (treeData.length) {
                return treeData.filter(item => item.checked)
            } else {
                return []
            }
        },
        // 节点被点击
        /**
         * node 被点击的节点
         * checked 选中的状态
         * data 需要传递的数据，暂时为空
         */
        handleCheckChange (node, checked, data) {
            if (!this.isMultiple) { // 单选教师
                this.singleTeacher = {
                    departmentId: node.departmentId,
                    departmentName: node.departmentName,
                    teacherId: node.id,
                    teacherName: node.name
                }
            }
            if (this.isShowOrganize) {
                if (node.checked !== checked) {
                    this.handleSetChecked(node, checked, this.treeData)
                }
                this.handleSetIndeterminate(this.treeData)
                this.selectedBranchListArr = this.getSelectedBranch(this.treeData)
                this.selectedTeacherListArr = []
                this.getSelectedUser(this.treeData)
            } else {
                if (node.checked !== checked) {
                    this.handleSetChecked(node, checked, this.customTreeData)
                }
                this.handleSetIndeterminate(this.customTreeData)
                this.selectedCustomBranchListArr = this.getSelectedBranch(this.customTreeData)
                this.selectedCustomTeacherLsitArr = []
                this.getSelectedUser(this.customTreeData)
            }
        },
        // 获取选中的用户
        getSelectedUser (treeData) {
            if (treeData.length) {
                for (let i = 0; i < treeData.length; i++) {
                    let item = treeData[i]
                    if (item.checked && item.type === 'user') {
                        this.isShowOrganize ? this.selectedTeacherListArr.push({
                            teacherId: item.id,
                            teacherName: item.name,
                            departmentId: item.departmentId,
                            departmentName: item.departmentName
                        }) : this.selectedCustomTeacherLsitArr.push({
                            teacherId: item.id,
                            teacherName: item.name,
                            departmentId: item.departmentId,
                            departmentName: item.departmentName
                        })
                    }
                    if (item.children && item.children.length) {
                        this.getSelectedUser(item.children)
                    }
                }
            }
        },
        // 设置节点选中/不选中
        handleSetChecked (node, checked, children) {
            if (children && children.length) {
                for (let i = 0; i < children.length; i++) {
                    let child = children[i]
                    if (child.id == node.id) {
                        // if(child.children && child.children.length){
                        //  this.setChildChecked(checked,child.children);
                        // }
                        //  解决自定义分组人员重复问题
                        if (node.departmentId) {
                            if (node.departmentId == child.departmentId) {
                                child.checked = checked
                                child.indeterminate = false
                                if (child.children && child.children.length) {
                                    this.setChildChecked(checked, child.children)
                                }
                            }
                        } else {
                            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) {
            if (children.length && 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)
                // 根据子元素的状态判断自身，如果子元素全选中则本身也选中，如果子元素有些全选或半选则本身半选，否则就是都没选
                if (obj.children.length) {
                    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))
        },
        // 设置节点下子节点是否全选
        // handleSetIndeterminate(treeData,data){
        //  if(treeData.length){
        //      for(let i = 0 ; i < treeData.length; i++){
        //          let item = treeData[i];
        //       if(item.children && item.children.length){
        //              let state =  this.getChildNodeState(item.children);
        //              item.checked = state.all ;
        //              item.indeterminate = !state.all && !state.none;
        //              this.handleSetIndeterminate(item.children,data)
        //         // this.setIndeterminate(item,item.children,item.children.length,data);
        //          }
        //      }
        //  }
        // },
        // getChildNodeState(children){
        //  let checkedItem =  [], indeterItem = [];
        //  let all = false, none = false ;
        //   if(children.length){
        //      for(let i =0 ;i < children.length; i++){
        //          const node = children[i];
        //          if(node.checked && !node.indeterminate){
        //              checkedItem.push(node)
        //          }
        //          if(!node.checked && node.indeterminate){
        //              indeterItem.push(node)
        //          }
        //      }
        //      all = checkedItem.length ===  children.length;
        //      none = checkedItem.length === 0 && indeterItem.length === 0;
        //  }
        //  return { all,  none };
        // },
        // 显示搜索框
        handleShowSearchPanelClick () {
            this.searchList = []
            this.searchVal = ''
            this.teacherListArr.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.teacherListArr.filter(item => item.teacherName.indexOf(this.searchVal) !== -1)
        },
        handleSelectedSearchClick (index) {
            if (this.isMultiple) {
                this.searchList[index].checked = !this.searchList[index].checked
            } else {
                this.searchList.map((item, searchIndex) => {
                    if (searchIndex !== index) {
                        item.checked = false
                    }
                })
                this.searchList[index].checked = !this.searchList[index].checked
            }
        },
        // 确定提交搜索结果
        searchSubmit () {
            let userList = this.searchList.filter(item => item.checked)
            if (!this.isMultiple && userList && userList.length === 1) {
                this.singleTeacher = { // 赋值给单个老师
                    departmentId: userList[0].departmentId,
                    departmentName: userList[0].departmentName,
                    teacherId: userList[0].teacherId,
                    teacherName: userList[0].teacherName
                }
            }
            this.$nextTick(() => {
                this.handleInitTreeData(this.treeData, userList)
                this.isShowOrganize ? this.selectedTeacherListArr = [] : this.selectedBranchListArr = []
                this.getSelectedUser(this.treeData)
                this.showSearchPanel = false
            })
        },
        // 确定
        handleSubmitClick () {
            if (this.isMultiple) { // 默认多选
                let list = this.handleUniqueObjArr(this.selectedTeacherListArr.concat(this.selectedCustomTeacherLsitArr), 'teacherId')
                list.forEach(item => {
                    item.id = item.teacherId
                    item.realname = item.teacherName
                })
                this.$emit('handleSubmit', list)
            } else { // 单选
                this.selectedTeacherListArr.length = 0
                if (JSON.stringify(this.singleTeacher) !== '{}') {
                    this.singleTeacher.id = this.singleTeacher.teacherId
                    this.singleTeacher.realname = this.singleTeacher.teacherName
                    this.selectedTeacherListArr.push(this.singleTeacher)
                }
                this.$emit('handleSubmit', this.selectedTeacherListArr)
            }
        },
        handleCloseClick () {
            this.$emit('close')
        },
        // 数组对象去重 param 需要去重的参数
        handleUniqueObjArr (arr, param) {
            const res = new Map()
            return arr.filter((a) => !res.has(a[param]) && res.set(a[param], 1))
        },
        getRecursion () {
            const loop = obj => {
                obj.children.map(item => {
                    if (item.children && item.children.length > 0) {
                        loop(item)
                    } else {
                        if (item.id !== this.singleTeacher.teacherId) {
                            item.checked = false
                        }
                        return item
                    }
                })
            }
            let arr = this.treeData
            this.treeData.map(item => loop(item))
        }
    },
    watch: {
        selectedTeacherListArr (newVal, oldVal) {
            if (!this.isMultiple && newVal && newVal.length > 1) {
                this.selectedTeacherListArr = oldVal
                setTimeout(() => {
                    this.getRecursion()
                }, 0)
            }
        },
        selectedBranchListArr (newValue, oldValue) {
            this.isAllCheck = newValue.length > 0 && newValue.length == this.treeData.length
        },
        selectedCustomBranchListArr (newValue, oldValue) {
            this.isAllCheck = newValue.length > 0 && newValue.length == this.customTreeData.length
        },
        show (newValue, oldValue) {
            if (newValue) {
                if (!this.isGetOrganize) {
                    this.getOrganizeTreeWithUser()
                }
                this.isShowOrganize = true
                this.setChildChecked(false, this.treeData)
                this.handleInitTreeData(this.treeData, this.userlist)
                this.selectedTeacherListArr = []
                this.selectedBranchListArr = []
                this.getSelectedUser(this.treeData)
                this.selectedBranchListArr = this.getSelectedBranch(this.treeData)
                this.$nextTick(() => {
                    this.scroll = new BScroll(this.$refs.scrollWrapper, {
                        click: true
                    })
                })
                this.$nextTick(() => {
                    this.scrollSearch = new BScroll(this.$refs.searchScroll, {
                        click: true
                    })
                })
            }
        }
    },
    created () {
        this.eventBus.$on('checked-change', this.handleCheckChange)
        this.getOrganizeTreeWithUser()
    // this.getCustomGroupWithPeople();
    }
}
</script>

<style lang="less" scoped>
.container{
    position: fixed;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 9000;
    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;
    }
}
.group-tab {
    display: flex;
    border: 1px solid #409eff;
    background-color: #fff;
    border-radius: 3px;
    margin: 0 10px 10px 10px;
    .tab-item {
        width: 50%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    color: #409eff;
    }
    .current {
        background-color: #409eff;
    color: #fff;
    }
}

.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>
