<template>
    <div class="menu-authorization-dialog-main">
        <div class="import-data-top">
            <div class="label"></div>
            <el-input
                :placeholder="`${$t('cs.common.text.searchPlaceholder')}...`"
                size="small"
                v-model="filterText"
                @keyup.enter.native="searchAllCompany"
                prefix-icon="el-icon-search"
            ></el-input>
        </div>
        <div style="margin-top: 10px;height: calc(100% - 60px);display: flex;box-sizing: border-box;flex-direction: column;" >
            <div class="choose-all-check-box-content">
                <el-checkbox @change="chooseAllMenu" v-model="allChecked">{{$t('cs.common.text.selectAll')}}</el-checkbox>
            </div>
            <div class="department-tree" v-show="isShowTree">
                <!-- 默认左侧树 -->
                <el-tree ref="tree" :empty-text="$t('cs.common.text.noData')" :default-expanded-keys="defaultExpandedKeys" :expand-on-click-node="false" node-key="id" :default-expand-all="true"
                    :highlight-current="true" :data="treeData" :props="treeData" :current-node-key="currentNode" :check-on-click-node="true" @node-click="treeClick" >
                    <span class="tree-slot" slot-scope="{ data }" :title="data.backName || data.name">
                    <!-- 资源表 -->
                    <span class="flex-align-center">
                        <span class="tree-slot-content">
                            <img v-show="data.isPublic" style="margin-right: 8px;" src="../Images/NotSelectable.png" />
                            <el-checkbox v-show="!data.isPublic" style="margin-right: 8px;" :indeterminate="data.children && data.children.length > 0 ? data.isIndeterminate : false" @click.stop.native="clickStop($event)" @change="checkBoxChange(data)" v-model="data.checked"></el-checkbox>
                            <i v-if="data.type != '0'" class="el-icon-folder"></i>
                            <i v-if="data.type == '0'" class="el-icon-s-home" style="margin-right: 8px;"></i>
                            <span class="title" v-html="data.name"></span>
                        </span>
                    </span>
                    </span>
                </el-tree>
            </div>
        </div>
        
    </div>
