<template>
    <div class="rolesManage-main roles-manage">
        <div class="rolesManage-mainLeft">
            <div
                class="roles-tree-header"
                style="border-bottom: 1px solid #d5d5d5;position: relative;overflow: hidden;"
            >
                <div style="margin-top:10px;margin-left:20px; font-size:16px;float:left;">二级角色列表</div>
                <el-button
                    size="small"
                    type="primary"
                    @click="operateRole('add', {})"
                    style="float: right;margin-right: 20px;margin-top: 7px;"
                    v-if="isManagerRole !== ''"
                >新增1角色</el-button>
            </div>
            <div style="width: 100%;padding: 20px 20px 0 20px;position: relative;">
                <el-table
                    ref="rolesTree"
                    v-loading="rolesTree.loading"
                    @filter-change="filterRoleChange"
                    @row-click="nodeClick"
                    @current-change="handleCurrentChange"
                    border
                    :height="treeHeight"
                    highlight-current-row
                    @selection-change="handleSelectionChange"
                    :data="rolesTree.tree"
                >
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="roleName"
                        label="角色名称"
                        align="center"
                        :filter-method="filterColumn"
                    >
                    </el-table-column>
                </el-table>
            </div>
        </div>
        
        <!-- 新增机构弹窗-->
        <el-dialog
            :title="dialogOrgTree.title"
            :visible.sync="dialogOrgTree.show"
            width="600px"
            center
        >
            <div style="margin:20px;">
                <div style="height:400px;overflow-y:auto;">
                    <el-tree
                        ref="dialogOrgTree"
                        class="orgTree"
                        style="margin-top:20px; overflow-x:hidden;"
                        :data="dialogOrgTree.tree"
                        :props="dialogOrgTree.defaultProps"
                        node-key="orgId"
                        show-checkbox
                        :expand-on-click-node="true"
                            >
                    </el-tree>
                </div>

                <el-button
                    type="primary"
                    @click="addOrgToRole"
                    size="small"
                    style="float:right;"
                >确 定</el-button>
            </div>
        </el-dialog>        

        <!-- 授权弹窗 -->
        <el-dialog
            :title="dialogAuthTree.title"
            :visible.sync="dialogAuthTree.show"
            width="600px"
            center
        >
            <div style="margin:20px;">
                <div style="height:400px;overflow-y:auto;">
                    <el-tree
                        ref="dialogAuthMenuTree"
                        class="orgTree"
                        style="margin-top:20px; overflow-x:hidden;"
                        :data="dialogAuthTree.tree"
                        :props="menuTree.defaultProps"
                        node-key="menuId"
                        show-checkbox
                        :default-expanded-keys="menuTree.expandedKeys"
                        :expand-on-click-node="true"
                            >
                    </el-tree>
                </div>

                <el-button
                    type="primary"
                    @click="beginBatchAuth"
                    size="small"
                    style="float:right;"
                >确 定</el-button>
            </div>
        </el-dialog>

        <!-- 新增角色弹窗 -->
        <el-dialog
            :title="dialogRoles.title"
            :visible.sync="dialogRoles.show"
            width="400px"
            center
        >
            <div style="text-align:center;margin:20px 0 40px 0;">
                <el-form
                    ref="dialogRoles"
                    :model="dialogRoles.form"
                    :rules="dialogRoles.ruleValidate"
                    label-width="90px"
                >
                    <el-form-item
                        label="id"
                        prop="id"
                        v-show="false"
                    >
                        <el-input
                            v-model="dialogRoles.form.id"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="父级角色"
                        prop="pId"
                        v-show="true"
                    >
                        <el-select v-model="dialogRoles.form.pId" size="small" filterable clearable placeholder="请选择角色">
                            <el-option
                            v-for="item in currentAccountManagerRoles"
                            :key="item.roleId"
                            :label="item.roleName"
                            :value="item.roleId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="角色编码"
                        prop="roleCode"
                    >
                        <el-input
                            v-model="dialogRoles.form.roleCode"
                            :disabled="dialogRoles.operate === 'add' ? false : true"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="角色ID"
                        v-show="dialogStatus === 'edit'"
                        prop="roleId"
                    >
                        <el-input
                            v-model="dialogRoles.form.roleId"
                            :disabled="true"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="角色名称"
                        prop="roleName"
                    >
                        <el-input
                            v-model="dialogRoles.form.roleName"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="角色级别"
                        prop="rank"
                        v-show="false"
                    >
                        <el-input
                            v-model="dialogRoles.form.rank"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>

                    <!--
                    <el-form-item
                        label="分组"
                        prop="remark"
                    >
                        <el-select
                            v-model="dialogRoles.form.remark"
                            placeholder="请选择分组"
                            size="small"
                        >
                            <el-option
                                v-for="(item,index) in grouping"
                                :key="index"
                                :label="item.dictName"
                                :value="item.dictName"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>-->
                </el-form>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    @click="dialogRoles.show = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    :loading="dialogRoles.loading"
                    type="primary"
                    @click="submitRole"
                    size="small"
                >保存</el-button>
            </span>
        </el-dialog>

        <div class="rolesManage-mainMiddle">
            <div class="save">
                <el-button
                    type="primary"
                    size="mini"
                    :loading="saveLoading"
                    @click="openOrgWin"
                >增加管理机构</el-button>
            </div>
            <el-tabs class="right-tabs">
                <el-tab-pane label="机构列表">
                    <!-- 机构权限 -->
                    <div style="margin:20px;">
                        <el-tree
                            ref="orgTree"
                            class="orgTree"
                            style="margin-top:20px; overflow-x:hidden"
                            :data="orgTree.tree"
                            :props="orgTree.defaultProps"
                            :style="{height: treeHeight + 'px'}"
                            node-key="orgId"
                            show-checkbox
                            default-expand-all
                            :expand-on-click-node="true"
                            @check-change="checkChageTree"
                            @node-click="getOrgMenu"
                        >
                        </el-tree>
                    </div>
                    <!-- 机构权限 -->
                </el-tab-pane>
            </el-tabs>
        </div>

        <div class="rolesManage-mainRight">
          <div v-show="hasOrgAuthPriv">  
            <div class="app-select">
                <el-select v-model="appCodeValue" placeholder="请选择应用" @change="selectAppCode">
                    <el-option
                        v-for="item in options"
                        :key="item.appId"
                        :label="item.appName"
                        :value="item.appId"
                    >
                    </el-option>
                </el-select>
            </div>
            <div style="position:absolute;right:16px;z-index:10;">
                <el-button
                    :loading="dialogAuthTree.loading"
                    type="primary"
                    @click="openUserAuthWin"
                    size="small"
                >增加授权操作</el-button>
            </div>
            <el-tabs class="right-tabs" v-model="activeAuthTabName">
                <el-tab-pane label="可访问权限" name="canAccess">
                    <div style="margin:20px;">
                        <el-tree
                            ref="canAccessMenuTree"
                            class="roles-menuTree"
                            style="margin-top:20px; overflow-x:hidden"
                            :data="canAccessMenuTree.tree"
                            :props="canAccessMenuTree.defaultProps"
                            :style="{height: treeHeight + 'px'}"
                            node-key="sysOrgAuthorizeId"
                            :show-checkbox="false"
                            default-expand-all
                            :expand-on-click-node="true"
                            @check-change="checkChageTree"
                            :render-content="renderCanAccessMenuTreeContent"
                        >
                        </el-tree>
                    </div>
                </el-tab-pane>

                <el-tab-pane label="可授权权限" name="canAuth">
                    <div style="margin:20px;">
                        <el-tree
                            ref="canAuthMenuTree"
                            class="roles-menuTree"
                            style="margin-top:20px; overflow-x:hidden"
                            :data="canAuthMenuTree.tree"
                            :props="canAuthMenuTree.defaultProps"
                            :style="{height: treeHeight + 'px'}"
                            node-key="sysOrgAuthorizeId"
                            :show-checkbox="false"
                            default-expand-all
                            :expand-on-click-node="true"
                            @check-change="checkChageTree"
                            :render-content="renderCanAuthMenuTreeContent"
                        >
                        </el-tree>
                    </div>
                </el-tab-pane>                
            </el-tabs>                
        </div>

        <div v-show="!hasOrgAuthPriv" style="position:absolute;top:50%;left:50%;">
            没有操作该部门的权限
        </div>
      </div>
        

    </div>
