<template>
    <div class="box h100p">
        <!-- 选部门时自定义分组不可选择 -->
        <template v-if="/teacher|student/.test(mode)">
            <!-- 搜索 -->
            <el-input
                class="search"
                :placeholder="`请输入姓名或${/teacher/.test(mode) ? '手机' : '学'}号`"
                v-model.trim="value"
                @keyup.native.enter="search"
            >
                <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>

            <!-- 切换分组 -->
            <el-radio-group
                class="type"
                v-model="radio"
                @change="$event ? getTreeList() : getCustomList()"
                v-if="/teacher/.test(mode)"
            >
                <el-radio-button class="btn" :label="true">组织架构</el-radio-button>
                <el-radio-button class="btn" :label="false">自定义分组</el-radio-button>
            </el-radio-group>
        </template>

        <!-- 组织架构 -->
        <el-tree
            :data="treeList"
            :props="{ label: 'realname', children: 'children' }"
            :class="{ radio: /(group|class)Radio/.test(mode) }"
            ref="tree"
            node-key="id"
            show-checkbox
            default-expand-all
            check-on-click-node
            :expand-on-click-node="false"
            @check="treeChange"
            v-show="radio"
        ></el-tree>

        <!-- 自定义分组 -->
        <div v-show="!radio">
            <el-checkbox-group class="custom" v-model="customChecked">
                <el-checkbox
                    v-for="item in customList"
                    :key="item.id"
                    :label="item.id"
                    @change="customChange"
                >{{ item.realname }}</el-checkbox>
            </el-checkbox-group>
            <div class="el-tree__empty-block" v-if="!customList.length">
                <span class="el-tree__empty-text">暂无数据</span>
            </div>
        </div>
    </div>
</template>

