<template>
    <div class="choose-departmentdialog-main">
        <div class="import-data-top">
            <div style="display: flex;align-items: center;">
                <span v-show="departmentList && departmentList.length" style="margin-right: 40px;">{{$t('cs.common.text.alreadyChoose',{num: departmentList.length})}}</span>
                <el-link v-show="departmentList && departmentList.length" type="primary"><span  @click.stop="clearDepartment">{{$t('cs.common.text.clear')}}</span></el-link>
            </div>
        </div>
        <div style="margin-top: 2px;height: calc(100% - 80px);display: flex; border: 1px solid #dcdfe6;box-sizing: border-box;flex-direction: column;" >
            <div class="choose-main-role-choose-all">
                <span>{{$t('cs.common.text.selectAll')}}</span>
                <el-checkbox @change="chooseAllDepartment(treeData)" v-model="allChecked"></el-checkbox>
            </div>
            <div class="department-tree" ref="departmentListBox">
                <!-- 默认左侧树 -->
                <el-tree ref="departmentListTree" :class="[haveScroll ? 'g-noScroll' : '']"  :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" @node-expand="treeHaveScroll1" @node-collapse="treeHaveScroll1" :current-node-key="currentNode" @node-click="treeClick">
                    <span class="tree-slot" slot-scope="{ data }" :title="data.name">
                    <!-- 资源表 -->
                    <span class="flex-align-center" @click.stop="chooseDepartment(data)">
                        <span class="tree-slot-content">
                        <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">{{ data.name }}</span>
                        </span>
                        <el-checkbox @click.stop.native="clickStop($event)" @change="chooseDepartment(data,true)" v-model="data.checked"></el-checkbox>
                    </span>
                    </span>
                </el-tree>
            </div>
        </div>
        
    </div>
