<template>
    <div class="ajm-panel">
        <div class="ajm-search-form">
            <el-form ref="searchForm" :model="searchForm" :inline="true">
                <el-row>
                    <el-col :span="8">
                        <el-form-item class="operate-buttons">
                            <el-button type="primary" icon="el-icon-ajm-add" @click="goAddRole" v-permission-code="'001002001_BTN'">{{$t('message.add')}}</el-button>
                            <el-button icon="el-icon-ajm-delete" @click="batchDeleteRole" v-permission-code="'001002002_BTN'">{{$t('message.delete')}}</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16" class="ajm-search-items">
                        <el-form-item>
                            <el-input id="enterSearch" class="search-item" v-model="searchForm.roleName" :placeholder="$t('message.RoleMain.confirmName')">
                            </el-input>
                        </el-form-item>
                        <el-form-item class="ajm-search-btns">
                            <el-button icon="el-icon-ajm-search" @click="search"></el-button>
                            <el-button icon="el-icon-ajm-refresh" @click="refreshSearch"></el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div class="ajm-table">
            <el-table ref="filterTable" :data="pageResult.list" tooltip-effect="light" style="width: 100%" @selection-change="roleIdsChange" @sort-change="handleSortChange" @filter-change="handleFilterChange" v-loading="listLoading">
                <el-table-column prop="roleId" type="selection" width="55" />
                <el-table-column type="index" :label="$t('message.Table.index')" width="70" />
                <el-table-column prop="roleName" :label="$t('message.RoleMain.roleName')"  :show-overflow-tooltip="true"/>
                <el-table-column prop="roleCode" :label="$t('message.RoleMain.roleCode')" :show-overflow-tooltip="true" min-width="120"/>
                <el-table-column prop="status.name" :label="$t('message.Table.status')" column-key="status" :filters="statusRole" :filter-method="filterStatus" :filter-multiple="false" width="70"/>
                <el-table-column prop="remark" :label="$t('message.RoleMain.describe')"  :show-overflow-tooltip="true"/>
                <el-table-column prop="createdTime" :label="$t('message.Table.createdTime')" width="180" sortable="custom" />
                <el-table-column :label="$t('message.Table.operate')" width="180" fixed="right">
                    <template slot-scope="scope">
                        <el-tooltip :content="$t('message.edit')" placement="top">
                            <el-button size="small" type="text" @click="goEditRole(scope.$index, scope.row)" v-permission-code="'001002003_BTN'" :disabled="scope.row.isDefault.value == 1">
                                <i class="el-icon-ajm-edit"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip :content="$t('message.delete')" placement="top">
                            <el-button size="small" type="text" @click="deleteRole(scope.$index, scope.row)" v-permission-code="'001002004_BTN'" :disabled="scope.row.isDefault.value == 1">
                                <i class="el-icon-ajm-delete"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip :content="$t('message.view')" placement="top">
                            <el-button size="small" type="text" @click="goSeeRole(scope.$index, scope.row)">
                                <i class="el-icon-ajm-view"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip :content="$t('message.RoleMain.roleUser')" placement="top">
                            <el-button type="text" @click="lookUser(scope.$index, scope.row)">
                                <i class="el-icon-ajm-user"></i>
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="ajm-pagination-bar">
            <el-pagination background @current-change="changePage" @size-change="handleSizeChange" :current-page="pageResult.pageNum" :page-sizes="[10, 20, 50, 100]"
                           :page-size="pageResult.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageResult.total">
            </el-pagination>
        </div>
        <!--编辑角色信息-->
        <el-dialog :title="dialogTitle" custom-class="ajm-dialog-middle" :visible.sync="roleFormVisible" width="45%" top="0" :before-close="closeRoleDialog" :modal-append-to-body="false" :close-on-click-modal="false">
            <el-form class="ajm-form" label-width="80px" :model="role" :rules="roleRules" ref="roleForm">
                <el-input v-model="role.roleId" style="display:none" />
                <el-form-item :label="$t('message.RoleMain.roleName')" prop="roleName" required>
                    <el-input v-model="role.roleName" :maxlength="20"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.RoleMain.roleCode')" prop="roleCode" required>
                    <el-input v-model="role.roleCode" :maxlength="50"></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="24">
                        <el-form-item :label="$t('message.RoleMain.describe')" style="width:100%">
                            <el-input type="textarea" :rows="4" v-model="role.remark" style="width:260px" :maxlength="200"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item :label="$t('message.RoleMain.roleStatus')" prop="status" required>
                    <el-switch v-model="role.status" active-value="1" :active-text="$t('message.Table.Enabled')" inactive-value="2" :inactive-text="$t('message.Table.Enabled')" />
                </el-form-item>

            </el-form>
            <!-- 角色权限面板 -->
            <el-tabs v-model="activeName" type="card" class="ajm-role-border-card">
                <el-tab-pane :label="$t('message.RoleMain.resource')" name="functionAuth" class="ajm-border-wrap" style="height: 100%;">
                    <div class="ajm-border-left">
                        <ul>
                            <li v-for="(items, index) in systemList" :key="index" @click="findSystemMenu(items,index)" :class="{'active':items.isActive}">{{items.systemName}}</li>
                        </ul>
                    </div>
                    <div class="role-tab" style="width: calc(100% - 160px);float: right;">
                        <el-tree class="role-tab-tree" v-loading="treeLoading" ref="menuTree" :data="menuNodes"
                                 :props="menuTreeProps" show-checkbox node-key="id" default-expand-all :current-node-key="0"
                                 :highlight-current="true" :expand-on-click-node="false" :default-checked-keys="checkedMenus"
                                 @check-change="permissionCheckChange" :render-content="renderContent" :check-strictly="true">
                        </el-tree>
                    </div>
                </el-tab-pane>
                <el-tab-pane :label="$t('message.RoleMain.range')" name="dataAuth" class="ajm-border-wrap" style="height: 100%;">
                    <el-table :data="list" style="width: 100%" v-loading="dataListLoading">
                        <el-table-column prop="moduleName" :label="$t('message.RoleMain.reModule')" width="200"/>
                        <el-table-column :label="$t('message.RoleMain.viewDate')"><!-- :render-header="renderHeader"-->
                            <template slot-scope="scope">
                                <el-radio-group v-model="scope.row.ruleType.value" :min="1">
                                    <el-radio v-for="item in dataLevelList" :key="item.value" :label="item.value" :value="item.value">
                                        {{item.name}}
                                    </el-radio>
                                </el-radio-group>
                            </template>
                        </el-table-column>
                        <el-table-column width="50">
                            <template slot="header" slot-scope="scope">
                                <el-tooltip :content="$t('message.RoleMain.clue')" placement="top">
                                    <i class="el-icon-ajm-message"></i>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" :loading="saveRoleLoading" @click="saveOrUpdate('roleForm')" v-if="isShow">{{$t('message.save')}}</el-button>
                <el-button size="small" @click="cancelRoleForm">{{$t('message.cancel')}}</el-button>
            </div>
        </el-dialog>
        <!-- 查看用户窗口 -->
        <el-dialog custom-class="ajm-dialog-middle" :title="$t('message.RoleMain.roleUserInfo')" :visible.sync="lookUserFormVisible" width="30%" top="0" :modal-append-to-body="false">
            <div class="ajm-search-form" style="margin: 0;">
                <el-form ref="searchUserForm" :model="searchUserForm" :inline="true">
                    <el-row>
                        <el-col :span="24" class="ajm-search-items">
                            <el-form-item>
                                <el-input class="search-item" v-model="searchUserForm.userName" :placeholder="$t('message.RoleMain.confirmUserName')">
                                </el-input>
                            </el-form-item>
                            <el-form-item class="ajm-search-btns">
                                <el-button icon="el-icon-ajm-search" @click="searchUser"></el-button>
                                <el-button icon="el-icon-ajm-refresh" @click="refreshSearchUser"></el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="ajm-table">
                <el-table ref="filterUserTable" :data="pageDialogResult.list" @filter-change="handleFilterUserChange" v-loading="listUserLoading" tooltip-effect="light" style="width: 100%">
                    <el-table-column type="index" :label="$t('message.Table.index')" width="70" sortable></el-table-column>
                    <el-table-column prop="userName" :label="$t('message.RoleMain.userName')" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="realName" :label="$t('message.RoleMain.name')" :show-overflow-tooltip="true"></el-table-column>
                    <el-table-column prop="status.name" :label="$t('message.Table.status')" width="90" column-key="userStatus" :filters="statusUser" :filter-method="filterUserStatus" :filter-multiple="false"/>
                    <el-table-column :label="$t('message.Table.operate')" width="90" fixed="right">
                        <template slot-scope="scope">
                            <el-tooltip :content="$t('message.RoleMain.move')" placement="top">
                                <el-button type="text" @click="removeRoleUser(scope.$index, scope.row)" v-permission-code="'001002005_BTN'" :disabled="userId == scope.row.userId">
                                    <i class="el-icon-ajm-move"></i>
                                </el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="ajm-pagination-bar">
                <el-pagination background @current-change="goUserChangePageParam" @size-change="goUserChangePageSizeParam" :current-page="pageDialogResult.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageDialogResult.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageDialogResult.total">
                </el-pagination>
            </div>
        </el-dialog>
    </div>