<script>
import { removeRepeatByKey } from '@/assets/utils/util.js'
// 兼容旧接口的数据: user_id 转 id, real_name 转 realname, MOBILE 转 mobile
const userMap = (list, custom) => list.map(item => ({
    id: item.user_id || '',
    realname: item.real_name || '',
    mobile: custom ? item.MOBILE || '' : item.mobile || '',
    type: 'teacher'
}))
export default {
    props: {
        mode: { type: String, default: '' },
        selectList: { type: Array, default: () => [] },
        checkedList: { type: Array, default: () => [] }
    },
    data () {
        return {
            value: '', // 搜索框
            radio: true, // 架构类型
            treeList: [], // 当前组织架构
            treeUserList: [], // 组织架构所有的人，用于搜索

            teacherList: [], // 教师端组织架构
            teacherUserList: [], // 教师端组织架构所有的人
            customList: [], // 教师端自定义分组
            customChecked: [], // 自定义分组选中的值
            treeSelected: [], // 组织架构选中的人，用于合并
            customSelected: [], // 自定义分组选中的人，用于合并

            studentList: [], // 学生端组织架构
            studentUserList: [] // 学生端组织架构所有的人
        }
    },
    watch: {
        // 切换模式时初始化数据，重新判断是否隐藏自定义分组
        mode () {
            this.clear()
            this.getTreeList()
            if (/group/.test(this.mode) && !this.radio) this.radio = true
        }
    },
    created () {
        this.getTreeList()
    },
    methods: {
        // 部门模式下初始化选中组织架构
        initTree () {
            if (/group|class/.test(this.mode) && this.checkedList.length) {
                const idList = this.checkedList.map(item => item.id)
                this.$refs.tree.setCheckedKeys(idList)
            }
        },
        // 获取组织架构
        getTreeList () {
            if (/teacher|group/.test(this.mode)) {
                if (!this.teacherList.length) this.getTeacherList()
                else this.treeList = this.teacherList
            } else {
                if (!this.studentList.length) this.getStudentList()
                else this.treeList = this.studentList
            }
        },
        // 获取教师端组织架构
        getTeacherList () {
            this.$api.platBaseApi.getOrganizeTreeWithUser().then(res => {
                if (res.data.Status) {
                    const userList = []
                    const loop = list => {
                        list.forEach(item => {
                            item.type = 'group'
                            item.realname = item.fullname
                            item.users = userMap(item.users)
                            userList.push(...item.users)
                            if (item.children.length) loop(item.children)
                        })
                    }
                    loop([res.data.Data])
                    this.treeUserList = this.teacherUserList = removeRepeatByKey(userList, 'id')
                    this.treeList = this.teacherList = [res.data.Data]
                    this.initTree()
                }
            })
        },
        // 获取教师端自定义分组
        getCustomList () {
            if (this.customList.length) return false
            this.$api.platBaseApi.getCustomGroupWithPeople().then(res => {
                if (res.data.Status) {
                    res.data.Data.forEach(item => {
                        item.realname = item.fullname
                        item.users = userMap(item.users, true)
                    })
                    this.customList = res.data.Data
                }
            })
        },
        // 获取学生端组织架构
        getStudentList () {
            this.$api.platBaseApi.getGradeStructureWithStudent().then(res => {
                if (res.data.Status) {
                    const userList = []
                    const loop = list => {
                        list.forEach(item => {
                            item.type = 'class'
                            item.realname = item.fullname
                            if (item.children.length) {
                                if (item.gradeno) {
                                    // 循环一次班级
                                    loop(item.children)
                                } else {
                                    // 获取学生数据
                                    item.student = item.children.map(item => ({
                                        id: item.studentId || '',
                                        realname: item.studentName || '',
                                        studentCode: item.studentCode || '',
                                        type: 'student'
                                    }))
                                    userList.push(...item.student)
                                    item.children = []
                                }
                            }
                        })
                    }
                    loop(res.data.Data)
                    this.treeUserList = this.studentUserList = removeRepeatByKey(userList, 'id')
                    this.treeList = this.studentList = res.data.Data
                    this.initTree()
                }
            })
        },
        // 搜索
        search () {
            if (!this.value) return this.$message.warning('输入内容不能为空')
            const list = this.treeUserList.filter(item => {
                if (/teacher/.test(this.mode)) {
                    return item.realname.includes(this.value) || item.mobile.includes(this.value)
                } else {
                    return item.realname.includes(this.value) || item.studentCode.includes(this.value)
                }
            })
            if (list.length) {
                this.$emit('update:selectList', list)
                this.$refs.tree.setCheckedKeys([])
                this.customChecked = []
            } else {
                this.$message('暂无查询结果')
            }
        },
        // 点击组织架构节点
        treeChange (data, node) {
            /teacher/.test(this.mode) ? this.teacherTree(data, node)
                : /student/.test(this.mode) ? this.studentTree(data, node)
                    : this.groupTree(data, node)
        },
        // 组织架构选教师
        teacherTree (data, node) {
            const { checked } = this.$refs.tree.getNode(data.id)
            this.treeSelected = node.checkedNodes.flatMap(item => item.users)
            this.concatList(checked)
        },
        // 自定义分组选教师
        customChange (checked) {
            this.customSelected = this.customList.filter(item => this.customChecked.includes(item.id)).flatMap(item => item.users)
            this.concatList(checked)
        },
        // 合并组织架构和自定义分组选中的人
        concatList (checked) {
            if (checked && this.selectList.length) this.$emit('add')
            const list = [].concat(this.treeSelected, this.customSelected)
            this.$emit('update:selectList', removeRepeatByKey(list, 'id'))
        },
        // 组织架构选择
        groupTree (data, node) {
            // 如果是单选只保留当前选中
            if (/radio/i.test(this.mode)) {
                this.$refs.tree.setCheckedKeys([data.id])
                node.checkedNodes = [data]
            }
            const list = []
            const idList = []
            node.checkedNodes.forEach((item, index) => {
                if (item.children.length) idList.push(...item.children.map(n => n.id))
                if (!idList.includes(item.id)) list.push(item)
            })
            this.$emit('update:checkedList', list)
        },
        // 组织架构选学生
        studentTree (data, node) {
            const { checked } = this.$refs.tree.getNode(data.id)
            if (checked && this.selectList.length) this.$emit('add')
            const list = node.checkedNodes.filter(item => item.student).flatMap(item => item.student)
            this.$emit('update:selectList', removeRepeatByKey(list, 'id'))
        },
        // 清空组织架构
        clear () {
            this.$refs.tree.setCheckedKeys([])
            this.$emit('update:selectList', [])
        },
        // 移除组织架构（外部调用，删除选中时触发）
        delTree () {
            this.$nextTick(() => {
                const idList = this.checkedList.map(item => item.id)
                this.$refs.tree.setCheckedKeys(idList)
            })
        }
    }
}
</script>

<style lang="less" scoped>
.search, .type {
    margin-bottom: 10px;
}
.type {
    display: flex;
    .btn {
        width: 50%;
        /deep/ span {
            display: block;
        }
    }
}
.el-tree {
    background-color: transparent;
    /deep/ .el-tree-node__label {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}
.el-tree.radio {
    /deep/ .is-indeterminate .el-checkbox__inner {
        background-color: #fff;
        border-color: #DCDFE6;
    }
    /deep/ .el-checkbox__inner {
        border-radius: 50%;
        &::after {
            width: 4px;
            height: 4px;
            border: none;
            border-radius: 50%;
            background-color: #fff;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            transition-property: all;
        }
    }
    /deep/ .is-checked .el-tree-node__children .el-checkbox__inner::after {
        background-color: transparent;
    }
}
</style>