</template>
<script scoped>
// @ is an alias to /src
import  CoreAPI from "../../Common/JS/CoreAPI";
export default {
    props: {
        departmentList: {
            type: Array,
            default: function () {
                return []
            }
        }
    },
    data() {
        return {
            filterText: '',
            defaultExpandedKeys: [],
            currentNode: '',
            allChecked: false,
            haveScroll: false,
            treeData: []
        };
    },
    watch: {
        treeData: function(params) {
            this.treeHaveScroll();
        }
    },
    methods: {
        treeHaveScroll() {
            setTimeout(() => {
                this.$nextTick(() => {
                    this.haveScroll = this.$refs?.departmentListBox?.offsetWidth == this.$refs?.departmentListTree?.$el?.offsetWidth;
                });
            });
        },
        treeHaveScroll1() {
            setTimeout(() => {
                this.$nextTick(() => {
                    this.haveScroll = this.$refs?.departmentListBox?.offsetWidth == this.$refs?.departmentListTree?.$el?.offsetWidth;
                    console.log(this.haveScroll)
                });
            }, 300);
        },
        getOrganizationTree(isNeedReload){
            let _this = this;
            let postData = {
                "systemId":  CloudServiceCommon.Props.systemId,
                "code": 'get_organization_tree',
                "param": {
                    "isLazyLoading":0,
                    "id":null
                }
            }
            CoreAPI.getSystemApiData(postData).then((result) => {
                let res = JSON.parse(result).obj
                let code = JSON.parse(result).code
                if(code == '429') return _this.$alert(_this.$t("cs.common.errorCode.429"), _this.$t("cs.common.text.tips"), {
                    confirmButtonText: _this.$t("cs.common.button.ok"),
                    type: 'warning',
                    callback: action => {}
                });
                if( res && res.length > 0 ) {
                    _this.ergodicTree(res)
                    _this.isAllCheck(res)
                }
                _this.treeData = res
                _this.loadTree = true;
            },function(error) {
                console.log(error)
            })
        },
        treeClick(data) {
            let _this = this;
            data.checked = !data.checked
        },
        //回车搜索
        searchAllCompany() {
            let this_ = this;
            let lazy = false;
            if (this_.filterText.trim()) {
                lazy = false;
            } else {
                lazy = true;
            }
            //延迟5s执行搜索
            let timer = setTimeout(() => {
                this_.treeTrigger = false;
                this.$nextTick(() => {
                    if (lazy && this_.lazy && this_.filterText.trim() == "") {
                        this_.initTreeOpenNode([]);
                        this_.treeConfig.lazy = true;
                        this_.treeTrigger = true;
                        clearTimeout(timer);
                        return;
                    }

                    this_.$parent.$parent.searchAllTree(this_.filterText.trim()).then(res => {
                        let result = res.some(item => {
                            if(item.children && item.children.length > 0){
                                return true;
                            }
                        });
                        if (result) {
                            ({ ...this_.treeConfig } = {
                                treeData: res,
                                radio: this_.radio,
                                search: this_.search,
                                lazy: false,
                                clickColCheck: true,
                                defaultExpandAll: false,
                                preview: false,
                                showCheckBox: this_.showCheckBox
                            });
                            this_.initData(res, this_.selectData);
                            if (this_.filterText.trim() != "") {
                                this_.initTreeOpenNode(res);
                            } else {
                                this_.initTreeOpenNode(this_.selectData);
                            }
                            this_.treeTrigger = true;
                            this.isNodata = false;
                        } else {
                            this_.selectData = [];
                            this.isNodata = true;
                        }
                        clearTimeout(timer);
                    });
                });
            }, 500);
        },
        //判断是否全选
        isAllCheck(tree) {
            let this_ = this;
            function isAllCheckFn(tree) {
                for (let i = 0; i < tree.length; i++) {
                    const element = tree[i];
                    if (!element.checked) {
                        this_.allChecked = false;
                        return;
                    }
                    if (element.children && element.children.length > 0) {
                        isAllCheckFn(element.children);
                    }
                }
            }
            this_.allChecked = true;
            isAllCheckFn(tree);
        },
        chooseDepartment(item, isCheckBox){
            let hasTarget = false;
            let _this = this;
            !isCheckBox ? item.checked = !item.checked : ''
            _this.departmentList.forEach(function(target, index) {
                if(item.id == target.id) {
                    hasTarget = true
                    !item.checked ?  _this.departmentList.splice(index ,1) : ''
                }
            })
            !hasTarget ? _this.departmentList.push({
                "id": item.id,
                "name": item.name
            }) : ''
            _this.isAllCheck(_this.treeData)
        },
        chooseAllDepartment(tree) {
            let _this = this;
            _this.isChooseAllRole = true;
            if(_this.allChecked) {
                tree.forEach(function(item) {
                    let hasTarget = false;
                    _this.departmentList.forEach(function(target, index) {
                        if(item.id == target.id) {
                            hasTarget = true
                            !item.checked ?  _this.departmentList.splice(index ,1) : ''
                        }
                    })
                    !hasTarget ? _this.departmentList.push({
                        "id": item.id,
                        "name": item.name
                    }) : ''
                    item.checked = _this.allChecked
                    if(item.children && item.children.length) {
                        _this.chooseAllDepartment(item.children)
                    }
                })
            }else{
                _this.$emit("clearDepartmentListFunc")
                _this.cancelTreeDataStateFunc(tree)
            }
        },
        cancelTreeDataStateFunc(tree) {
            let _this = this;
            tree?.forEach(element => {
                element.checked = _this.allChecked
                if(element.children && element.children.length) {
                    _this.cancelTreeDataStateFunc(element.children)
                }
            });
        },
        clearDepartment() {
            this.clearTreeState(this.treeData)
            this.allChecked = false
            this.$emit("clearDepartmentListFunc")
        },
        clearTreeState(treeData){
            for(var i = 0; i < treeData.length; i++ ) {
                treeData[i].checked = false
                if(treeData[i].children && treeData[i].children.length) {
                    this.clearTreeState(treeData[i].children)
                }
            }
        },
        ergodicTree(tree){
            let _this = this;
            tree?.forEach(element => {
                element.checked = false;
                if(_this.departmentList && _this.departmentList.length > 0) {
                    _this.departmentList.forEach(function(target) {
                        target.id == element.id ? element.checked = true : ''
                    })
                }
                if(element.children && element.children.length > 0) {
                    _this.ergodicTree(element.children)
                }
            });
        },
        clickStop(e) {
            if (e.target.tagName === "INPUT") return;
        }
    },
    created() {
        let _this = this;
        _this.getOrganizationTree()
    }
};
</script>
<style lang="less">
.choose-departmentdialog-main .el-input--small .el-input__icon {
    font-size: 14px;
}
.choose-departmentdialog-main .el-input__inner {
    font-size: 14px;
}
.choose-departmentdialog-main .g-tree-solt-con {
    display: flex;
    align-items: center;
    width: 100%;
}
.choose-departmentdialog-main .g-tree-solt-con p {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    padding-right: 10px;
}
.choose-departmentdialog-main .tree-box {
    height: calc(100% - 42px);
    overflow: auto;
}
.choose-departmentdialog-main .el-tree {
    height: calc(100% - 44px);
    overflow: initial;
}
</style>
<style lang="less" scoped>
.choose-departmentdialog-main {
    width: 100%;
    height: 100%;
    padding-top: 0;
    .g-noData {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: calc(100% - 90px);
        text-align: center;
        color: #909399;
    }
    .g-noScroll {
        padding-right: 8px;
    }
}
.choose-departmentdialog-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%; 
    box-sizing: border-box;
    overflow: auto;

    .el-tree .tree-slot-content {
        width: calc(100% - 30px);
    }
}
.choose-main-role-choose-all {
    display: flex;
    align-items: center;
    width: 100%;
    height: 36px;
    justify-content: space-between;
    padding-left: 16px;
    padding-right: 24px;
    box-sizing: border-box;
    flex-shrink: 0;
}
</style>
