<template>
    <div class="choose-user-dialog-main">
        <div class="import-data-top">
            <div style="display: flex;align-items: center;">
                <span v-show="roleUserList && roleUserList.length" style="margin-right: 40px;">{{$t('cs.common.text.alreadyChoose',{num: roleUserList.length})}}</span>
                <el-link v-show="roleUserList && roleUserList.length" type="primary"><span  @click.stop="clearRoleUserList">{{$t('cs.common.text.clear')}}</span></el-link>
            </div>
            <el-input
                :placeholder="`${$t('cs.common.text.searchPlaceholder')}...`"
                size="small"
                v-model="filterText"
                @keyup.enter.native="searchAllCompany"
                prefix-icon="el-icon-search"
                style="width:240px;"
            ></el-input>
        </div>
        <div class="choose-user-main" >
            <div class="choose-user-main-box">
                <!-- 默认左侧树 -->
                <el-tree ref="tree" v-if="loadTree" :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="currentNodeKey" @node-click="treeClick">
                    <span class="tree-slot" slot-scope="{ data }" :title="data.name">
                    <!-- 资源表 -->
                    <span class="flex-align-center">
                        <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>
                    </span>
                    </span>
                </el-tree>
            </div>
            <div class="choose-user-main-role">
                <div v-show="roleList && roleList.length" class="choose-user-main-role-choose-all">
                    <span>{{$t('cs.common.text.selectAll')}}</span>
                    <el-checkbox @change="chooseAllRole" v-model="allChecked"></el-checkbox>
                </div>
                <div v-show="roleList && roleList.length"  class="choose-user-main-role-box" ref="roleListBox">
                    <ul
                    class="role-list"
                    ref="roleListUL"
                    :class="[haveScroll ? 'g-noScroll' : '']"
                    v-infinite-scroll="loadUser"
                    :infinite-scroll-disabled="infiniteScrollDisabled"
                    :infinite-scroll-distance="infiniteScrollDistance"
                    :infinite-scroll-immediate="infiniteScrollImmediate">
                        <li v-for="i in roleList" :key="i.mangerUserId + 'roleListItem'" @click="chooseRole(i)" class="list-item" >
                            <i class="el-icon-user-solid role-item-icon"></i>
                            <span style="display: inline-block; width: calc(100% - 54px);">
                                {{ i.userName }}
                            </span>
                            <el-checkbox @click.stop.native="clickStop($event)" :disabled="i.disabled" @change="chooseRole(i,true)" v-model="i.checked"></el-checkbox>
                        </li>
                    </ul>
                </div>
                <div class="choose-user-no-data" v-show="!roleList.length && showNoData">
                    {{noDataText}}
                </div>
            </div>
        </div>
        
    </div>
