<template>
    <div class="data-authorization-dialog-main">
        <el-tabs v-model="topTabsConfig.active" type="card" @tab-click="handleClick">
            <el-tab-pane v-for="(item, index) in topTabsConfig.data" :key="index" :label="item.name" :name="item.id"></el-tab-pane>
        </el-tabs>
        <div class="top-tab-description" v-if="topTabsConfig.activeNode && topTabsConfig.activeNode.description">
            {{topTabsConfig.activeNode.description}}
        </div>
        <el-table
            ref="multipleTable"
            v-if="isShowTable"
            :data="tableData"
            style="width: 100%;margin-bottom: 20px;"
            :height="topTabsConfig.activeNode && topTabsConfig.activeNode.description ? 'calc(100% - 82px)' : 'calc(100% - 56px)'"
            row-key="id"
            border
            default-expand-all
            :header-cell-style="{background: '#fafafa',color: '#626066'}"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column
                prop="name"
                width="370"
                min-width="370"
                :show-overflow-tooltip="true"
                label="日期">
                <template #header >
                    <el-input
                        :placeholder="`${$t('cs.common.text.searchPlaceholder')}...`"
                        size="small"
                        prefix-icon="el-icon-search"
                        @keyup.enter.native="searchAllCompany"
                        v-model="filterText">
                    </el-input>
                </template>
                <template #default="scope" >
                    <i style="margin-right: 3px;" :class="iconList[scope.row.type]"></i>
                    <div style="    flex: 1 1 auto;    max-width: 100%;    min-width: 100px;">
                        <span style="cursor: default;display: block;height: 32px;line-height: 32px;overflow: hidden;padding-left: 0px;text-overflow: ellipsis;white-space: nowrap;" v-html="scope.row.name"></span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                prop="name"
                min-width="471"
                label="姓名">
                <template #header >
                    <div style="display: flex;width: 100%;justify-content: space-around;">
                        <div style="width:80px; flex-shrink: 0;" v-for="(checkboxItem, checkboxIndex) in headerData" :key="checkboxIndex + 'queryConditionAreaItem'">
                            <el-checkbox @change="chooseAllRole(checkboxItem.key)" v-model="checkboxItem.value">{{checkboxItem.name}}</el-checkbox>
                        </div>
                    </div>
                </template>
                <template #default="scope" >
                    <div style="display: flex;width: 100%;justify-content: space-around;">
                        <div style="width:80px; flex-shrink: 0;" v-for="(checkboxItem, checkboxIndex) in config" :key="scope.row.id + checkboxIndex + 'queryConditionAreaItems'">
                            <el-checkbox v-if="isShowCheckBox(scope.row, checkboxItem)" @change="chooseRole(scope.row, scope.row.funcAuthorityList, checkboxItem.code)" v-model="scope.row.funcAuthorityList[checkboxItem.code]">{{checkboxItem.name}}</el-checkbox>
                        </div>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>