</template>

<script>
import $ from "jquery";

// 角色服务
import roleService from "../services/roleService";
// 资源服务
import resourceService from "../services/resourceService";
// 系统服务
import systemService from '../services/systemService';
//用户服务
import userService from "../services/userService";

export default {
    data() {
        return {
            //默认显示权限类
            activeName: 'functionAuth',
            //数据范围列表
            list:[],
            //修改后数据范围
            dataRuleList:[],
            dataListLoading:false,
            //可选数据范围
            dataLevelList:[{name:this.$t('message.RoleMain.person'),value:1},{name:this.$t('message.RoleMain.all'),value:4}],
            dataChecked:'',
            //弹窗标题
            dialogTitle:'',
            statusRole: [{ text: this.$t('message.Table.Enabled'), value: 1 }, { text: this.$t('message.Table.Unabled'), value: 2 }],
            checkList: [],
            // 列表加载
            listLoading: false,
            // 树加载
            treeLoading: false,
            saveRoleLoading: false,
            roleFormVisible: false,
            //分页结果集
            pageResult: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
                list: []
            },
            // 查询表单
            searchForm: {
                // 角色名
                roleName: "",
                // 手机号码
                roleCode: ""
            },
            // 选择角色集合
            selectedRoles: [],
            // 选择角色ID集合
            selectedRoleIds: [],
            // 角色
            role: {
                roleId: "",
                roleName: "",
                roleCode: "",
                // 状态
                status: {
                    value: ""
                },
                remark: ""
            },
            /*// 角色规则
            roleRules: {
                // 角色名称
                roleName: [
                    {min:1,max:50,message:"长度为1-50字符"},
                    { validator: checkRoleName, trigger: "" }
                ],
                roleCode: [
                    {min:1,max:50,message:"长度为1-50字符"},
                    { validator: checkRoleCode, trigger: "" }
                ]
            },*/
            //菜单树
            menuNodes: [],
            //菜单store
            menuTreeStore: {},
            menuTreeProps: {
                children: "menuNodeList",
                label: "nodeName"
            },
            // 选中按钮
            checkedBtns: [],
            // 选中菜单
            checkedMenus: [],
            editFormIsInit: false,
            userId:this.$store.getters.userInfo.userId,
            permissionCode:this.$store.getters.userInfo.permissionCode,
            status: '',
            sortType: 2,
            //角色用户
            //查询用户配置属性
            searchUserForm: {
                userName: "",
                realName:"",
                roleIds:''
            },
            //查看角色用户弹窗
            lookUserFormVisible:false,
            //用户分页
            pageDialogResult: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
                list: []
            },
            //加载角色用户
            listUserLoading:false,
            //角色用户状态
            userStatus:'',
            statusUser:[{ text: this.$t('message.Table.Enabled'), value: 1 }, { text: this.$t('message.Table.Unabled'), value: 2 }],
            //是否显示弹窗保存按钮
            isShow:false,

            //所有系统列表
            systemList:[],
            //所有系统选中权限
            allCheckedItems:[],
            //所有系统选中按钮权限
            allCheckedBtns:[],
            //上一选中系统
            lastIndex:0,
            //是否修改角色
            isEdit:false,
            //当前修改角色
            currentRoleId:''
        };
    },
    computed:{
        // 角色规则
        roleRules() {
            var checkRoleName = (rule, value, callback) => {
                var roleId = this.role.roleId;
                if (!value) {
                    return callback(new Error(this.$t('message.RoleMain.confirmName')));
                } else {
                    roleService.checkRoleName(roleId, value).then(resp => {
                        if (resp) {
                            callback();
                        } else {
                            return callback(new Error(this.$t('message.RoleMain.hasRoleName')));
                        }
                    });
                }
            };
            var checkRoleCode = (rule, value, callback) => {
                var roleId = this.role.roleId;

                if (!value) {
                    return callback(new Error(this.$t('message.RoleMain.confirmCode')));
                }
                var reg = /^[A-Za-z0-9]+$/;
                if (reg.test(value)) {
                    roleService.checkRoleCode(roleId, value).then(resp => {
                        var result = resp;
                        if (result) {
                            callback();
                        } else {
                            return callback(new Error(this.$t('message.RoleMain.hasRoleName')));
                        }
                    });
                } else {
                    callback(new Error(this.$t('message.RoleMain.checkRoleCode')));
                }
            };
            return{
                // 角色名称
                roleName: [
                    { validator: checkRoleName, trigger: "" }
                ],
                roleCode: [
                    { validator: checkRoleCode, trigger: "" }
                ]
            }
        },
    },
    methods: {
        //获取所有服务类型
        getSystemList(roleId){
            systemService.getSystemList().then(resp =>{
                this.systemList = [];
                resp.forEach((items,indexs) => {
                    items.systemList.forEach((item,index) => {
                        let system = {
                            systemId: item.systemId,
                            systemName:item.systemName,
                            systemCategoryId: item.systemCategoryId,
                            systemCode: item.systemCode,
                            status:item.status,
                            orderNo: item.orderNo,
                            isActive: false,
                        };
                        if(indexs == 0 && index == 0){
                            system.isActive = true;
                        }
                        this.systemList.push(system);
                    });
                });

                if(roleId){
                    this.systemList.forEach((item,system) => {
                        this.loadRoleResourceList(roleId,item.systemCode,system);
                    });
                }else{

                }
                this.loadResourceNodeList(this.systemList[0].systemCode);
                //新增的时候不应该调用查选中菜单
                if(roleId){
                    this.loadRoleResourceList(roleId,this.systemList[0].systemCode);
                }
            })
        },

        //选中系统
        findSystemMenu(item,index){
            this.systemList.forEach((item) => {
                item.isActive = false;
            })
            this.systemList[index].isActive = true;
            this.loadResourceNodeList(item.systemCode);


            var checkedMenus = this.$refs.menuTree.getCheckedKeys();
            var checkBtns = [];
            $("input[name=el-checkbox_btn][checked]").each(function() {
                checkBtns.push(Number($(this).val()));
            });
            var checkedResourceId = checkedMenus.concat(checkBtns);


            if(checkedResourceId){
                this.allCheckedItems[this.lastIndex] = checkedResourceId

                if(checkBtns){
                    this.allCheckedBtns[this.lastIndex] = checkBtns;
                }
            }else{
                this.allCheckedItems[this.lastIndex] = []
            }

            let currentItem = this.allCheckedItems[index];
            let currentBtns = this.allCheckedBtns[index]

            this.lastIndex = index;

            if(currentItem && currentItem !=[]){
                this.checkedMenus = currentItem;
                if(currentBtns){
                    this.checkedBtns = currentBtns;
                    this.loadResourceNodeList(item.systemCode).then(() => {
                        this.clearBtnSelectedStyle();
                        this.addBtnSelectedStyle();
                    });
                }
            }else{
                if(this.isEdit){
                    this.loadRoleResourceList(this.currentRoleId,item.systemCode);
                }
            }
        },

        resetForm(formName) { //重置表单
            if (this.$refs[formName] !== undefined) {
                this.$refs[formName].resetFields();
            }
        },
        handleSortChange(column, prop, order ){
            if(column.order === "ascending"){
                this.sortType=1;
            }else if(column.order === "descending"){
                this.sortType=2;
            }
            this.findRoleListByPage();
        },

        handleFilterChange(filters) {
            this.pageResult.pageNum = 1
            let value = filters.status[0];
            this.status = value;
            this.findRoleListByPage();
        },
        filterStatus(value, row) {
            return row.status.value === value;
        },
        //查询角色分页列表
        findRoleListByPage() {
            //查询角色列表
            this.listLoading = true;
            var params = {
                page: this.pageResult.pageNum,
                rows: this.pageResult.pageSize,
                //角色名称
                roleName: this.searchForm.roleName,
                // 角色编码
                roleCode: this.searchForm.roleCode,
                status:{value:this.status},
                sortType:this.sortType
            };
            // 查询角色分页列表
            roleService.findRoleListByPage(params).then(resp => {
                this.pageResult = resp;
                this.listLoading = false;
            }).catch(() => {
                this.listLoading = false;
            });
        },
        // 加载资源节点列表
        loadResourceNodeList(systemCode) {
            let params = {
                systemCode:systemCode
            }
            return resourceService.findResourceNodeList(params).then(resp => {
                if(resp){
                    this.menuNodes = resp.data || resp;
                }else{
                    this.menuNodes = []
                }
            });
        },
        // 角色集合改变
        roleIdsChange(values) {
            this.selectedRoleIds = [];
            this.selectedRoles = values;
            var $this = this;
            this.selectedRoles.forEach(function(item) {
                $this.selectedRoleIds.push(item.roleId);
            });
        },
        //切换页面
        changePage(page) {
            this.pageResult.pageNum = page;
            this.findRoleListByPage();
        },
        //根据页码切换页面
        handleSizeChange(pageSize) {
            this.pageResult.pageSize = pageSize;
            this.findRoleListByPage();
        },
        // 查询
        search() {
            this.pageResult.pageNum = 1
            this.findRoleListByPage();
        },
        //刷新页面
        refreshSearch(){
            this.searchForm.roleName = '';
            this.pageResult.pageNum = 1
            this.pageResult.pageSize = 10
            this.sortType = 2
            if(this.status){
                this.$refs.filterTable.clearFilter();
                this.status = ''
            }
            this.findRoleListByPage();
        },
        // 添加角色
        goAddRole() {
            this.resetForm("roleForm");
            this.dialogTitle = this.$t('message.RoleMain.addRole')
            this.clearBtnSelectedStyle();
            this.roleFormVisible = true;
            this.isShow = true
            this.role.roleId = ''
            this.role.roleName = ''
            this.role.roleCode = ''
            this.role.remark = ''
            this.role.status= "1";
            this.allCheckedItems = []
            this.allCheckedBtns = []
            this.checkedMenus = [];
            this.checkedBtns = []
            this.isEdit = false
            this.lastIndex = 0
            this.getSystemList()
            this.findModuleList();
        },
        //查询所有模块列表
        findModuleList(){
            roleService.findModuleList().then((resp) => {
                this.list = resp;
                this.list.forEach((item)=>{
                    this.$set(item,'ruleType',{value:1})
                })
            });
        },
        //获取数据范围
        findRoleRules(){
            roleService.findRoleRules().then((resp) => {
                if(resp){
                    this.list = resp;
                }
            });
        },
        //依据Id获取数据范围
        findRoleRulesByRoleId(roleId){
            roleService.findRoleRulesByRoleId(roleId).then((resp) => {
                this.list = resp;
            });
        },
        /*//表头添加图标
        renderHeader(h, { column, $index }){
            return h(
                'div',
                [
                    h('span',{style:'color:#72767a'}, column.label),
                    h('el-tooltip',[
                        h('div',{
                            slot:'content'
                        },"设置角色可查看的数据范围，当用户具备多个角色时，默认按更高的数据范围查看"),
                        h('i', {
                            class:'el-icon-ajm-info',
                            style:'float:right;margin-top: 9px;'
                        })
                    ])
                ]
            );
        },*/
        //执行添加角色
        saveOrUpdate(formName) {
            let _this = this;
            this.saveRoleLoading = true;
            var checkedMenus = this.$refs.menuTree.getCheckedKeys();
            var checkBtns = [];
            $("input[name=el-checkbox_btn][checked]").each(function() {
                checkBtns.push(Number($(this).val()));
            });
            var checkedResourceId = checkedMenus.concat(checkBtns);

            if(checkedResourceId){
                this.allCheckedItems[this.lastIndex] = checkedResourceId
            }

            var allCheckedItems = []

            for (var i = 0;i < this.allCheckedItems.length;i++) {
                if(this.allCheckedItems[i] && this.allCheckedItems[i].length > 0){
                    allCheckedItems = allCheckedItems.concat(this.allCheckedItems[i]);
                }
            }

            let list = this.list;
            _this.dataRuleList = [];
            list.forEach(function (item, index) {
                let rule = '';
                if (item.ruleType.value == 1) {
                    rule = 1;
                }else if(item.ruleType.value == 4){
                    rule = 4;
                }
                _this.dataRuleList.push({
                    moduleId :item.moduleId ,
                    moduleName :item.moduleName ,
                    roleId :item.roleId ,
                    ruleId :item.ruleId ,
                    ruleType:{value:rule}
                });
            });

            var role = this.role;
            var roleVO = {
                roleId: role.roleId,
                roleName: role.roleName,
                roleCode: role.roleCode,
                status: {
                    value: role.status
                },
                remark: role.remark,
                resourceIds: allCheckedItems,
                dataRuleList:_this.dataRuleList
            };

            // 执行表单验证
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (allCheckedItems == []) {
                        this.$message({
                            type: 'warning',
                            message: this.$t('message.RoleMain.confirmRole'),
                            duration:1000
                        });
                        setTimeout(() => {
                            _this.saveRoleLoading = false;
                        }, 1000);
                        return;
                    }
                    //执行添加
                    roleService.saveOrUpdate(roleVO).then(resp => {
                        if (resp.status == 500) {
                            this.$message({
                                message: resp.message,
                                type: "error"
                            });
                        } else {
                            this.$message({
                                type: 'success',
                                message: this.$t('message.saveSuccess')
                            });
                            this.roleFormVisible = false;
                            this.findRoleListByPage();
                            this.$refs.roleForm.resetFields();
                        }
                        this.saveRoleLoading = false;
                    });
                }else {
                    this.saveRoleLoading = false;
                    return false;
                }
            });
        },
        //关闭角色表单弹窗
        closeRoleDialog(done) {
            done();
            this.list = [];
            this.$refs.roleForm.resetFields();
        },
        //取消角色表单保存
        cancelRoleForm() {
            this.roleFormVisible = false;
            this.list = [];
            this.$refs.roleForm.resetFields();
        },
        //角色信息
        showRoleDetail(index, row){
            this.roleFormVisible = true;
            this.editFormIsInit = true;
            this.treeLoading = true;
            var self = this;
            //初始化完毕后将初始化状态设置为false
            setTimeout(() => {
                self.editFormIsInit = false;
                this.treeLoading = false;
            }, 800);
            var roleId = row.roleId;
            this.role.roleId = roleId;
            this.role.roleName = row.roleName;
            this.role.roleCode = row.roleCode
            this.role.status = row.status.value.toString();
            this.role.remark = row.remark;
            this.findRoleRulesByRoleId(roleId);
            this.checkedMenus = [];
            this.checkedBtns = [];
            this.allCheckedItems = []
            this.allCheckedBtns = []
            this.getSystemList(roleId);
            this.currentRoleId = roleId
            this.isEdit = true
            this.lastIndex = 0
        },
        // 编辑角色
        goEditRole(index, row) {
            this.dialogTitle = this.$t('message.edit');
            this.isShow = true;
            this.activeName = 'functionAuth';
            this.showRoleDetail(index, row);
        },
         //查看角色信息
        goSeeRole(index, row){
            this.dialogTitle = this.$t('message.RoleMain.role');
            this.isShow = false;
            this.showRoleDetail(index, row);
        },
        //查看角色用户页面
        goUserChangePageParam(page) {
            this.pageDialogResult.pageNum = page;
            this.findUsersByRoleId();
        },
        //根据角色用户页面页码切换页面
        goUserChangePageSizeParam(pageSize) {
            this.pageDialogResult.pageSize = pageSize;
            this.findUsersByRoleId();
        },
        //  角色用户列表的查询方法
        findUsersByRoleId() {
            this.listUserLoading = true;
            this.lookUserFormVisible = true;
            var params = {
                page: this.pageDialogResult.pageNum,
                rows: this.pageDialogResult.pageSize,
                roleIds: [this.searchUserForm.roleIds],
            };
            if(this.searchUserForm.userName){
                params.userName = this.searchUserForm.userName
            }
            if(this.userStatus){
                params.status = {
                    value: this.userStatus
                }
            }
            userService.findUserListByPage(params).then((resp) => {
                this.listUserLoading = false;
                this.pageDialogResult = resp;
            });
            /*roleService.findUsersByRoleId(params).then((resp) => {
                this.listUserLoading = false;
                this.pageDialogResult = resp.data || resp;
            });*/
        },
        //筛选角色用户
        handleFilterUserChange(filters){
            this.pageDialogResult.pageNum = 1
            this.userStatus = filters.userStatus[0];
            this.findUsersByRoleId();
        },
        //角色用户筛选状态
        filterUserStatus(value,row){
            return row.status.value === value;
        },
        // 执行角色用户页面的搜索
        searchUser() {
            this.pageDialogResult.pageNum = 1
            this.findUsersByRoleId();
        },
        //执行角色用户页面的刷新
        refreshSearchUser(){
            this.pageDialogResult.pageNum = 1
            this.pageDialogResult.pageSize = 10
            this.searchUserForm.userName = ''
            if(this.userStatus){
                this.$refs.filterUserTable.clearFilter();
                this.userStatus = ''
            }
            this.findUsersByRoleId();
        },
        //角色用户页面
        lookUser(index, row) {
            var roleId = row.roleId;
            this.role.roleId = roleId;
            this.lookUserFormVisible = true;
            this.searchUserForm.userName = '';
            this.searchUserForm.realName = '';
            this.searchUserForm.roleIds = row.roleId
            this.findUsersByRoleId();
        },
        //移除用户
        removeRoleUser(index,row){
            var roleId = this.role.roleId;
            this.$confirm(this.$t('message.RoleMain.confirmMove') + "[" + row.userName + "]？", this.$t('message.RoleMain.tips'), {
                confirmButtonText: this.$t('message.confirm'),
                cancelButtonText: this.$t('message.cancel'),
                type: "warning"
            }).then(() => {
                roleService.removeUser(roleId,row.userId).then(resp => {
                    if (resp.status == 500) {
                        this.$message({
                            type: 'error',
                            message: resp.message
                        });
                        return;
                    }
                    this.$message({
                        type: 'success',
                        message: this.$t('message.RoleMain.moveSuccess')
                    });
                    this.findUsersByRoleId();
                });
            }).catch(() => {

            })
        },
        clearBtnSelectedStyle() {
            $("input[name=el-checkbox_btn]:checked").each(function() {
                $(this).attr("checked", false);
            });
            $("span[name=el-checkbox_btn_span]").each(function() {
                $(this).removeClass("is-checked");
            });
        },

        addBtnSelectedStyle() {
            for (var id in this.checkedBtns) {
                var $item = $("#operate_item_" + this.checkedBtns[id]);
                $item.attr("checked", true);
                $("#operate_" + this.checkedBtns[id]).addClass("is-checked");
            }
        },

        // 加载用户角色集合
        loadRoleResourceList(roleId,systemCode,system) {
            let params = {
                systemCode:systemCode,
                roleIds:[roleId]
            }
            var menuIds = [];
            var btnIds = [];
            this.checkedMenus = [];
            this.checkedBtns = [];
            return roleService.findResourceListByResourceRoleVO(params).then(resp => {
                var resourceList = resp.data || resp;
                if (resp.status == 500) {
                    this.$message({
                        type: 'error',
                        message: resp.message
                    })
                }
                //循环角色集合
                resourceList.forEach((resource, index) => {
                    var resourceId = resource.resourceId;
                    var resourceType = resource.resourceType.value;
                    if (resourceType == 1) {
                        menuIds.push(resourceId);
                    } else {
                        /*var $item = $('#operate_item_' + resourceId);
              $item.attr("checked",true);
              $('#operate_' + resourceId).addClass("is-checked");*/
                        btnIds.push(resourceId);
                    }
                });
                this.checkedMenus = menuIds;
                this.checkedBtns = btnIds;

                if( system == 0 || system){
                    this.allCheckedItems[system] = this.checkedMenus.concat(this.checkedBtns)
                    this.allCheckedBtns[system] = this.checkedBtns;

                }
                this.loadResourceNodeList(systemCode).then(() => {
                    this.clearBtnSelectedStyle();
                    this.addBtnSelectedStyle();
                });


            });
        },
        // 删除角色
        deleteRole(index, row) {
            this.$confirm(this.$t('message.confirmRequest') +"[" + row.roleName + "]？", this.$t('message.delClue'), {
                cancelButtonClass:"message-cancel-button",
                confirmButtonText: this.$t('message.confirm'),
                cancelButtonText: this.$t('message.cancel'),
                type: "warning"
            })
                .then(() => {
                    roleService.deleteRoleByRoleId(row.roleId).then(resp => {
                        this.$message({
                            type: 'success',
                            message: this.$t('message.delSuccess')
                        });
                        this.findRoleListByPage();
                        if(resp.status == 500){
                            this.$message({
                                message: resp.message,
                                type: "warning"
                            });
                        }
                    });
                });
        },
        //批量删除角色
        batchDeleteRole() {
            if (this.selectedRoleIds.length > 0) {
                this.$confirm(this.$t('message.confirmBatch'), this.$t('message.confirmDel'), {
                    cancelButtonClass:"message-cancel-button",
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: "warning"
                })
                    .then(() => {
                        roleService.batchDeleteRole(this.selectedRoleIds).then(resp => {
                            // 处理响应结果
                            if(resp.status == 500){
                                this.$message({
                                    message:resp.message,
                                    type:'error'
                                })
                            }else{
                                this.$message({
                                    message:this.$t('message.delSuccess'),
                                    type:'success'
                                })
                                this.findRoleListByPage();
                            }
                        });
                    }).catch(() => {});
            } else {
                this.$message({
                    message: this.$t('message.RoleMain.chooseRole'),
                    type: "error",
                    duration: 1500
                });
            }
        },

        //选中节点
        selectMenuNode(data, node) {
            if (this.selectBtn) {
                this.selectBtn = false;
                return;
            }
            var isChecked = !node.checked;
            var key = node.key;
            if (isChecked) {
                this.addCheckedKeys(key);
            } else {
                this.removeCheckedKeys(key);
            }
        },

        //权限切换
        permissionCheckChange(data, isChecked, subChecked) {
            //如果是在初始化编辑框不执行
            if (this.editFormIsInit == true) {
                return;
            }
            //如果数据是否选择与实际不符则返回
            /*var index = $.inArray(data.id, this.checkedMenus);
        if((index != -1 && !isChecked) ||
                 (index == -1 && isChecked)){
            return;
        }*/
            var store = this.$refs.menuTree.store;
            var node = store.getNode(data.id);

            if (!isChecked) {
                var operateItems = $("#operate_panel_" + data.id + " .el-checkbox__input");
                var operateCheckedItems = $("#operate_panel_" + data.id + " input");
                operateItems.removeClass("is-checked");
                operateCheckedItems.attr("checked", false);
                this.selectBtn = false;

                // 取消子节点选中
                if (!subChecked) {
                    this.cancelCheckedChildNodes(node);
                }

                // 取消选中父
                if (node.parent.level > 0 && node.parent.checked) {
                    this.cancelCheckedParentNode(node);
                    this.currentLevel = node.level;
                } else {
                    this.currentLevel = null;
                }
            } else {
                if (!this.selectBtn) {
                    var operateItems = $("#operate_panel_" + data.id + " .el-checkbox__input");
                    var operateCheckedItems = $("#operate_panel_" + data.id + " input");
//                    if(this.selectBtn){//20180710 选中子节点后 父节点默认加上is-checked
                        operateItems.addClass("is-checked");
                        operateCheckedItems.attr("checked", true);
//                    }
                } else {
                    this.selectBtn = false;
                }

                // 大于当前层级的 不执行选中子节点
                if (this.currentLevel && node.level < this.currentLevel) {
                    if (node.level == this.currentLevel - 1) {
                        this.currentLevel = null;
                    }
                    return false;
                }

                // 选中父
                if (node.parent.level > 0 && !node.parent.checked) {
                    this.checkedParentNode(node);
                    this.currentLevel = node.level;
                } else {
                    this.currentLevel = null;
                }

                // 选中子菜单
                this.checkedChildNodes(node);
            }
        },

        // 选中父节点
        checkedParentNode(node) {
            var level = node.parent.level;
            if (level == 0) {
                this.currentLevel = null;
                return false;
            }

            var data = node.parent.data;

            var store = this.$refs.menuTree.store;
            var parentNode = store.getNode(data.id);
            if (parentNode) {
                this.addCheckedKeys(parentNode.key);
                this.checkedParentNode(parentNode);
            }
        },

        // 选中所有子节点
        checkedChildNodes(node) {
            var childNodes = node.childNodes;
            if (!childNodes || childNodes.length <= 0) {
                return false;
            }
            // 迭代子节点
            childNodes.forEach(child => {
                var key = child.key;
                this.addCheckedKeys(key);
                this.checkedChildNodes(child);
            });
        },

        //取消选中父节点
        cancelCheckedParentNode(node) {
            var level = node.parent.level;
            if (level <= 0) {
                return false;
            }
            var store = this.$refs.menuTree.store;
            var data = node.parent.data;

            var parentNode = store.getNode(data.id);
            var childNodes = parentNode.childNodes;
            if (!childNodes || childNodes.length <= 0) {
                return false;
            }

            var isChecked = false;
            childNodes.forEach(child => {
                isChecked = isChecked || child.checked;
            });

            if (!isChecked) {
                this.removeCheckedKeys(data.id);
            }
        },

        // 取消选中子节点
        cancelCheckedChildNodes(node) {
            var childNodes = node.childNodes;
            if (!childNodes || childNodes.length <= 0) {
                return false;
            }
            var checkedKeys = this.$refs.menuTree.getCheckedKeys();
            childNodes.forEach(child => {
                var key = child.key;
                var index = $.inArray(key, checkedKeys);
                if (index != -1) {
                    checkedKeys.splice(index, 1);
                    this.$refs.menuTree.setCheckedKeys(checkedKeys);
                }
            });
        },

        //移除选中key
        removeCheckedKeys(key) {
            var checkedKeys = this.$refs.menuTree.getCheckedKeys();
            var index = $.inArray(key, checkedKeys);
            if (index != -1) {
                checkedKeys.splice(index, 1);
                this.$refs.menuTree.setCheckedKeys(checkedKeys);
            }
        },

        //添加选中key
        addCheckedKeys(key) {
            var checkedKeys = this.$refs.menuTree.getCheckedKeys();
            if ($.inArray(key, checkedKeys) != -1) {
                return false;
            }
            checkedKeys.push(key);
            this.$refs.menuTree.setCheckedKeys(checkedKeys);
        },

        //渲染
        renderContent: function(createElement, { node, data, store }) {
            var self = this;
            this.menuTreeStore = store;

            var elements = [];

            var btnNodeList = data.btnNodeList;
            if (btnNodeList) {
                var btnNode = null;
                for (var i = 0; i < btnNodeList.length; i++) {
                    btnNode = btnNodeList[i];
                    elements.push(
                        this.createOperateElement(self, createElement, btnNode)
                    );
                }
            }

            //操作面板
            var operatePanel = createElement(
                "div",
                {
                    attrs: {
                        class: "tree-operate-panel",
                        id: "operate_panel_" + data.id
                    }
                },
                elements
            );

            //显示标题
            var label = createElement(
                "span",
                {
                    on: {
                        click: function() {
                            self.selectMenuNode(data, node);
                        }
                    }
                },
                node.label
            );

            return createElement("span", [label, operatePanel]);
        },
        // 创建操作按钮
        createOperateElement(self, createElement, btnNode) {
            var spanInnerEle = createElement("span", {
                attrs: {
                    class: "el-checkbox__inner el-checkbox__input"
                }
            });

            var inputEle = createElement("input", {
                attrs: {
                    class: "el-checkbox__original",
                    name: "el-checkbox_btn",
                    type: "checkbox",
                    value: btnNode.id,
                    id: "operate_item_" + btnNode.id
                },
                on: {
                    click: function(event) {
                        self.selectBtn = true;
                        var $item = $("#operate_item_" + btnNode.id);
                        var isChecked = !$item.attr("checked");
                        $item.attr("checked", isChecked);
                        if (isChecked) {
                            $("#operate_" + btnNode.id).addClass("is-checked");

                            self.addCheckedKeys(btnNode.parentNodeId);
                            //self.checkedBtns.push(btnNode.id);
                        } else {
                            $("#operate_" + btnNode.id).removeClass(
                                "is-checked"
                            );

                            self.removeCheckedKeys(btnNode.id);
                            //this.checkedBtns.pop(btnNode.id);
                        }
                        // 选择
                        /*if(isChecked){
                  self.addCheckedKeys(btnNode.parentNodeId);
                }*/
                    }
                }
            });

            var spanInputEle = createElement(
                "span",
                {
                    attrs: {
                        class: "el-checkbox__input",
                        name: "el-checkbox_btn_span",
                        id: "operate_" + btnNode.id
                    }
                },
                [spanInnerEle, inputEle]
            );

            var spanLabelEle = createElement(
                "span",
                {
                    attrs: {
                        class: "el-checkbox__label"
                    }
                },
                btnNode.nodeName
            );

            // label 父标签
            var labelEle = createElement(
                "label",
                {
                    attrs: {
                        class: "tree-operate el-checkbox"
                    }
                },
                [spanInputEle, spanLabelEle]
            );
            return labelEle;
        }
    },
    //初始化
    mounted() {
        //查询角色列表
        this.findRoleListByPage();
        let self = this;
        document.getElementById("enterSearch").addEventListener("keydown", function (event) {
            if (event.keyCode === 13) {
                self.search(event);
            }
        }, false);
    }
};
</script>
<style lang="less" scoped>
    .role-tab{
        width: 100%;
        overflow: auto;
        height: 100%;
        .role-tab-tree{
            border: none;
            min-width: 100%;
            display: inline-block !important;
        }
    }
    .ajm-border-left{
        width: 160px;
        height: 100%;
        display: inline-block;
        overflow: auto;
        ul{
            width:100%;
            border-right: 1px solid #EBEBEB;
            height:100%;
        }
        li {
            height: 40px;
            line-height: 40px;
            text-align: center;
            border-bottom: 1px solid #ebeef5;
            background-color: #F2F5F7;

        }
        li.active{
            background-color: #fff;
            color: #007DEB;
            margin-right: -1px;
        }
        li:hover{
            background-color: #E8F3FC;
            cursor: pointer;
        }
        li.active:hover{
            background-color: #fff;
        }
    }
</style>