</template>
<script scoped>
// @ is an alias to /src
import  CoreAPI from "../../Common/JS/CoreAPI";
export default {
      props: {
        roleUserList: {
            type: Array,
            default: function () {
                return []
            }
        },
        systemUserId: {
            type: String,
            default: function() {
                return ''
            }
        }
    },
    data() {
        return {
            filterText: '',
            defaultExpandedKeys: [],
            currentNodeKey: '',
            currentNode: {},
            allChecked: false,
            loadTree: false,
            treeData: [],
            roleList: [],
            pageIndex: '1',
            pageSize: '30',
            infiniteScrollDisabled: true,
            infiniteScrollImmediate: false,
            infiniteScrollDistance: 100,
            haveScroll: false,
            noDataText: '无数据',
            showNoData: false
        };
    },
    watch: {
        roleList: function(params) {
            this.treeHaveScroll();
        }
    },
    methods: {
        treeHaveScroll() {
            setTimeout(() => {
                this.$nextTick(() => {
                    this.haveScroll = this.$refs?.roleListBox?.offsetWidth == this.$refs?.roleListUL?.offsetWidth;
                });
            });
        },
        treeClick(e) {
            console.log(e)
            let _this = this;
            _this.currentNodeKey =e.id
            _this.currentNode = e
            _this.pageIndex = '1'
            let postData = {
                "pageNo": _this.pageIndex,
                "pageSize": _this.pageSize
            }
            if(e.parentId && e.id != "100000000000000000") {
                postData.orgId = e.id
            }
            _this.filterText ? postData.userName = _this.filterText : ''
            _this.roleList = []
            _this.infiniteScrollDisabled = false
            _this.getOrgAndUser(postData)
        },
        clearRoleUserList() {
            for(var i = 0; i < this.roleList.length; i++ ) {
                !this.roleList[i].disabled ? this.roleList[i].checked = false :''
            }
            this.allChecked = false
            this.$emit("clearRoleUserListFunc")
        },
        //回车搜索
        searchAllCompany() {
            let _this = this;
            //延迟5s执行搜索
            let timer = setTimeout(() => {
                this.$nextTick(() => {
                    let filterValue = _this.filterText.trim()
                    _this.pageIndex = '1'
                    let postData = {
                        "pageNo": _this.pageIndex,
                        "pageSize": _this.pageSize
                    }
                    _this.roleList = []
                    _this.treeData = []
                    if (filterValue !== "") {
                        postData.userName = filterValue
                    }
                    _this.getOrgAndUser(postData, true)
                    clearTimeout(timer);
                    return;
                });
            }, 500);
        },
        chooseRole(item, isCheckBox){
            let hasTarget = false;
            let _this = this;
            if(item.disabled) return
            !isCheckBox ? item.checked = !item.checked : ''
            _this.roleUserList.forEach(function(target, index) {
                if(item.mangerUserId == target.participationUserId) {
                    hasTarget = true
                    !item.checked ?  _this.roleUserList.splice(index ,1) : ''
                }
            })
            !hasTarget ? _this.roleUserList.push({
                "participationUserId": item.mangerUserId,
                "participationOrgId": _this.currentNodeKey,
                "participationUserName" : item.userName,
                "disabled": item.disabled
            }) : ''
            _this.checkUserListDataState();
        },
        chooseAllRole() {
            let _this = this;
            _this.isChooseAllRole = true;
            if(_this.allChecked) {
                _this.roleList.forEach(function(item) {
                    let hasTarget = false;
                    _this.roleUserList.forEach(function(target, index) {
                        if(item.mangerUserId == target.participationUserId) {
                            hasTarget = true
                            !item.checked ?  _this.roleUserList.splice(index ,1) : ''
                        }
                    })
                    !hasTarget ? _this.roleUserList.push({
                        "participationUserId": item.mangerUserId,
                        "participationOrgId": _this.currentNodeKey,
                        "participationUserName" : item.userName,
                        "disabled": item.disabled
                    }) : ''
                })
            }else{
                this.$emit("clearRoleUserListFunc")
            }
            _this.roleList?.forEach(element => {
                !element.disabled ? element.checked = _this.allChecked : ''
            });
        },
        clickStop(e) {
            if (e.target.tagName === "INPUT") return;
        },
        getOrgAndUser(postData, isNeedReload){
            let _this = this;
            let postValue = {
                "systemId":  CloudServiceCommon.Props.systemId,
                "code": 'get_org_and_user',
                "param": postData
            }
            CoreAPI.getSystemApiData(postValue).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 => {}
                });
                // _this.treeData = res.organizationTreeList
                if( res.userList && res.userList.length > 0 ) {
                    res.userList.forEach(function(item) {
                        item.checked = false;
                        item.disabled = false;
                        if(_this.roleUserList && _this.roleUserList.length > 0) {
                            _this.roleUserList.forEach(function(target) {
                                target.participationUserId == item.mangerUserId ? item.checked = true : ''
                                if(target.isDefault && item.checked) {
                                    target.participationUserId == _this.systemUserId ? item.disabled = true : ''
                                    target.disabled = true
                                }
                            })
                        }
                        _this.roleList.push(item)
                    })
                    res.userList.length < 30 ? _this.infiniteScrollDisabled = true : ''
                }
                _this.checkUserListDataState();
                _this.roleList.length == 0 ? _this.isAllCheck = false : ''
                let filterValue = _this.filterText.trim()
                filterValue ? _this.noDataText = '无结果' : _this.noDataText = '无数据'
                if(!isNeedReload) return 
                if( res.organizationTreeList && res.organizationTreeList.length > 0 ) {
                    res.organizationTreeList.forEach(function(item) {
                        _this.treeData.push(item)
                    })
                }
                _this.currentNodeKey = res.organizationTreeList && res.organizationTreeList.length ? res.organizationTreeList[0].id : ''
                _this.currentNode = res.organizationTreeList && res.organizationTreeList.length ? res.organizationTreeList[0] : ''
                // 判断当前userList内的数据是不是都是选中的  如果都是选中的 那就选中全选
                _this.loadTree = true;
                _this.$nextTick(function(){
                    _this.roleList.length == 0 ? _this.showNoData = true : _this.showNoData = false
                    _this.infiniteScrollDisabled = false
                })
            },function(error) {
                console.log(error)
            })
        },
        checkUserListDataState() {
            let _this = this;
            for(var i = 0; i < _this.roleList.length; i++) {
                if(!_this.roleList[i].checked) {
                    return _this.allChecked = false;
                }
            }
            _this.allChecked = true;
        },
        loadUser(){
            let _this = this;
            _this.pageIndex++
            let postData = {
                "pageNo": _this.pageIndex,
                "pageSize": _this.pageSize
            }
            if(_this.currentNode.parentId && _this.currentNode.id != "100000000000000000") {
                postData.orgId = _this.currentNode.id
            }
            _this.filterText ? postData.userName = _this.filterText : ''
            _this.getOrgAndUser(postData)
        }
    },
    created() {
        let _this = this;
        let postData = {
            "pageNo": _this.pageIndex,
            "pageSize": _this.pageSize
        }
        _this.getOrgAndUser(postData, true)
    }
};
</script>
<style lang="less">
.choose-user-dialog-main .el-input--small .el-input__icon {
    font-size: 14px;
}
.choose-user-dialog-main .el-input__inner {
    font-size: 14px;
}
.choose-user-dialog-main .g-tree-solt-con {
    display: flex;
    align-items: center;
    width: 100%;
}
.choose-user-dialog-main .g-tree-solt-con p {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    padding-right: 10px;
}
.choose-user-dialog-main .tree-box {
    height: calc(100% - 42px);
    overflow: auto;
}
.choose-user-dialog-main .el-tree {
    height: 100%;
    overflow: auto;
}
</style>
<style lang="less" scoped>
.choose-user-dialog-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-user-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;
}
.choose-user-no-data {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
}
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: 12px;
    margin: 0;
    .list-item {
        width: 100%;
        height: 36px;
        display: flex;
        align-items: center;
        cursor: pointer;
    }
    .role-item-icon {
        margin-right: 10px;
        color: #909399;
    }
}

.choose-user-sub-title {
    display: flex;
    width: 100%;
    justify-content: space-between;
    padding: 0 10px;
    box-sizing: border-box;
}
.choose-user-sub-title-single {
    flex-direction: row-reverse;
    padding: 0;
}

.choose-user-main {
    margin-top: 2px;
    height: calc(100% - 42px);
    display: flex; 
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    &-box {
        width: 50%;
        height: 100%; 
        border-right: 1px solid #dcdfe6; 
        box-sizing: border-box;
    }
    &-role {
        width: 50%;
        height: 100%; 
        &-choose-all {
            display: flex;
            align-items: center;
            width: 100%;
            height: 36px;
            justify-content: space-between;
            padding-left: 12px;
            padding-right: 24px;
            box-sizing: border-box;
        }
        &-box {
            width: 100%;
            height: calc(100% - 36px);
            overflow: auto;
        }
    }
}

</style>