</template>
<script scoped>
// @ is an alias to /src
import  CoreAPI from "../../Common/JS/CoreAPI";
export default {
    props: {
        menuIdList: {
            type: Array,
            default: function () {
                return []
            }
        },
        roleId: {
            type: String,
            default: function () {
                return ''
            }
        },
        userId: {
            type: String,
            default: function () {
                return ''
            }
        },
        orgId: {
            type: String,
            default: function () {
                return ''
            }
        },
        authorityType: {
            type: String,
            default: function () {
                return ''
            }
        }
    },
    data() {
        return {
            filterText: '',
            defaultExpandedKeys: [],
            currentNode: '',
            allChecked: false,
            treeData: [],
            isShowTree: false,
            firstTargetValue: null
        };
    },
    watch: {
        
    },
    methods: {
        loadMenuAuthorityTree(){
            let _this = this;
            let postData = {
                "authorityType": _this.authorityType,
                "roleId": _this.roleId ? _this.roleId : null,
                "userId": _this.userId ? _this.userId : null,
                "orgId": _this.orgId ? _this.orgId : null,
                "systemId":  CloudServiceCommon.Props.systemId,
                "filterModel": {
                    "filterGroupModel": []
                },
                "sortModels": [
                    {
                        "fieldName": "order",
                        "sortType": 0
                    }
                ]
            }
            CoreAPI.getMenuAuthorityTree(postData).then(function(res) {
                _this.handleTreeData(res)
                _this.isAllChoose(res)
                _this.checkHandleTreeData(res)
                _this.treeData = res
                _this.isShowTree = true
            })
        },
        // 拼接
        join(str, key, id) {
            var reg = new RegExp(`(${key})`, 'igm')
            var replace = '<span id='+ id +' style="background-color: #fff179;">$1</span>'
            return str.replace(reg, replace)
        },
        // 检查复选框 三种状态是否显示正确
        checkHandleTreeData(tree, isSearch){
            let _this = this;
            console.log(_this.menuIdList)
            tree?.forEach(function(item) {
                // 检查那种未选中的 看看有没有子 如果有子的话 子是不是存在选中状态
                if(!item.checked && item.children && item.children.length) {
                    var checkNum = 0
                    // 循环子
                    item.children.forEach(function(target) {
                        // 如果选中 数量加1
                        target.checked ? checkNum++ : ''
                    })
                    console.log(checkNum)
                    // 如果有选中子 就选中
                    checkNum != 0 ? item.checked = true : ''
                    // 如果有选中子 并且 不是所有子选中 那半选
                    checkNum != 0 && checkNum != item.children.length ?  item.isIndeterminate = true : ''
                }
            })
        },
        handleTreeData(tree, isSearch){
            let _this = this;
            console.log(_this.menuIdList)
            tree?.forEach(function(item) {
                item.isIndeterminate = false;
                item.checked = item.isAuthority ? true : false;
                if(isSearch) {
                    _this.menuIdList.indexOf(item.id) == '-1' ? item.checked = false : item.checked = true
                }else{
                    !item.isPublic && item.isAuthority && _this.menuIdList.indexOf(item.id) == '-1' ? _this.menuIdList.push(item.id) : ''
                }
                if(item.children && item.children.length > 0) {
                    item.checked && _this.handleTreeTargetData(item, isSearch)
                    _this.handleTreeData(item.children, isSearch)
                }
            })
        },
        handleTreeTargetData(item, isSearch) {
            let _this = this;
            let publicNum = 0
            let chooseNum = 0
            item.children.forEach(function(target) {
                if(target.isPublic) {
                    publicNum++
                }else{
                    if(isSearch) {
                        _this.menuIdList.indexOf(target.id) != '-1' ? chooseNum++ : ''
                    }else{
                        target.isAuthority ? chooseNum++ : ''
                    }
                }
            })
            let target = item.children.length - publicNum
            target == chooseNum ? item.isIndeterminate = false : item.isIndeterminate = true;
        },
        checkBoxChange(data) {
            let _this = this;
            if(data.checked) {
                _this.menuIdList.indexOf(data.id) == '-1' ? _this.menuIdList.push(data.id) : ''
            }else{
                _this.menuIdList.indexOf(data.id) != '-1' ? _this.menuIdList.splice(_this.menuIdList.indexOf(data.id), 1) : ''
            }
            _this.$nextTick(function(){
                if(data.children && data.children.length > 0) {
                    _this.ergodicTree(data.children, data.checked)
                }
                data.isIndeterminate && (data.isIndeterminate = false)
                _this.setParentNodeCheck(data.id)
                _this.isAllChoose(_this.treeData)
            })
        },
        treeClick(data) {
            let _this = this;
            data.checked = !data.checked
            if(data.checked) {
                _this.menuIdList.indexOf(data.id) == '-1' ? _this.menuIdList.push(data.id) : ''
            }else{
                _this.menuIdList.indexOf(data.id) != '-1' ? _this.menuIdList.splice(_this.menuIdList.indexOf(data.id), 1) : ''
            }
            _this.$nextTick(function(){
                if(data.children && data.children.length > 0) {
                    _this.ergodicTree(data.children, data.checked)
                }
                data.isIndeterminate && (data.isIndeterminate = false)
                _this.setParentNodeCheck(data.id)
                _this.isAllChoose(_this.treeData)
            })
        },
        findParentNode(tree, id) {
            let _this = this;
            let elementNode = null
            tree.forEach(function(element) {
                if (element.id == id) elementNode = element
                if (elementNode) return elementNode
                if(element.children && element.children.length > 0) {
                    return _this.findParentNode(element.children, id)
                }
            })
            return elementNode
        },
        // 递归设置父节点的选中状态
        setParentNodeCheck: function (nodeId) {
            let _this = this;
            // 获取当前节点的父节点
            var parentNode = null;
            for (var i = 0; i < _this.treeData.length; i++) {
                parentNode = _this.getParentNodeByChildNode(_this.treeData[i], nodeId);
                if (parentNode) {
                    break;
                }
            }
            if (parentNode != null) {
                console.log(parentNode)
                _this.setTreeNodeCheckState(parentNode)
                // 如果不是根节点,进入递归
               _this.setParentNodeCheck(parentNode.id);
            }
            else {
                // 如果最上级节点,递归结束
                return;
            }
        },
        setTreeNodeCheckState: function (node) {
            let _this = this;
            // 然后判断当前节点是否是不需要授权
            // if (!node.needAuthority) {
                // 如果是不需要授权,那么只可能是全选中或者半选中,他的子若全是选中则是全选中,若不是全选中则认为是半选中
            // }
            // 这里要判断,若当前节点为未选中,则直接为未选中

            // 判断当前节点下的子节点是否全部是全部选中
            var allChecked = true;
            // 判断当前节点下的子节点是否一个都没有选
            var allUnChecked = true;

            for (var i = 0; i < node.children.length; i++) {
                if (node.children[i].checked) {
                    allUnChecked = false;
                }
                if (!node.children[i].checked) {
                    allChecked = false;
                }
            }

            if (allChecked && !node.isPublic) {
                // 如果是全部选中,把当前根节点设置为选中
                node.checked = true
                node.isIndeterminate = false
            }
            else {
                // 如果不是全部选中,要继续判断是否一个也没有勾选
                if (allUnChecked && !node.isIndeterminate) {
                    // 如果一个选中的也没有,则把当前节点置为未选中状态------(这里应该永远走不到)
                    // node.checked = false
                    let hasPublic = false;
                    for (var i = 0; i < node.children.length; i++) {
                        if (node.children[i].isPublic) {
                            hasPublic = true;
                        }
                    }
                    if(hasPublic) {
                        node.checked = true
                        node.isIndeterminate = true
                    }
                }
                else {
                    // 这里把当前节点置为半选中状态
                    if(!node.isPublic) {
                        node.checked = true
                        node.isIndeterminate = true
                    }
                }
            }
            if(node.checked && !node.isPublic) {
                _this.menuIdList.indexOf(node.id) == '-1' ? _this.menuIdList.push(node.id) : ''
            }else{
                _this.menuIdList.indexOf(node.id) != '-1' ? _this.menuIdList.splice(_this.menuIdList.indexOf(node.id), 1) : ''
            }
        },
        // 根据子节点获取父节点的方法
        getParentNodeByChildNode: function (node, childNodeId) {
            let _this = this;
            for (var i = 0; i < node.children.length; i++) {
                if (node.children[i].id == childNodeId) {
                    return node;
                }
                else {
                    var returnNode = _this.getParentNodeByChildNode(node.children[i], childNodeId);
                    if (returnNode) {
                        return returnNode;
                    }
                }
            }
            return null;
        },
        //回车搜索
        searchAllCompany() {
            let _this = this;
            //延迟5s执行搜索
            let timer = setTimeout(() => {
                this.$nextTick(() => {
                    let filterValue = _this.filterText.trim()
                    _this.pageIndex = '1'
                    let postData = {
                        "authorityType": _this.authorityType,
                        "roleId": _this.roleId ? _this.roleId : null,
                        "userId": _this.userId ? _this.userId : null,
                        "orgId": _this.orgId ? _this.orgId : null,
                        "systemId":  CloudServiceCommon.Props.systemId,
                        "filterModel": {
                            "filterGroupModel": []
                        },
                        "sortModels": [
                            {
                                "fieldName": "order",
                                "sortType": 0
                            }
                        ]
                    }
                    CoreAPI.getMenuAuthorityTree(postData).then(function(res) {
                        if (filterValue !== "") {
                            _this.firstTargetValue = null
                            _this.highlightValue(res)
                        }
                        _this.isAllChoose(res)
                        _this.handleTreeData(res, true)
                        _this.treeData = res
                        _this.$nextTick(() => {
                        if(_this.firstTargetValue) {
                            let offsetHeight = $("#" + _this.firstTargetValue )[0]?.parentElement?.parentElement?.parentElement?.parentElement?.parentElement.offsetTop
                            if($(".menu-authorization-dialog-main .el-tree")) {
                                $(".menu-authorization-dialog-main .el-tree")[0].scrollTop = offsetHeight
                            }
                        }
                    })
                    })
                    clearTimeout(timer);
                    return;
                });
            }, 500);
        },
        highlightValue(treeData){
            let _this = this;
            treeData.forEach(function(target) {
                // if(target.name.includes(_this.filterText.trim())) {

                    target.backName = target.name
                    target.name = _this.join(target.name, _this.filterText.trim(), target.id)
                    target.name.indexOf(target.id) != '-1' && !_this.firstTargetValue ? _this.firstTargetValue = target.id : ''
                // }
                if(target.children && target.children.length) {
                    _this.highlightValue(target.children)
                }
            })
        },
        chooseRole(item){
            item.checked = !item.checked
        },
        ergodicTree(tree, isChoose){
            let _this = this;
            tree?.forEach(element => {
                !element.isPublic ? element.checked = isChoose : element.checked = false
                if(element.checked) {
                    _this.menuIdList.indexOf(element.id) == '-1' ? _this.menuIdList.push(element.id) : ''
                }else{
                    _this.menuIdList.indexOf(element.id) != '-1' ? _this.menuIdList.splice(_this.menuIdList.indexOf(element.id), 1) : ''
                }
                if(element.children && element.children.length > 0) {
                    element.isIndeterminate = false
                    _this.ergodicTree(element.children, isChoose)
                }
            });
        },
        clickStop(e) {
            if (e.target.tagName === "INPUT") return;
        },
        //全选
        chooseAllMenu() {
            let _this = this;
            _this.ergodicTree(_this.treeData, _this.allChecked)
        },
        isAllChoose(tree) {
            let _this = this;
            let isAllCheck = true;
            function check(treeData) {  
                treeData?.forEach(element => {
                    if(!element.isPublic && !element.checked) {
                        return isAllCheck = false;
                    }
                    if(element.children && element.children.length > 0) {
                        check(element.children)
                    }
                });
            }
            check(tree)
            _this.allChecked = isAllCheck;
        }
    },
    created() {
        this.loadMenuAuthorityTree()
    }
};
</script>
<style lang="less">
.menu-authorization-dialog-main .el-input--small .el-input__icon {
    font-size: 14px;
}
.menu-authorization-dialog-main .el-input__inner {
    font-size: 14px;
}
.menu-authorization-dialog-main .g-tree-solt-con {
    display: flex;
    align-items: center;
    width: 100%;
}
.menu-authorization-dialog-main .g-tree-solt-con p {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    padding-right: 10px;
}
.menu-authorization-dialog-main .tree-box {
    height: calc(100% - 42px);
    overflow: auto;
}
.menu-authorization-dialog-main .el-tree {
    height: 100%;
    overflow: auto;
}
</style>
<style lang="less" scoped>
.menu-authorization-dialog-main {
    width: 100%;
    height: calc(100% - 62px);
    padding-top: 0;
    .g-noData {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: calc(100% - 90px);
        text-align: center;
        color: #909399;
    }
}
.choose-all-check-box-content {
    height: 36px;
    width: 100%;
    display: flex;
    align-items: center;
    padding-left: 24px;
    cursor: pointer;
}
.menu-authorization-dialog-main .import-data-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 40px;
    flex-wrap: wrap;
    margin-bottom: 0px;
    overflow: hidden;
    flex-shrink: 0;
}


.role-list {
    padding-left: 10px;
    margin: 0;
    .list-item {
        width: 100%;
        height: 36px;
        display: flex;
        align-items: center;
        cursor: pointer;
    }
    .role-item-icon {
        margin-right: 10px;
    }
}
.department-tree {
    width: 100%;
    height: 100%; 
    box-sizing: border-box;

    .el-tree .tree-slot-content {
        width: calc(100% - 50px);
    }

}
</style>