<script scoped>
// @ is an alias to /src
import  CoreAPI from "../../Common/JS/CoreAPI";
export default {
    props: {
        authorityDataCategoryList: {
            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 {
            topTabsConfig: {
                data: [],
                active: ''
            },
            filterText: '',
            defaultExpandedKeys: [],
            currentNode: '',
            allChecked: false,
            isShowTable: false,
            bizDataType: '',
            headerData: [],
            config: [],
            tableData: [],
            backData: {},
            iconList:[],
            loading: false
        };
    },
    watch: {
        
    },
    methods: {
        getDataAuthorityTree: function() {
            let _this = this;
            let postData = {
                "systemId": CloudServiceCommon.Props.systemId,
                "authorityDataCategoryCode": _this.topTabsConfig.activeNode.code,
                "authorityType": _this.authorityType,
                "roleId": _this.roleId ? _this.roleId : null,
                "userId": _this.userId ? _this.userId : null,
                "orgId": _this.orgId ? _this.orgId : null
            }
            CoreAPI.getDataAuthorityTree(postData).then(function (res) {
                console.log(res)
                let list = [];
                let config = {}
                let alreadyTarget = false;
                let targetIndex = null
                _this.authorityDataCategoryList.forEach(function (item, index) {
                    if(item.authorityDataCategoryCode == _this.topTabsConfig.activeNode.code) {
                        alreadyTarget = true;
                        targetIndex = index
                    }
                })
                if (!alreadyTarget) {
                    _this.authorityDataCategoryList.push({
                        "authorityDataCategoryCode": _this.topTabsConfig.activeNode.code,
                        "dataAuthorityItemChooseConfig": {
                            configMap:{},
                            nowChooseMap:{}
                        },
                        "dataAuthorityItemList": []
                    })
                    targetIndex = _this.authorityDataCategoryList.length - 1
                }
                list = _this.authorityDataCategoryList[targetIndex].dataAuthorityItemList
                config = _this.authorityDataCategoryList[targetIndex].dataAuthorityItemChooseConfig
                _this.topTabsConfig.activeNode.func.forEach(function(targets) {
                    config.configMap[targets.code] = 0;
                    config.nowChooseMap[targets.code] = 0;
                })
                _this.initTableData(res, list, config)
                _this.dataAuthorityItemChooseConfig = config
                _this.isAllChoose(res)
                _this.backData[_this.topTabsConfig.activeNode.id] = res
                _this.tableData = res
                _this.isShowTable = true;
            })

        },
        getAuthorityDataCategoryBySystemId: function() {
            let _this = this;
            CoreAPI.getAuthorityDataCategoryBySystemId(CloudServiceCommon.Props.systemId).then(function (res) {
                if(res && res.length) {
                    _this.topTabsConfig.data = res
                    _this.topTabsConfig.active = res[0].id
                    _this.topTabsConfig.activeNode = res[0]
                    _this.initTreeTable(true)
                }
            })
        },
        initTreeTable: function(isNeed) {
            let _this = this;
            _this.bizDataType = _this.topTabsConfig.activeNode.bizDataType.sort(_this.compare("bizDataType"))
            _this.iconList = []
            _this.bizDataType.forEach(function(item) {
                _this.iconList.push(item.icon)
            })
            _this.config = _this.topTabsConfig.activeNode.func.sort(_this.compare("order"))
            _this.config.forEach(function(target) {
                _this.headerData.push({
                    key: target.code,
                    value: false,
                    name: target.name
                })
            })
            isNeed ? _this.getDataAuthorityTree() : _this.initDataAuthorityConfig()
        },
        initDataAuthorityConfig: function() {
            let _this = this;
            let targetIndex = null
            _this.authorityDataCategoryList.forEach(function (item, index) {
                if(item.authorityDataCategoryCode == _this.topTabsConfig.activeNode.code) {
                    targetIndex = index
                }
            })
            _this.dataAuthorityItemChooseConfig = _this.authorityDataCategoryList[targetIndex].dataAuthorityItemChooseConfig
            _this.isAllChoose(_this.tableData)
        },
        compare: function(property) {
            return function (a, b) {
                var value1 = a[property];
                var value2 = b[property];
                return value1 - value2;
            }
        },
        isShowCheckBox: function(row, item){
            let _this = this;
            let value = false
            _this.bizDataType.forEach(element => {
                if(element.bizDataType == row.type) {
                    value = element.funcCode && element.funcCode.indexOf(item.code) != '-1' ? true : false
                } 
            });
            return value
        },
        handleClick(tabs, e) {
            let _this = this;
            _this.isShowTable = false
            let oldActive = _this.topTabsConfig.activeNode.id
            _this.topTabsConfig.data.forEach(function(target) {
                if(target.id == tabs.name) {
                    _this.topTabsConfig.active = target.id
                    _this.topTabsConfig.activeNode = target
                }
            })
            _this.headerData = []
            oldActive != _this.topTabsConfig.active ? _this.filterText = '' : ''
            if(!_this.backData[_this.topTabsConfig.active]) {
                _this.initTreeTable(true)
            }else{
                _this.initTreeTable()
                oldActive != _this.topTabsConfig.active && _this.reductionHighlightValue(_this.backData[tabs.name])
                _this.tableData = _this.backData[tabs.name]
                _this.isShowTable = true
                _this.$nextTick(() =>{
                    if(oldActive != _this.topTabsConfig.active) {
                        _this.$refs.multipleTable ? _this.$refs.multipleTable.bodyWrapper.scrollTop = 0 : ''
                    }
                })
            }
        },
        //回车搜索
        searchAllCompany() {
            let _this = this;
            //延迟5s执行搜索
            let timer = setTimeout(() => {
                this.$nextTick(() => {
                    let filterValue = _this.filterText.trim()
                    let res = _this.backData[_this.topTabsConfig.activeNode.id]
                    _this.reductionHighlightValue(res)
                    if (filterValue !== "") {
                        _this.firstTargetValue = null
                        _this.highlightValue(res)
                    }
                    _this.treeData = res
                    clearTimeout(timer);
                    _this.$nextTick(() => {
                        if(_this.firstTargetValue) {
                            let offsetHeight = $("#" + _this.firstTargetValue )[0]?.parentElement?.parentElement?.parentElement?.parentElement?.parentElement.offsetTop
                            if($(".data-authorization-dialog-main") && $(".data-authorization-dialog-main").find(".el-table__body-wrapper")[0]) {
                                $(".data-authorization-dialog-main").find(".el-table__body-wrapper")[0].scrollTop = offsetHeight
                            }
                        }
                    })
                    return;
                });
            }, 500);
        },
        highlightValue(treeData){
            let _this = this;
            treeData.forEach(function(target) {
                // if(target.name.includes(_this.filterText.trim())) {
                    target.backName = target.name.indexOf("</span>") == '-1' ? target.name : target.backName
                    target.name = _this.join(target.name, _this.filterText.trim(), target.id)
                    if(target.name.indexOf("</span>") != "-1" && !_this.firstTargetValue) {
                        _this.firstTargetValue = target.id
                    }
                // }
                if(target.children && target.children.length) {
                    _this.highlightValue(target.children)
                }
            })
        },
        reductionHighlightValue(treeData){
            let _this = this;
            treeData.forEach(function(target) {
                if(target.backName) {
                    target.name = target.backName
                }
                if(target.children && target.children.length) {
                    _this.reductionHighlightValue(target.children)
                }
            })
        },
        // 拼接
        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)
        },
        chooseRole(row, item, code){
            let _this = this;
            _this.handleBackData(row, code, item[code])
            _this.$nextTick(function() {
                _this.isAllChoose(_this.tableData)
            })
        },
        chooseAllRole(key) {
            let _this = this;
            let checkd = false;
            const loading = _this.$loading({
                fullscreen: true,
                lock: true,
                background: 'rgba(0, 0, 0, 0.1)'
            });
            _this.headerData.forEach(function (target) {
                target.key == key ? checkd = target.value : ''
            })
            _this.isChooseAllRole = true;
            _this.ergodicTree(_this.tableData, checkd, key)
            _this.$nextTick(function(){
                setTimeout(function() {
                    loading.close()
                },1000)
                _this.isAllChoose(_this.tableData)
            })
        },
        ergodicTree(tree, isChoose, key){
            let _this = this;
            tree?.forEach(element => {
                // if(element.funcAuthorityList.hasOwnProperty.call(key)) {
                if(Object.prototype.hasOwnProperty.call(element.funcAuthorityList, key) && element.funcAuthorityList[key] != isChoose) {
                    element.funcAuthorityList[key] = isChoose
                    _this.handleBackData(element, key, isChoose, true)
                }
                if(element.children && element.children.length > 0) {
                    _this.ergodicTree(element.children, isChoose, key)
                }
            });
        },
        handleBackData(element, key, isChoose, isAllChoose) {
            let hasTarget = false;
            let _this = this;
            let needSplice = false;
            let spliceIndex = 0;
            let list = [];
            let alreadyTarget = false;
            let targetIndex = null;
            let dataTargetIndex = null;
            let parentNodeIndex = null;
            let parentNode = element.parentId ? _this.findParentNode(element.parentId) : false
            let childrenList = element.children
            let hasParentNode = false;
            let childrenHasCheck = false;
            let parentNodeChildrenHasCheck = false;
            _this.authorityDataCategoryList.forEach(function (item, index) {
                if(item.authorityDataCategoryCode == _this.topTabsConfig.activeNode.code) {
                    alreadyTarget = true;
                    targetIndex = index
                }
            })
            if (!alreadyTarget) {
                 _this.authorityDataCategoryList.push({
                    "authorityDataCategoryCode": _this.topTabsConfig.activeNode.code,
                    "dataAuthorityItemList": []
                })
                targetIndex = _this.authorityDataCategoryList.length - 1
            }
            list = _this.authorityDataCategoryList[targetIndex].dataAuthorityItemList
            list.forEach(function (target, index) {
                if(parentNode && target.authItemId == parentNode.id) {
                    hasParentNode = true;
                    parentNodeIndex = index
                }
                if(target.authItemId == element.id) {
                    hasTarget = true;
                    dataTargetIndex = index;
                    element.funcAuthorityList[key] ? target.funcCodeList.indexOf(key) == '-1' ? target.funcCodeList.push(key) : '' : target.funcCodeList.indexOf(key) != '-1' ? target.funcCodeList.splice(target.funcCodeList.indexOf(key), 1) : ''
                    if( target.funcCodeList.length == 0 ) {
                        spliceIndex = index;
                        needSplice = true;
                    }
                }
            })
            // 判断当前节点是否有子  如果有子  看看子有没有权限 如果有 不能删
            if(childrenList && childrenList.length) {
                childrenList.forEach(function(targett) {
                    if(targett.funcAuthorityList && !childrenHasCheck) {
                        for(var i in targett.funcAuthorityList) {
                            if(isAllChoose) {
                                i != key && targett.funcAuthorityList[i] ? childrenHasCheck = true : ''
                            }else{
                                targett.funcAuthorityList[i] ? childrenHasCheck = true : ''
                            }
                        }
                    }
                })
            }
            // 判断当前节点的父节点 看看子有没有权限 如果有 不能删
            if(parentNode && parentNode.children.length) {
                parentNode.children.forEach(function(targett) {
                    if(targett.funcAuthorityList && !parentNodeChildrenHasCheck) {
                        for(var i in targett.funcAuthorityList) {
                            if(isAllChoose) {
                                i != key && targett.funcAuthorityList[i] ? parentNodeChildrenHasCheck = true : ''
                            }else{
                                targett.funcAuthorityList[i] ? parentNodeChildrenHasCheck = true : ''
                            }
                        }
                    }
                })
            }
            needSplice && !childrenHasCheck ? list.splice(spliceIndex, 1) : needSplice && list[spliceIndex] && childrenHasCheck ? list[spliceIndex].funcCodeList = [] : ''
            needSplice && hasParentNode && list[parentNodeIndex] && !list[parentNodeIndex].funcCodeList.length && !parentNodeChildrenHasCheck ? list.splice(parentNodeIndex, 1) : ''
            isChoose ? _this.dataAuthorityItemChooseConfig.nowChooseMap[key]++ : _this.dataAuthorityItemChooseConfig.nowChooseMap[key]--
            hasTarget && !needSplice && element.linkageConfig && isChoose && _this.linkageConfigFunc({element, key, isChoose, dataTargetIndex, list})
            if(!hasTarget) {
                isChoose && list.push({
                    "authItemId": element.id,
                    "funcCodeList": [
                        key
                    ]
                })
                isChoose && parentNode && !hasParentNode && list.push({
                    "authItemId": parentNode.id,
                    "funcCodeList": []
                })
            }
        },
        findParentNode(parentId) {
            let _this = this;
            // 是否找到父节点
            let parentNode = false;
            if(!parentId) return false
            let findFunc = function (list, parentId) {
                list.forEach(function(target) {
                    if(target.id == parentId) {
                        parentNode = target
                    }
                    if(!parentNode && target.children && target.children.length) {
                        findFunc(target.children, parentId)
                    }
                })
            }
            findFunc(_this.tableData, parentId)
            return parentNode
        },
        linkageConfigFunc(obj) {
            let _this = this;
            let {element, key, isChoose, dataTargetIndex, list} = {...obj}
            let linkageConfig = null
            linkageConfig = element.linkageConfig
            if(typeof element.linkageConfig == 'string') {
                linkageConfig = JSON.parse(element.linkageConfig)
            }
            linkageConfig.forEach(function(target) {
                if(target.code == key && target.linkage_type == 0) {
                    target.linkage_function_code.forEach(function(items) {
                        let targetIndex = list[dataTargetIndex].funcCodeList.indexOf(items)
                        targetIndex != '-1' ? list[dataTargetIndex].funcCodeList.splice(targetIndex, 1) : ''
                        targetIndex != '-1' ? element.funcAuthorityList[items] = false : ''
                        targetIndex != '-1' ? _this.dataAuthorityItemChooseConfig.nowChooseMap[items]-- : ''
                    })
                }
            })
            
        },
        initTableData(tree, targetList, targetConfig){
            let _this = this;
            tree.forEach(function(item) {
                let funcCodeList = []
                _this.topTabsConfig.activeNode.func.forEach(function(target) {
                    if(item.funcAuthorityList && item.funcAuthorityList[target.code]) {
                       funcCodeList.push(target.code)
                       targetConfig.nowChooseMap[target.code]++ 
                       // 进了true的判断了  就肯定不会走下面的三目  所以要加上
                       targetConfig.configMap[target.code]++
                    } 
                    item.funcAuthorityList && !item.funcAuthorityList[target.code] && item.funcAuthorityList[target.code] != undefined ? targetConfig.configMap[target.code]++ : ''
                })
                _this.bizDataType && _this.bizDataType.forEach(function(target) {
                    target.bizDataType == item.type && target.linkageConfig ? item.linkageConfig = JSON.parse(target.linkageConfig) : ''
                })
                let hasTarget = false;
                targetList.forEach(function(value) {
                    item.parentId && value.authItemId == item.parentId ? hasTarget = true : ""                   
                })
                if(funcCodeList.length > 0) {
                    !hasTarget && item.parentId && targetList.push({
                        "authItemId": item.parentId,
                        "funcCodeList": []
                    })
                    targetList.push({
                        "authItemId": item.id,
                        "funcCodeList": funcCodeList
                    })
                }
                if(item.children && item.children.length) {
                    _this.initTableData(item.children, targetList, targetConfig)
                }
            })
        },
        isAllChoose(tree, targetList){
            let _this = this;
            // _this.dataAuthorityItemChooseConfig = config
            //     "dataAuthorityItemChooseConfig": {
            //                 configMap:{},
            //                 nowChooseMap:{}
            //             },
            _this.headerData.forEach(function(target) {
                if(_this.dataAuthorityItemChooseConfig.configMap[target.key] == _this.dataAuthorityItemChooseConfig.nowChooseMap[target.key] && _this.dataAuthorityItemChooseConfig.nowChooseMap[target.key] != 0) {
                    target.value = true
                }else{
                    target.value = false
                }
            })
            // // 备份
            // let headerData = JSON.parse(JSON.stringify(_this.headerData))
            // // 特殊处理 如果只有根目录 直接return把
            // if(!tree[0].children || (tree[0].children && !tree[0].children.length)) {
            //     _this.headerData.forEach((element, index) => {
            //         if(Object.prototype.hasOwnProperty.call(tree[0].funcAuthorityList, element.key) && !tree[0].funcAuthorityList[element.key]) {
            //             headerData[index].isAllCheck = false;
            //         }else if(!Object.prototype.hasOwnProperty.call(tree[0].funcAuthorityList, element.key)) {
            //             headerData[index].isAllCheck = false;
            //         }
            //     });
            //     headerData.forEach(function(target, index) {
            //         if(!Object.prototype.hasOwnProperty.call(target, 'isAllCheck')){
            //             _this.headerData[index].value = true;
            //         }
            //     })
            //     return 
            // }
            // function check(tree) {
            //     tree.forEach(function(item) {
            //         _this.headerData.forEach((element, index) => {
            //             if(Object.prototype.hasOwnProperty.call(item.funcAuthorityList, element.key) && !item.funcAuthorityList[element.key]) {
            //                 headerData[index].isAllCheck = false;
            //             }
            //         });
            //         if(item.children && item.children.length) {
            //             check(item.children)
            //         }
            //     })
            // }
            // check(tree)
            // headerData.forEach(function(target, index) {
            //     if(!Object.prototype.hasOwnProperty.call(target, 'isAllCheck')){
            //         _this.headerData[index].value = true;
            //     }else{
            //         _this.headerData[index].value = target.isAllCheck;
            //     }
            // })
        },
        clickStop(e) {
            if (e.target.tagName === "INPUT") return;
        }
    },
    created() {
        this.getAuthorityDataCategoryBySystemId()
    }
};
</script>
<style lang="less">
.data-authorization-dialog-main .el-input--small .el-input__icon {
    font-size: 14px;
}
.data-authorization-dialog-main .el-input__inner {
    font-size: 14px;
}
.data-authorization-dialog-main .el-table__placeholder {
    flex-shrink: 0;
}
.data-authorization-dialog-main .g-tree-solt-con {
    display: flex;
    align-items: center;
    width: 100%;
}
.data-authorization-dialog-main .g-tree-solt-con p {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    padding-right: 10px;
}
.data-authorization-dialog-main .tree-box {
    height: calc(100% - 42px);
    overflow: auto;
}
.data-authorization-dialog-main .el-tree {
    height: 100%;
    overflow: auto;
}
</style>
<style lang="less" scoped>
.data-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;
    }
    .top-tab-description {
        margin-bottom: 10px;
        color: #909399;
        font-size: 12px;
    }
}
.data-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;
}
html .el-dialog__body .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content,
body .el-dialog__body .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background: #f5f7fa !important;
}

.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%; 
    border-right: 1px solid #dcdfe6; 
    box-sizing: border-box;

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

}
</style>