</template>
<script>
import store from '@/store/index.js';
import { checkCharLength, checkCharLength2, checkCharNoChinese, checkChar } from '@/utils/validator.js';
import { dgTree, objAssign, getCookie } from '@/utils/util.js';
import { setTimeout, clearTimeout } from 'timers';
import usersAddAndEdit from './usersAddAndEdit.vue';
export default {
    components: {
        usersAddAndEdit
    },
    data () {
        return {
            activeMenu: '', //菜单id
            companys: [], // 用户公司列表
            companyId: '', // 选择公司Id
            companyName: '', // 选择公司名称
            saveLoading: false,
            store,
            treeHeight: 500,
            treeHeight2: 300,
            clickRole: false, // 是否已点击角色
            //  角色
            rolesTree: {
                tree: [],
                item: {},
                //  默认配置数据对应项
                defaultProps: {
                    children: 'children',
                    label: 'roleName'
                },
                //  默认展开的ID数组
                expandedKeys: []
            },
            //  菜单树
            menuTree: {
                tree: [],
                items: [],
                item: [],
                //  默认配置数据对应项
                defaultProps: {
                    children: 'children',
                    label: 'menuLabel'
                },
                //  默认展开的ID数组
                expandedKeys: [],
                //  角色菜单关联表数据
                authList: [],
                loading: false
            },
            //  能访问菜单树
            canAccessMenuTree: {
                tree: [],
                items: [],
                item: [],
                //  默认配置数据对应项
                defaultProps: {
                    children: 'children',
                    label: 'menuLabel'
                },
                //  默认展开的ID数组
                expandedKeys: [],
                //  角色菜单关联表数据
                authList: [],
                loading: false
            },
            //  能授权菜单树
            canAuthMenuTree: {
                tree: [],
                items: [],
                item: [],
                //  默认配置数据对应项
                defaultProps: {
                    children: 'children',
                    label: 'menuLabel'
                },
                //  默认展开的ID数组
                expandedKeys: [],
                //  角色菜单关联表数据
                authList: [],
                loading: false
            },   
            dialogAuthTree:{
                tree: [],
                loading: false,
                show: false,
                title: "授权",
                treeHeight: 400,
                accessPrivArr: [],
                authPrivArr: []
            },    
            dialogOrgTree:{
                tree: [],
                loading: false,
                show: false,
                title: "添加",
                treeHeight: 400,
                //  默认配置数据对应项
                defaultProps: {
                    children: 'children',
                    label: 'orgName'
                }
            },                          
            dialogRoles: {
                //  保存中
                loading: false,
                operate: 'add',
                show: false,
                title: '添加',
                //  编辑时选中
                item: {},
                form: {
                    id: '',
                    roleCode: '',
                    roleName: '',
                    pId: '',
                    rank: '1',
                    roleType: '3',
                    remark: '',
                    companyId: ''
                },
                ruleValidate: {
                    pId: [
                        { required: true, message: '父级角色不能为空', trigger: 'change' }
                    ],
                    roleCode: [
                        { required: true, message: '角色编码不能为空', trigger: 'change' },
                        { validator: checkCharLength2, max: 64, trigger: 'change' },
                        { validator: checkCharNoChinese, trigger: 'change' }
                    ],
                    roleName: [
                        { required: true, message: '角色名称不能为空', trigger: 'change' },
                        { validator: checkCharLength, max: 32, trigger: 'change' },
                        { validator: checkChar, trigger: 'change' }
                    ],
                    roleType: [
                        { required: true, message: '请选择角色类型', trigger: 'change' }
                    ],
                    remark: [
                        { validator: checkCharLength, max: 100, trigger: 'change' }
                    ]
                }
            },
            //  数据权限列表
            table: {
                height: 600,
                loading: false,
                list: [],
                //  选中项
                items: [],
                item: {},
                //  角色与数据权限关联数据
                authList: []
            },
            restoreData: [],
            backVisible: false,
            restoreVisible: false,
            restoreSVisible: false,
            deletVisible: false,
            loadingStatus: false,
            doNotClose: true,
            filterText: '',
            arrID: [],
            //  机构树
            orgTree: {
                tree: [],
                items: [],
                item: {},
                //  默认配置数据对应项
                defaultProps: {
                    children: 'children',
                    label: 'orgName',
                    disabled : 'disabled'
                },
                //  默认展开的ID数组
                expandedKeys: [],
                //  角色菜单关联表数据
                authList: []
            },
            activeOrgId: '', // 点击项id
            activeAuthTabName: 'canAccess',
            hasOrgAuthPriv:true,
            // 用户列表
            userTable: {
                height: 600,
                loading: false,
                list: [],
                list2: [],
                listBack: [],
                //  选中项
                items: [],
                item: {},
                tableParams: {
                    form: {
                        companyId: '',
                        pageNum: 1,
                        pageSize: 30
                    },
                    //  返回分页数据
                    page: {
                        total: 0
                    }
                }
            },
            userTableBack: [],
            dialogStatus: 'add',
            activeRoleId: '', // 点击项id
            addUserRole: false,
            multipleSelection: [],
            batchVisible: false,
            pasteStatus: false, // 粘贴复制状态区分
            isPaste: 3, // 区分正常点击与复制粘贴
            copyResourceIdArr1: [], // 复制菜单权限
            copyResourceIdArr2: [], // 复制数据权限
            copyResourceIdArr3: [], // 复制机构权限
            grouping: [],
            choiceGrouping: '',
            indexRow: 0,
            pageSize: 40, // 默认每页显示条数
            pageNum: 1, // 默认当前页
            total: 0, // 数据总数
            editPr: false,
            delPr: false,
            pastePr: false, //按钮权限
            rolesUserdialog: false,
            props: true,
            checkList: [],
            usersTree: [],
            obj: {
                value: '',
                label: '',
                children: []
            },
            treeLoading: false,
            filterMethod(query, item) {
                return item.pinyin.indexOf(query) > -1;
            },
            reseveValue: [],
            data: [],
            transferLoading: false, // 穿梭框数据加载
            groupObject: {},
            userData: [], // 选中机构下的所有用户合集
            addUserList: [], //已选择添加到角色下的用户列表
            oldList: [], // 角色下的初始用户列表
            removeList: [], // 角色下需移除的用户列表
            isRoleUser: false, // 区分用户列表展示角色下用户无分页
            appCodeValue: '',
            isManagerRole: false, // 区分是否管理员角色，管理员角色顶部才显示增加角色的入口
            options: [],
            currentAccountManagerRoles: []
        }
    },
    created () {
        this.activeMenu = window.top.localStorage.getItem('activeMenu');
        this.getEntryListData()
    },
    mounted () {
        // 获取公司信息
        this.companys = JSON.parse(window.top.localStorage.getItem('companys'));
        this.companyId = window.top.localStorage.getItem('companyId');
        if (this.companyId !== '' && this.companyId !== null) {
            this.companyName = this.companys.find((x) => x.id === this.companyId).companyName;
        }
        this.userTable.tableParams.form.companyId = this.companyId;
        this.dialogRoles.form.companyId = this.companyId;
        this.initData();
        this.$nextTick(() => {
            //  设置树区域高度
            this.treeHeight = this.getRoleHeight(this.$refs['rolesTree'].$el) - 120;
            //this.editPr = this.checkPrivilege(this.activeMenu + 'ROLEEDIT');
            //this.delPr = this.checkPrivilege(this.activeMenu + 'ROLEDELET');
            //this.pastePr = this.checkPrivilege(this.activeMenu + 'ROLEPASTE');
        });

        var sysRoles = (top.globalUserInfo || []).sysRoles || [];
        var managerRoleArr = [];
        for(var i = 0; i < sysRoles.length; i++){
            if(sysRoles[i].roleId == "superadmin" || sysRoles[i].roleType == 3){
                // 是管理员账号或者roleType为3的都显示添加角色的按钮入口
                this.isManagerRole = true;
                managerRoleArr.push(sysRoles[i]);
            }
        }
        // 过滤条件: 管理员或者roleType为3的角色
        this.currentAccountManagerRoles = managerRoleArr;
    },
    computed: {
        //  树配置
        defaultProps () {
            return this.store.state.system.organizManage.defaultProps;
        },
        //  展开数组
        expandedKeys: {
            get: function () {
                return this.store.state.system.organizManage.expandedKeys;
            },
            set: function (data) {
                this.store.commit('system/organizManage/expandedKeys', data);
            }
        },
        //  选中节点数据
        treeItem () {
            return this.store.state.system.sysPosts.treeItem;
        }
    },
    watch: {
        filterText (val) {
            this.$refs.rolesTree.filter(val);
        }
    },
    methods: {
        //  计算树区域高度
        getRoleHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        //  init
        initData () {
            //  取角色数据
            // this.getRoles();
            //  取菜单数据
            // this.getMenu();
            //  取数据权限列表
            //this.getDataRoles();
            // 获取备份列表
            //   this.getRecorList();
            // 获取机构列表
            this.getOrg();
            //获取分组
            //this.getDictList();
            // 获取当前公司集团id
            //this.getGroupData()
            // add by lester
            this.getRoles();
        },
        // 每条页数
        pageSizeChange (pageSize) {
            this.userTable.tableParams.form.pageSize = pageSize;
            this.getUser(this.userTable.tableParams.form);
        },
        //当前页
        pageCurrentChange (pageNum) {
            this.userTable.tableParams.form.pageNum = pageNum;
            this.getUser(this.userTable.tableParams.form);
        },
        getDictList () {
            this.axios.get('pass/v1/sysdicts/listDict?pDictId=ROLE_TYPE&status=1&companyId=' + this.companyId).then((res) => {
                if (res.code === '0') {
                    this.grouping = res.data.list
                } else {
                    this.$message.error(res.message)
                }
            }).catch(() => {
                //   console.log(res.message)
            })
        },
        //  角色table点击
        async nodeClick (item) {
            let that = this;
            //this.loopSetDisabled(this.orgTree.tree);
            if(!item){
                // 手动触发nodeClick调用时用到 add by lester
                item = this.rolesTree.item;
            }
            this.clickRole = true;
            this.rolesTree.item = item;

            this.activeRoleId = item.roleId;
            //选中行
            // this.$refs.rolesTree.toggleRowSelection(item);
            //  查询权限选中项
            /**
            await this.getSysauthorizes(item.roleId, '1').then(() => {
                //  选中菜单
                let resourceIdArr = [];
                for (let item of this.menuTree.authList) {
                    if (item.resourceId && item.resourceType === '1' && that.$refs.menuTree.getNode(item.resourceId) && that.$refs.menuTree.getNode(item.resourceId).childNodes.length === 0) {
                        resourceIdArr.push(item.resourceId);
                    }
                }
                switch (that.isPaste) {
                    case 1: //复制
                        //  选中
                        this.$refs['menuTree'].setCheckedKeys(resourceIdArr);
                        that.copyResourceIdArr1 = resourceIdArr;
                        break;
                    case 2: // 粘贴
                        //  清空
                        this.$refs['menuTree'].setCheckedKeys([]);
                        //  选中
                        this.$refs['menuTree'].setCheckedKeys(that.copyResourceIdArr1);
                        break;
                    case 3: // 普通点击
                        this.$refs['menuTree'].setCheckedKeys(resourceIdArr);
                        break;
                }
                this.ruleTreeClick(item)
                this.activeRoleId = item.roleId;
            });*/
            /**
            await this.getSysauthorizes(item.roleId, '2').then(() => {
                //  选中数据权限
                if (that.isPaste === 1) {
                    this.table.list.forEach(row => {
                        let bol = false;
                        for (let item of this.table.authList) {
                            if (item.resourceId === row.tableAuthId && item.resourceType === '2') {
                                bol = true;
                                break;
                            }
                        }
                        if (bol) {
                            this.$refs['dataTable'].toggleRowSelection(row, true);
                        } else {
                            this.$refs['dataTable'].toggleRowSelection(row, false);
                        }
                    });
                    that.copyResourceIdArr2 = this.table.authList;
                } else if (that.isPaste === 2) {
                    this.table.list.forEach(row => {
                        let bol = false;
                        for (let item of that.copyResourceIdArr2) {
                            if (item.resourceId === row.tableAuthId && item.resourceType === '2') {
                                bol = true;
                                break;
                            }
                        }
                        if (bol) {
                            this.$refs['dataTable'].toggleRowSelection(row, true);
                        } else {
                            this.$refs['dataTable'].toggleRowSelection(row, false);
                        }
                    });
                } else {
                    this.table.list.forEach(row => {
                        let bol = false;
                        for (let item of this.table.authList) {
                            if (item.resourceId === row.tableAuthId && item.resourceType === '2') {
                                bol = true;
                                break;
                            }
                        }
                        if (bol) {
                            this.$refs['dataTable'].toggleRowSelection(row, true);
                        } else {
                            this.$refs['dataTable'].toggleRowSelection(row, false);
                        }
                    });
                }
            });*/

            await this.getSysauthorizes2(item.roleId).then(() => {
                //  角色下的组织部门列表
                let orgIdArr = [];
                for (let item of this.orgTree.authList) {
                    if (item.orgId && that.$refs.orgTree.getNode(item.orgId) && that.$refs.orgTree.getNode(item.orgId).childNodes.length === 0) {
                        orgIdArr.push(item.orgId);
                    }
                }
                switch (that.isPaste) {
                    case 1: // 复制
                        this.$refs['orgTree'].setCheckedKeys(orgIdArr);
                        that.copyResourceIdArr3 = orgIdArr;
                        break;
                    case 2: // 粘贴
                        this.$refs['orgTree'].setCheckedKeys(orgIdArr);
                        //  清空
                        this.$refs['orgTree'].setCheckedKeys([]);
                        //  选中
                        this.$refs['orgTree'].setCheckedKeys(that.copyResourceIdArr3);
                        break;
                    case 3: // 普通点击
                        this.$refs['orgTree'].setCheckedKeys(orgIdArr);
                        for(var i = 0; i < orgIdArr.length; i++){
                            that.$refs.orgTree.getNode(orgIdArr[i]).data.disabled = false;
                        }
                        break;
                }
            });

            switch (that.isPaste) {
                case 1: // 复制
                    this.$message.success('复制成功');
                    that.isPaste = 3;
                    this.pasteStatus = !this.pasteStatus;
                    break;
                case 2: // 粘贴
                    this.$message.success('粘贴成功，如需保存请进行保存操作！');
                    that.isPaste = 3;
                    this.pasteStatus = !this.pasteStatus;
                    break;
                case 3: // 普通点击
                    // do
                    break;
            }
        },
        // 获取结构下的菜单列表
        getOrgMenu(item){
            let that = this;
            this.getCanAccessMenuList(item.orgId);            
            this.getCanAuthMenuMenuList(item.orgId);
            this.activeOrgId = item.orgId;
            this.hasOrgAuthPriv = !item.disabled;
        },
        // 当前行发生改变触发穿梭框刷新
        handleCurrentChange () {
            this.reseveValue = [];
            this.addUserList = [];
        },
        //  数据权限选中
        dataSelectChange (items) {
            //
            this.table.items = items;
        },
        //  保存配置
        async rolesMenuDataSave () {
            this.saveLoading = true;
            // if (!this.multipleSelection || this.multipleSelection.length < 1) {
            //     this.$message.error('请选择角色');
            //     this.saveLoading = false;
            //     return false;
            // }
            //  取菜单选中项
            let menuIdArr = this.$refs['menuTree'].getHalfCheckedKeys().concat(this.$refs['menuTree'].getCheckedKeys());
            // 取机构选中项
            let orgIdArr = this.$refs['orgTree'].getHalfCheckedNodes().concat(this.$refs['orgTree'].getCheckedNodes());
            let orgIdArr2 = this.$refs['orgTree'].getHalfCheckedKeys().concat(this.$refs['orgTree'].getCheckedKeys());
            // for (let item of orgIdArr) {
            //     if ('children' in item && item.children !== null) {
            //         for (let s of item.children) {
            //             if (JSON.stringify(orgIdArr).indexOf(JSON.stringify(s)) > -1) {
            //                 let index = orgIdArr2.findIndex(item => item === s.orgId);
            //                 orgIdArr2.splice(index,1);
            //             }
            //         }
            //     }
            // }
            //  取数据权限选中项
            let tempArr = this.table.items ? this.table.items : [];
            let dataArr = [];
            for (let item of tempArr) {
                if (item.id && item.id !== '') {
                    dataArr.push(item.id);
                }
            }
            //  分配菜单
            // if(menuIdArr.length !== 0 && dataArr.length !== 0 ) {
                await this.addRoleUser(); // 在角色下添加用户
                await this.setSysauthorizes(menuIdArr, '1');
                await this.setSysauthorizes(dataArr, '2');
                await this.setSysauthorizes2(orgIdArr2, 0);
            // } else {
            //     this.$message.error('功能权限与数据权限至少选择一个选项！')
            // }
            // 角色下移除用户
            if (this.removeList.length !== 0) {
                this.deleteUserRole(this.removeList).then(() =>{
                    this.saveLoading = false;
                });
                this.removeList = [];
            }
        },
        //  取角色树
        getRoles () {
            this.rolesTree.loading = true;
            this.axios.get('pass/v1/sysroles/getMineChildManageRole?' + "companyId=" + this.companyId).then((res) => {
                if (res.code === '0') {
                    this.rolesTree.tree = res.data;
                    this.rolesTree.loading = false;
                } else {
                    this.rolesTree.loading = false;
                    this.$message.error(res.message);
                }
            }).catch((err) => {
                console.log(err);
            })
        },
        // 下拉选择公司
        selectComPany (command) {
            this.companyId = command.id;
            this.companyName = command.companyName;
            this.userTable.tableParams.form.companyId = this.companyId;
            this.getRoles();
            this.getMenu();
            this.getDataRoles();
            this.getOrg();
            this.getGroupData()
        },
        // 当我切换了公司以后，那么我就要发送请求获取该公司隶属集团id
        getGroupData () {
            this.axios.get('pass/v1/sysgroups/findGroupByCompanyId?companyId=' + this.companyId).then((res) => {
                if (res.code === '0') {
                    this.groupObject = res.data
                } else {
                    this.$message.error(res.message)
                }
            }).catch(() => {
                //   console.log(res.message)
            })
        },
        //  取菜单
        async getMenu () {
            //  查询列表
            this.menuTree.loading = true;
            const promise = await this.store.dispatch('system/functionMain/menuTree', { companyId: this.companyId, appId: this.appCodeValue }).then(res => {
                if (res.code === '0') {
                    //this.menuTree.tree = res.data;
        
                    //this.canAccessMenuTree.tree = res.data;
                    //this.canAuthMenuTree.tree = res.data;
                    //this.menuTree.loading = false;
                    //let arr = [];
                    for (let i = 0; i < res.data.length; i++) {
                        //arr.push(this.moveFunChildren(res.data[i]));
                    }
                } else {
                    //this.$message.error(res.message);
                    //this.menuTree.loading = false;
                }
            });
            return promise;
        },
        //  获取当前登录账号下相关授权权限 this.appCodeValue
        async getUserCanAuthMenuList () {
            //  查询列表
            this.menuTree.loading = true;
            const promise = await this.store.dispatch('system/rolesManage/userCanAuthMenuList', { appId: this.appCodeValue }).then(res => {
                if (res.code === '0') {
                    this.dialogAuthTree.tree = res.data;
                    this.dialogAuthTree.show = true;
                    let arr = [];
                    for (let i = 0; i < res.data.length; i++) {
                        //arr.push(this.moveFunChildren(res.data[i]));
                    }
                } else {
                    this.$message.error(res.message);
                    this.menuTree.loading = false;
                }
            });
            return promise;
        },
        //  获取当前登录账号下可管理的部门列表
        async getUserCanAuthOrgList () {
            //  查询列表
            this.menuTree.loading = true;
            const promise = await this.store.dispatch('system/rolesManage/userCanAuthOrgList', { appId: this.appCodeValue }).then(res => {
                if (res.code === '0') {
                    this.dialogOrgTree.tree = res.data;
                    this.dialogOrgTree.show = true;
                    let arr = [];
                } else {
                    this.$message.error(res.message);
                    this.menuTree.loading = false;
                }
            });
            return promise;
        },        
        //  取数据权限列表
        async getDataRoles () {
            //  查询列表
            const promise = await this.store.dispatch('system/rolesManage/dataRolesList1', { companyId: this.companyId }).then(res => {
                if (res.code === '0') {
                    this.table.list = res.data;
                } else {
                    this.$message.error(res.message);
                }
            });
            return promise;
        },
        // 取机构树
        async getOrg () {
            //  查询机构树
            this.treeLoading = true
            const promise = await this.store.dispatch('system/organizManage/tree', this.companyId).then(res => {
                if (res.code === '0') {
                    this.treeLoading = false
                    dgTree(res.data, 'children', item => {
                        if ('children' in item && (item.children === null || item.children.length < 1)) {
                            delete item.children;
                        }
                    });
                    var orgTreeData = res.data;
                    this.loopSetDisabled(orgTreeData);
                    this.orgTree.tree = orgTreeData;
                    // 获取用户列表
                    this.getUser(this.userTable.tableParams.form);
                } else {
                    this.$message.error(res.message);
                }
            });
            return promise;
        },
        loopSetDisabled (data){
            for(var i = 0; i < data.length; i++){
                data[i].disabled = true;
                if(data[i].children && data[i].children.length){
                    this.loopSetDisabled(data[i].children);
                }        
            }
        },
        //  取角色菜单数据关联，数据
        //  resourceType 资源类型 资源类型：1-菜单 按钮 2-数据集权限
        async getSysauthorizes (roleId, resourceType) {
            const promise = await this.store.dispatch('system/rolesManage/sysauthorizes', { roleId, resourceType, pageSize: '100000' }).then(res => {
                if (res.code === '0') {
                    if (resourceType === '1') {
                        this.menuTree.authList = res.data.list;
                    } else if (resourceType === '2') {
                        this.table.authList = res.data.list;
                    }
                } else {
                    this.$message.error(res.message);
                }
            });
            return promise;
        },
        // 取角色机构关联数据
        async getSysauthorizes2 (roleId) {
            const promise = await this.store.dispatch('system/rolesManage/dataOrgsList', { roleId, pageSize: '100000' }).then(res => {
                if (res.code === '0') {
                    this.orgTree.authList = res.data.list;
                } else {
                    this.$message.error(res.message);
                }
            });
            return promise;
        },
        // 获取部门可访问菜单列表
        async getCanAccessMenuList (orgId) {
            const promise = await this.store.dispatch('system/rolesManage/canAccessMenuList', { orgId, appId: this.appCodeValue}).then(res => {
                if (res.code === '0') {
                    this.canAccessMenuTree.tree = res.data;
                    //for (let i = 0; i < res.data.length; i++) {
                        //this.moveFunChildren(res.data[i]);
                    //}
                } else {
                    
                }
            });
            return promise;
        },
        // 获取部门可授权菜单列表
        async getCanAuthMenuMenuList (orgId) {
            const promise = await this.store.dispatch('system/rolesManage/canAuthMenuList', { orgId, appId: this.appCodeValue}).then(res => {
                if (res.code === '0') {
                    this.canAuthMenuTree.tree = res.data;
                    //for (let i = 0; i < res.data.length; i++) {
                        //this.moveFunChildren(res.data[i]);
                    //}                    
                } else {
                    
                }
            });
            return promise;
        },
        // 批量赋权限
        async batchAuthMenu (orgId) {
            var menuIdArr = this.$refs['dialogAuthMenuTree'].getHalfCheckedKeys().concat(this.$refs['dialogAuthMenuTree'].getCheckedKeys());
            if(!menuIdArr.length){
                this.$message.error('不能设置空的权限');
                return;
            }
 
            // 1: 可授权 2: 可访问
            var type = (this.activeAuthTabName == "canAccess") ? 2 : 1;
            const promise = await this.store.dispatch('system/rolesManage/batchAuthMenu', {orgId, authorizes: menuIdArr.join(","), type}).then(res => {
                if (res.code === '0') {
                    this.$message.success('授权操作成功');
                    this.getCanAccessMenuList(orgId);
                    this.getCanAuthMenuMenuList(orgId);
                    this.dialogAuthTree.show = false;
                } else {
                }
            });
          
            return promise;
        },
        // 删除权限
        async deleteOrgMenu (ids) {
            const promise = await this.store.dispatch('system/rolesManage/deleteOrgMenu', {id: ids}).then(res => {
                if (res.code === '0') {
                    this.$message.success('删除操作成功');
                    this.activeOrgId && this.getCanAccessMenuList(this.activeOrgId);
                    this.activeOrgId && this.getCanAuthMenuMenuList(this.activeOrgId);
                } else {
                }
            });
          
            return promise;
        },
        //  设置角色菜单数据关联，数据
        //  resourceType 资源类型 资源类型：1-菜单 按钮 2-数据集权限
        async setSysauthorizes (items, resourceType) {
            let roleIdArr = '';
            if (this.multipleSelection && this.multipleSelection.length > 1) {
                for (let i = 0; i < this.multipleSelection.length; i++) {
                    roleIdArr += i === 0 ? this.multipleSelection[i].roleId : ',' + this.multipleSelection[i].roleId
                }
            } else if (this.multipleSelection && this.multipleSelection.length === 1){
                roleIdArr = this.multipleSelection[0].roleId;
            }
            let form = {
                roleId: roleIdArr ? roleIdArr : this.activeRoleId,
                resourceType: resourceType,
                resourceId: items.join(',')
            };

            //
            const promise = await this.store.dispatch('system/rolesManage/setSysauthorizes', form).then(res => {
                if (res.code === '0') {
                    this.$message.success('设置成功');
                } else {
                    this.$message.error(res.message);
                }
            });
            return promise;
        },
        // 设置角色机构数据关联
        async setSysauthorizes2 (items, number) {
            let roleIdArr = '';
            if (this.multipleSelection && this.multipleSelection.length > 0) {
                // for (let i = 0; i < this.multipleSelection.length; i++) {
                    if (number < this.multipleSelection.length) {
                        let itemForm = {
                            roleId: this.multipleSelection[number].roleId,
                            orgIds: items.join(',')
                        };
                        // 设置机构权限
                        const promise = await this.store.dispatch('system/rolesManage/setSysauthorizes2', itemForm).then(res => {
                            if (res.code === '0') {
                                this.$message.success('设置成功');
                            } else {
                                this.$message.error(res.message);
                            }
                        });
                        this.setSysauthorizes2(items, number + 1)
                        this.saveLoading = false;
                        return promise;
                    }
                // }
            } else {
                let form = {
                    roleId: this.activeRoleId,
                    orgIds: items.join(',')
                };

                // 设置机构权限
                const promise = await this.store.dispatch('system/rolesManage/setSysauthorizes2', form).then(res => {
                    if (res.code === '0') {
                        this.$message.success('设置成功');
                        this.dialogOrgTree.show = false;
                        this.nodeClick();
                    } else {
                        this.$message.error(res.message);
                    }
                });
                this.saveLoading = false;
                return promise;
            }
        },
        //  add roles
        addRoles (form) {
            this.dialogRoles.loading = true;
            this.store.dispatch('system/rolesManage/addRoles', form).then(res => {
                this.dialogRoles.loading = false;
                if (res.code === '0') {
                    this.$message.success('添加成功');
                    this.dialogRoles.show = false;
                    //  更新列表
                    this.rolesTree.tree.unshift(res.data)
                    this.$refs['rolesTree'].setCurrentRow(res.data);
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  删除角色
        delRoles (items) {
            //
            this.store.dispatch('system/rolesManage/delRoles', items).then(res => {
                if (res.code === '0') {
                    this.$message.success('删除成功');
                    //  更新列表
                    this.getRoles();
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  修改角色
        editRoles (form) {
            //
            this.store.dispatch('system/rolesManage/editRoles', { id: form.id, form: form }).then(res => {
                if (res.code === '0') {
                    this.$message.success('修改成功');
                    this.dialogRoles.show = false;
                    //  更新列表
                    for (let item in this.rolesTree.tree[this.indexRow]) {
                        this.rolesTree.tree[this.indexRow][item] = res.data[item];
                    }
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        // //  操作
        operateRole (str, item, index, node) {
            switch (str) {
                case 'add':
                    //
                    this.dialogRoles.operate = 'add';
                    this.dialogRoles.title = '添加';
                    this.dialogRoles.show = true;
                    this.dialogRoles.form.pId = '';
                    this.dialogRoles.form.pId = this.currentAccountManagerRoles[0].roleId;
                    setTimeout(() => {
                        this.$refs['dialogRoles'].resetFields();
                        this.dialogRoles.form.pId = this.currentAccountManagerRoles[0].roleId;
                    }, 100);
                    break;
                case 'padd':
                    //
                    this.dialogRoles.operate = 'add';
                    this.dialogRoles.title = '添加';
                    this.dialogRoles.show = true;
                    setTimeout(() => {
                        this.$refs['dialogRoles'].resetFields();
                        this.dialogRoles.form.pId = item.id;
                    }, 100);
                    break;
                case 'edit':
                    //
                    this.dialogRoles.operate = 'edit';
                    this.dialogRoles.title = '修改';
                    this.dialogRoles.show = true;
                    this.indexRow = index;
                    setTimeout(() => {
                        this.$refs['dialogRoles'].resetFields();
                        this.dialogRoles.form = objAssign(this.dialogRoles.form, item);
                    }, 100);

                    // this.$refs.rolesTree.toggleRowSelection(item);
                    break;
                case 'del':
                    //
                    let data = item;
                    //   if ((data.children && data.children.length > 0) || (node.childNodes && node.childNodes.length > 0)) {
                    //     this.$message.error('此节点有子节点，不允许删除');
                    //     return false;
                    //   }
                    //
                    this.$confirm('确定要删除记录吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.delRoles([item]);
                    }).catch(() => {
                        this.$message.info('已取消操作');
                    });
                    break;
            }
        },
        //  保存
        submitRole () {
            let _bool = false;
            this.currentAccountManagerRoles.forEach(item => {
                if(item.roleId === this.dialogRoles.form.pId) {
                    if(this.dialogRoles.form.roleName === item.roleName) {
                        _bool = true;
                    }
                }
            });

            if(_bool) {
             this.$message.error('当前新增数据中父级角色和角色名称不能相同');
             return;
            }

            //this.dialogRoles.form.appId = this.appCodeValue;
            this.$refs['dialogRoles'].validate((valid) => {
                if (valid) {
                    if (this.dialogRoles.operate === 'add') {
                        this.addRoles(this.dialogRoles.form);
                    } else if (this.dialogRoles.operate === 'padd') {
                        //  添加子角色
                        //this.addRoles(this.dialogRoles.form);
                    } else if (this.dialogRoles.operate === 'edit') {
                        //this.editRoles(this.dialogRoles.form);
                    }
                }
            })
        },
        // 树形控件过滤数据
        filterOrgTree (value, data) {
            if (!value) return true;
            return data.roleName.indexOf(value) !== -1;
        },
        // 选中事件切换
        selsChange (val) {
            var valIdx = [];
            for (var i = 0; i < val.length; i++) {
                var arrIDsame = false;
                valIdx.push(val[i]);
            }
            this.arrID = valIdx;
        },
        // 还原 备份 校验
        recordAction (type) {
            let that = this;
            that.loadingStatus = true;
            if (type) {
                // 删除备份记录
                if (!this.arrID.length) {
                    this.$message.error('请选中一条数据进行删除');
                    that.loadingStatus = false;
                } else {
                    let ids = '';
                    for (let i = 0; i < that.arrID.length; i++) {
                        if (i === 0) {
                            ids = ids + that.arrID[i].restoreName;
                        } else {
                            ids = ids + ',' + that.arrID[i].restoreName;
                        }
                    }
                    that.axios.delete('/pass/v1/sysbackups/deleteByVer/' + ids).then((res) => {
                        if (res.code === '0') {
                            that.$message.success('删除成功');
                            that.getRecorList();
                            that.deletVisible = false;
                        } else {
                            that.$message.error(res.message)
                        }
                        that.loadingStatus = false;
                    }).catch((res) => {
                        that.loadingStatus = false;
                    })
                }
            } else {
                // 还原选中备份记录
                if (this.arrID.length > 1) {
                    this.$message.error('最多选择一条备份记录');
                    that.loadingStatus = false;
                } else if (!this.arrID.length) {
                    this.$message.error('请选中一条备份记录');
                    that.loadingStatus = false;
                } else {
                    that.doNotClose = false;
                    that.axios.post('/pass/v1/sysbackups/restoreData/' + that.arrID[0].restoreName).then((res) => {
                        if (res.code === '0') {
                            that.$message.success('还原成功');
                            that.restoreVisible = false;
                            that.restoreSVisible = false;
                            that.getRecorList();
                        } else {
                            that.$message.error(res.message)
                        }
                        that.loadingStatus = false;
                        that.doNotClose = true;
                    }).catch((res) => {
                        that.loadingStatus = false;
                        that.doNotClose = true;
                    })
                }
            }
        },
        // 获取备份记录列表
        getRecorList () {
            let that = this;
            that.axios.get('pass/v1/sysbackups/selectVersion/').then((res) => {
                let list = [];
                if (res.code === '0') {
                    for (let i = 0; i < res.data.length; i++) {
                        let item = {};
                        item.restoreName = res.data[i];
                        list.push(item)
                    }
                    that.restoreData = list;
                } else {
                    that.$message.error(res.message)
                }
            }).catch((res) => {
                console.log(res)
            })
        },
        // 备份角色信息
        backUpRoles () {
            let that = this;
            that.loadingStatus = true;
            that.axios.post('pass/v1/sysbackups/backupData/').then((res) => {
                if (res.code === '0') {
                    that.$message.success('备份成功');
                    that.getRecorList();
                    that.backVisible = false;
                } else {
                    that.$message.error(res.message)
                }
                that.loadingStatus = false;
            }).catch((res) => {
                that.loadingStatus = false;
            })
        },
        // 用户过滤
        filterChange (filters) {
            var _this = this;
            _this.setFilterDatas(_this.$refs.userTable.columns, _this.$refs.userTable.tableData, ['userCode', 'userName', 'orgName']);
        },
        filterRoleChange (filters) {
            var _this = this;
            _this.setFilterDatas(_this.$refs.rolesTree.columns, _this.$refs.rolesTree.tableData, ['roleName', 'remark']);
        },
        // 查询机构名称
        getOrgName (list, code) {
            var name = '';
            for (let i = 0; i < list.length; i++) {
                try {
                    if (list[i].orgCode === code) {
                        name = list[i].orgName
                        return name
                    } else if (list[i].children && list[i].children.length >= 1) {
                        name = this.getOrgName(list[i].children, code);
                        if (name) {
                            return name
                        }
                    }
                } catch (error) {
                    console.log(error)
                }
            }
            return name;
        },
        // 获取用户列表
        getUser (form) {
            let _this = this;
            _this.userTable.loading = true;
            // form.pageSize = '1000000';
            this.store.dispatch('system/usersManage/list', form).then(res => {
                if (res.code === '0') {
                    this.userTable.list = res.data.list;
                    this.userTable.listBack = res.data.list;
                    this.userTable.tableParams.page.total = res.data.total;
                    for (let a = 0; a < this.userTable.list.length; a++) {
                        this.userTable.list[a].orgName = this.getOrgName(this.orgTree.tree, this.userTable.list[a].orgCode)
                        this.userTable.listBack[a].orgName = this.getOrgName(this.orgTree.tree, this.userTable.list[a].orgCode)
                    }
                    // 设置过滤数据 setFilterDatas(列数组对象, 数据, 需要过滤的字段, 列名转义对象)
                    _this.setFilterDatas(_this.$refs.userTable.columns, res.data.list, ['userCode', 'userName', 'orgName']);
                    _this.userTable.loading = false;
                } else {
                    this.$message.error(res.message);
                    this.userTable.tableParams.form.pageNum = 1;
                    this.userTable.tableParams.page.total = 0;
                }
            });
        },
        //  获取角色下的用户
        ruleTreeClick (item) {
            let that = this;
            that.userTable.loading = true;
            that.isRoleUser = true;
            that.axios.get('pass/v1/sysuserroles/getUsersByRoleId?roleId=' + item.id + '&companyId=' + this.companyId + '&status=1' + '&pageNum=1&pageSize=100000').then((res) => {
                if (res.code === '0') {
                    that.userTable.list = res.data.list;
                    // that.userTable.tableParams.page.total = res.data.total;
                    for (let a = 0; a < this.userTable.list.length; a++) {
                        this.userTable.list[a].orgName = this.getOrgName(this.orgTree.tree, this.userTable.list[a].orgCode);
                    }
                    that.oldList = JSON.parse(JSON.stringify(that.userTable.list));
                    if (res.data.list.length === 0) {
                        that.$refs.userTable.columns[0].filters = [];
                        that.$refs.userTable.columns[1].filters = [];
                        that.$refs.userTable.columns[2].filters = [];
                    }
                    that.setFilterDatas(that.$refs.userTable.columns, that.userTable.list, ['userCode', 'userName', 'orgName']);
                    this.userTable.loading = false;
                } else {
                    this.$message.error(res.message);
                }
            }).catch(() => {
                that.$message.error('请求失败')
            })
        },
        // 功能权限加入children
        moveFunChildren (data) {
            let obj = data;
            if (obj.menuType === '4' && obj.funChildren) {
                obj.children = [];
                for (let i = 0; i < obj.funChildren.length; i++) {
                    obj.children.push(obj.funChildren[i])
                }
            } else if (obj.children) {
                for (let i = 0; i < obj.children.length; i++) {
                    try {
                        if (obj.children[i].menuType === '4' && obj.children[i].funChildren) {
                            obj.children[i].children = [];
                            for (let b = 0; b < obj.children[i].funChildren.length; b++) {
                                obj.children[i].children.push(obj.children[i].funChildren[b]);
                            }
                        } else if (obj.children[i].children) {
                            for (let c = 0; c < obj.children[i].children.length; c++) {
                                obj.children[i].children[c] = this.moveFunChildren(obj.children[i].children[c])
                            }
                        }
                    } catch (err) {
                        console.log(err)
                    }
                }
            }
            return obj
        },
        toggleSelection (rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        // 用户列表选中
        toggleSelection1 (rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.dataTable.toggleRowSelection(row, true);
                });
            } else {
                this.$refs.dataTable.clearSelection();
            }
        },
        handleSelectionChange (val) {
            this.multipleSelection = val;
        },
        batchAuthorization () {
            if (this.multipleSelection && this.multipleSelection.length > 0) {
                this.batchVisible = true;
                this.userTable.loading = true;
                let timer = setTimeout(() => {
                    this.userTableBack = this.userTable.listBack;
                    this.userTable.loading = false;
                    clearTimeout(timer)
                }, 100)
            } else {
                this.$message.error('请选择角色')
            }
        },
        saveBatch () {
            if (this.userSelection && this.userSelection.length) {

            } else {
                this.$message.error('请选择用户')
            }
        },
        // 复制权限 粘贴权限
        paste (row) {
            if (!this.pasteStatus) {
                this.isPaste = 1;
            } else {
                this.isPaste = 2;
            }
        },
        editGrouping () {
            if (this.multipleSelection && this.multipleSelection.length < 1) {
                this.$message.error('请选择一个角色')
                return false
            }
            this.getDictList();
            this.backVisible = true;
        },
        changeGrouping () {
            let idArr = '';
            for (let i = 0; i < this.multipleSelection.length; i++) {
                if (i === 0) {
                    idArr = this.multipleSelection[i].roleId
                } else {
                    idArr += ',' + this.multipleSelection[i].roleId
                }
            }
            this.axios.put('pass/v1/sysroles/batchAddGroup?remark=' + this.choiceGrouping + '&roleId=' + idArr).then((res) => {
                if (res.code === '0') {
                    this.$message.success('操作成功');
                    this.initData();
                    this.backVisible = false;
                    this.choiceGrouping = '';
                }
            })
            this.backVisible = false;
        },
        // 获取用户角色关联数据
        getUserRole (user) {
            this.axios.get('pass/v1/sysuserroles/?roleId=' + this.rolesTree.item.id + '&userId=' + user.id).then((res) => {
                if (res.code === '0') {
                    this.removeList = this.removeList.concat(res.data.list);
                    this.userTable.list = this.userTable.list.filter((obj) => obj.id !== user.id);
                    this.$message.success('移除成功,请确认后在右上角进行统一保存！');
                } else {
                    this.$message.error(res.message)
                }
            }).catch((err) => {
                console.log(err);
            })
        },
        async removeRoleUser (row) {
            let _this = this
            let isNewRole = false;
            let newList = _this.oldList.filter((obj) => obj.id === row.id);
            if (newList.length !== 0) {
                await _this.getUserRole(row);
            } else {
                _this.userTable.list = _this.userTable.list.filter((obj) => obj.id !== row.id);
                _this.addUserList = _this.addUserList.filter((obj) => obj.id !== row.id);
                // 筛掉穿梭框已选值
                let index = _this.data.findIndex((obj) => obj.item.id === row.id)
                _this.reseveValue = _this.reseveValue.filter((obj) => obj !== index);
                _this.$message.success('移除成功');
            }
        },
        deleteUserRole (removeList) {
            for (let item of removeList) {
                this.axios.delete('pass/v1/sysuserroles/' + item.id).then((res) => {
                    // if (res.code === '0') {
                    //     //
                    // } else {
                    //     this.$message.error(res.message)
                    // }
                }).catch((err) => {
                    console.log(err);
                })
            }
        },
        async addUserDelog () {
            let _this = this
            let orgIdArr = this.$refs['orgTree'].getCheckedNodes();
            if (JSON.stringify(this.rolesTree.item) === '{}') {
                this.$message.warning('请您先点击某个具体角色');
            } else {
                if (orgIdArr.length > 0) {
                    // 剔除复选框选中的机构多余子集数据
                    let data = _this.getTreeAll(orgIdArr)
                    // 获取穿梭框用户数据
                    this.transferLoading = true
                    await _this.getAllOrgUser(data);
                    _this.rolesUserdialog = true;
                } else {
                    this.$message.warning('您当前尚未选择任何机构权限');
                }
            }
        },
        // 遍历树只返回选中父级，清除连带子集
        getTreeAll (tree) {
            let arr = []
            if (!!tree && tree.length !== 0) {
                tree.forEach(item => {
                    for (let index in tree) {
                        if (item.pId === tree[index].id) {
                            return false;
                        }
                    }
                    arr.push(item);
                })
            }
            return arr
        },
        // 获取选中机构下的所有用户
        getAllOrgUser (list) {
            let count = 0;
            for (let item of list) {
                let params = {
                    orgCode: item.orgCode,
                    orgName: item.orgName,
                    pageNum: 1,
                    pageSize: 100000,
                    companyId: this.companyId
                }
                this.store.dispatch('system/usersManage/list', params).then(res => {
                    if (res.code === '0') {
                        if (this.userData.length === 0) {
                            this.userData = res.data.list;
                        } else {
                            this.userData = this.userData.concat(res.data.list);
                        }
                        count++;
                        if (count === list.length) {
                            this.generateData(this.userData);
                        }
                    } else {
                        this.$message.error(res.message);
                    }
                });
            }
        },
        setCheckedNodes () {
            this.defaultExpand = true; // 展开所有节点
            for (var i = 0; i < this.$refs.orgTrees.store._getAllNodes().length; i++) {
                this.$refs.orgTrees.store._getAllNodes()[i].expanded = this.defaultExpand;
            }
        },
        setCheckedKeys () {
            this.defaultExpand = false;
            for (var i = 0; i < this.$refs.orgTrees.store._getAllNodes().length; i++) {
                this.$refs.orgTrees.store._getAllNodes()[i].expanded = this.defaultExpand;
            }
        },
        generateData (list) {
            // 穿梭框数据去掉已有用户
            if (list.length > 0 && this.oldList.length > 0) {
                for (let user in this.oldList) {
                    for (let item in list) {
                        if (list[item].userId === this.oldList[user].userId) {
                            list.splice(item, 1)
                        }
                    }
                }
            }
            const data = [];
            const cities = list;
            const pinyin = [];
            list.forEach(item => {
                pinyin.push(item.userName)
            })
            for (let obj of cities) {
                if (obj) {
                    obj['orgName'] = this.getOrgName(this.orgTree.tree, obj.orgCode);
                }
            }
            cities.forEach((city, index) => {
                data.push({
                    label: city.userName,
                    key: index,
                    pinyin: pinyin[index],
                    item: city
                });
            });
            this.data = []
            if(!this.addUserList.length) {
                this.reseveValue = []
            }
            this.data = data;
            if(!this.addUserList.length) {
                this.reseveValue = []
            }
            this.transferLoading = false;
        },
        checkChageTree (data, checked, node) {
            let length = this.userTable.list.length - this.addUserList.length;
            this.userTable.list = this.userTable.list.splice(0, length);
            this.addUserList = [];
        },
        // 角色确定按钮
        rolesSure () {
            this.addUserList = [];
            let reseveValueList = [];
            for (let i of this.reseveValue) {
                reseveValueList.push(this.data[i])
            }
            for (let item of reseveValueList) {
                let newList = this.oldList.filter((obj) => obj.id === item.item.id);
                if (newList.length === 0) {
                    this.addUserList.push(item.item);
                }
            }
            if (this.addUserList.length === 0) {
                this.$message.success('您当前选择的用户已拥有该角色！');
            } else {
                this.userTable.list = this.oldList.concat(this.addUserList);
                this.$message.success('添加成功,请确认后在右上角进行统一保存！');
            }
            if(this.$refs.myTransfer){
                this.$refs.myTransfer.$children["0"]._data.query = '';
                this.$refs.myTransfer.$children["3"]._data.query = '';
            }
            this.rolesUserdialog = false;
            this.userData = [];
        },
        // 在角色下添加用户
        addRoleUser () {
            let that = this;
            if (that.addUserList.length > 0) {
                for (let i = 0; i < that.addUserList.length; i++) {
                    let form = {
                        userId: that.addUserList[i].userId,
                        userCode: that.addUserList[i].userCode,
                        roleId: that.activeRoleId
                    };
                    that.axios.post('pass/v1/sysuserroles/', form).then((res) => {
                        if (res.code === '0') {
                            // that.$message.success('操作成功')
                            that.userData = [];
                            that.data = [];
                            that.addUserList = [];
                        } else {
                            that.$message.error(res.message)
                        }
                    }).catch(() => {
                        that.$message.error('操作失败')
                    })
                }
            }
        },
        // 角色取消
        rolesCancel () {
            this.$confirm('确认取消？')
            .then(_ => {
                if(this.$refs.myTransfer){
                    this.$refs.myTransfer.$children["0"]._data.query = '';
                    this.$refs.myTransfer.$children["3"]._data.query = '';
                }
                this.rolesUserdialog = false;
                this.userData = [];
                this.data = [];
                this.addUserList = [];
            })
            .catch(_ => {});
        },
        // 角色添加用户弹窗关闭
        roleDialogClose (done) {
            this.$confirm('确认关闭？')
            .then(_ => {
                if(this.$refs.myTransfer){
                    this.$refs.myTransfer.$children["0"]._data.query = '';
                    this.$refs.myTransfer.$children["3"]._data.query = '';
                }
                done();
                this.userData = [];
                this.data = [];
                this.addUserList = [];
            })
            .catch(_ => {});
        },
        selectAppCode() {
            //this.getRoles();
            //this.getMenu();
        },
    getEntryListData() {
      return this.axios
        .get("pass/v1/sysappclients/like/", {companyId: this.companyId})
        .then((response) => {
          let res = response.data;
          if (response.succeed) {
            this.options = res.list;
            this.appCodeValue = res.list[0].appId;
          } else {
            this.$message.error(response.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    openUserAuthWin() {
        this.getUserCanAuthMenuList();
    },
    openOrgWin() {
        this.getUserCanAuthOrgList();
    },
    beginBatchAuth() {
        this.batchAuthMenu(this.activeOrgId);    
    },
    addOrgToRole() {
        let dialogOrgIdArr = this.$refs['dialogOrgTree'].getHalfCheckedKeys().concat(this.$refs['dialogOrgTree'].getCheckedKeys());
        let oldOrgIdArr = this.$refs['orgTree'].getHalfCheckedKeys().concat(this.$refs['orgTree'].getCheckedKeys());
        this.setSysauthorizes2(dialogOrgIdArr.concat(oldOrgIdArr), 0);
    },
    renderAuthTreeContent(h, { node, data, store }) {
          if(node.parent.parent == null){
            return (
            <span class="custom-tree-node">
                <span>{node.label}</span>
            </span>);
          }else if(data.menuType == "1" || data.menuType == "4"){
            return (
            <span class="custom-tree-node">
                <span style="margin-right:10px;">{node.label}</span>
                <span>
                    <input type="checkbox" on-click={ (e) => this.addAccessPriv(e, data, node) }/>增加访问权限
                    &nbsp;&nbsp;&nbsp;
                    <input type="checkbox" on-click={ (e) => this.addAuthPriv(e, data, node) }/>增加授权权限
                </span>
            </span>);
          }
          else{
            return (
            <span class="custom-tree-node">
                <span>{node.label}</span>
            </span>);
          }
    },
    renderCanAuthMenuTreeContent(h, { node, data, store }) {
        return (
            <span class="custom-tree-node">
                <span>{node.label}</span>
                <span style="margin-left:20px;">
                    <a on-click={ (e) => this.deleteOrgAuth(e, data, node) }><span style="color:blue;">delete</span></a>
                </span>
            </span>);
    },
    renderCanAccessMenuTreeContent(h, { node, data, store }) {
        return (<span class="custom-tree-node">
            <span>{node.label}</span>    
            <span style="margin-left:20px;">
                <a on-click={ (e) => this.deleteOrgAuth(e,data,node) }><span style="color:blue;">delete</span></a>
            </span>
            </span>);
    },
    deleteOrgAuth(e,data,node) {
        //let sysOrgAuthorizeIdArr = this.$refs['canAccessMenuTree'].getHalfCheckedKeys().concat(this.$refs['canAccessMenuTree'].getCheckedKeys());
        var sysOrgAuthorizeIdArr = []; 
        sysOrgAuthorizeIdArr.push(node.data.sysOrgAuthorizeId);
        //while(node.parent){
           // node = node.parent;
           // node.data && node.data.sysOrgAuthorizeId && sysOrgAuthorizeIdArr.push(node.data.sysOrgAuthorizeId);
       // }
        this.deleteOrgMenu(sysOrgAuthorizeIdArr.join(","));
    },
    addPrivData(e,node,type) {
        //var menuId = node.menuId; dialogAuthMenuTree
        var isChecked = $(e.currentTarget).is(":checked");
        var hasExist = false;
        var index = 0;
        var arr = [];
        var key = "";
        var menuIdArr = [];
        menuIdArr.push(node.data.menuId);
        while(node.parent){
            node = node.parent;
            node.data && node.data.menuId && menuIdArr.push(node.data.menuId);
        }

        if(type == 1){
            // 可访问权限
            arr = this.dialogAuthTree.accessPrivArr;    
        }else if(type == 2){
            // 可授权权限
            arr = this.dialogAuthTree.authPrivArr;
        }

        
        if(isChecked){
            insertToArr();
        }else{
            deleteFromArr();
        }

        function insertToArr(){
            for(var i = 0; i < menuIdArr.length; i++){
                if($.inArray(menuIdArr[i], arr) == -1){
                    // 不插入重复的
                    arr.push(menuIdArr[i]);
                }
            }
        }

        function deleteFromArr(){
            for(var k = menuIdArr.length - 1; k >= 0; k--){
                if($.inArray(menuIdArr[k], arr) != -1){
                    // 删除
                    arr.splice(k,1);
                }
            }            
        }        
    },
    addAccessPriv(e, data, node) {
        this.addPrivData(e, node, 1);
    },
    addAuthPriv(e, data, node) {
        this.addPrivData(e, node, 2);
    }    
  }
}
</script>
<style lang="less" scoped>
.roles-manage {
    height: 100%;
    position: relative;
    min-width: 1000px;
    /deep/ .right-tabs {
        .roles-menuTree {
            .el-checkbox {
                margin-right: 10px;
            }
        }
        .el-tabs__item {
            height: 42px;
            line-height: 42px;
        }
        .el-tabs__nav-wrap::after {
            height: 1px;
            background-color: rgb(213, 213, 213);
        }
        .el-tabs__active-bar {
            height: 1px;
        }
        .el-tabs__nav {
            margin-left: 20px;
        }
    }
    .company-select {
        padding: 9px 15px 8px 15px;
        border-bottom: 1px solid #d5d5d5;
        .el-dropdown {
            font-weight: bold;
            font-size: 14px;
            cursor: pointer;
        }
    }
    .roles-tree-header {
        height: 42px;
    }
    //  保存
    .rolesManage-mainRight {
        position: relative;
        height: inherit;
    }
}
.el-dropdown-menu {
    overflow-y: scroll;
    max-height: 200px;
}
.foot-style {
    margin: 5px 0 0;
    text-align: right;
}
.rolesManage-footer {
    background: #f5f5f5;
    margin: -12px -17px -11px -17px;
    height: 40px;
    text-align: center;
    vertical-align: middle;
}

.rolesManage-invite-agree {
    border: none;
    background: none;
    font-size: 14px;
    color: #666;
    cursor: pointer;
    width: 100%;
    height: 100%;
}

.rolesManage-create-header {
    background-color: #f5f5f5;
    margin: -15px -15px 0 -15px;
}

.rolesManage-create-header-title {
    color: #666;
    font-size: 16px;
    text-align: center;
    height: 50px;
    line-height: 50px;
}

.rolesManage-mainLeft {
    width: 20%;
    border-right: 1px solid #e0e0e0;
    float: left;
    overflow-x: hidden;
    height: inherit;
}

.rolesManage-mainMiddle {
    width: 30%;
    float: left;
    border-right: 1px solid #e0e0e0;
    position: relative;
    height: inherit;
    .save {
        position: absolute;
        right: 20px;
        top: 7px;
        z-index: 100;
    }
}

.rolesManage-mainRight {
    width: 50%;
    float: left;
}

.mainRigh-function {
    padding: 13px 0 15px 20px;
    text-align: left;
    border-bottom: 1px solid #d5d5d5;
    position: relative;
}

.rolesManage-searchContent {
    text-align: left;
    position: relative;
    float: left;
    width: 50%;
    margin-left: 20px;
    margin-top: 5px;
    margin-bottom: 9px;
}
#pane-userList {
    padding: 10px;
}
.el-tree-node__content .el-icon-plus,
.el-tree-node__content .el-icon-edit {
    margin-right: 15px;
}
.el-select {
    width: 100%;
}
.sl-content-main {
    overflow: hidden;
}
.public-function-div {
    font-size: 16px;
    padding: 10px 20px;
    border-bottom: 1px solid #d5d5d5;
    position: relative;
}
.public-function-div .refresh {
    position: absolute;
    right: 15px;
    top: 10px;
}
.public-function-div .refresh2 {
    position: absolute;
    right: 80px;
    top: 10px;
}
.addUser-main {
    overflow: hidden;
    .addUser-Left {
        float: left;
        width: 40%;
        border-right: 2px solid #ccc;
    }
    .addUser-Right {
        float: left;
        width: 60%;
    }
}
/deep/ .el-transfer-panel {
    width: 44% !important;
    margin-left: 0px
}
/deep/ .el-transfer__buttons {
    display: inline-block;
    vertical-align: middle;
    padding: 0 10px;
    width: 12%;
    height: 100%;
}
/deep/ .el-transfer__button:first-child {
        display: block;
        padding: 10px;
        border-radius: 50%;
        font-size: 0;
        position: absolute;
        left: 47.8%;
        margin: -50px 0;
}
/deep/ .el-transfer .el-button+.el-button {
    display: block;
    padding: 10px;
    border-radius: 50%;
    font-size: 0;
    position: absolute;
    left: 47.8%;
    margin: 0px 0;
}
/deep/ .el-transfer .el-checkbox+.el-checkbox {
    margin-left: 0px;
}
.el-message .el-message--error {
    z-index: 3100!important;
}
.el-message .el-message--success {
    z-index: 3100!important;
}
.app-select {
    padding: 0px 15px 10px 0px;
}
</style>
