<template>
    <el-container>
        <!-- 角色列表 -->
        <el-aside width="300px">
            <el-scrollbar > 
                <el-select  v-model="selectNAme" filterable placeholder="搜索" style="width:94%; margin-top: 5px" @change="selectRoleNAme">
                    <el-option key="0" label="全部" value=""></el-option>
                    <el-option
                      v-for="item in rolelist"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name"
                      >
                    </el-option>
                </el-select>

                <el-table style="width: 100%" 
                    :data="rolelist"
                    @row-click="selectRow" 
                    :row-style="rowStyle" 
                    >
                    <el-table-column prop="name" label="角色名称" >
                        <template slot-scope="{ row }">
                            <div class="roleTitle "  @click="setupEmpower(row)">{{row.name}}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="state" label="状态" align="center">
                        <template slot-scope="{ row }">
                            <el-switch
                                @change="systemRoleState(row)"
                                v-model="row.istrue"
                                active-color="#13ce66"
                                inactive-color="#ff4949">
                            </el-switch>
                        </template>
                        
                    </el-table-column>
                    <el-table-column fixed="right" prop="name" label="操作" width="100" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" @click="editcont(scope.row)" size="small">编辑</el-button>
                            <el-button type="text" @click="delcont(scope.row)" size="small">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <el-button type="primary" @click="addSystemRole" icon="el-icon-plus" style="width:94%; margin: 15px 0 15px 0;">添加角色</el-button>

            </el-scrollbar>
        </el-aside>
        <el-main>

            <!--头部系统页面-->
            <el-row>
                <el-col :span="24">
                    <div>
                        <el-radio-group v-model="choiceSystem" size="medium" @change="systemChange">
                            <el-radio-button :label="sysItem.coder" v-for="(sysItem,sysIndex) in systemList" :key="sysIndex">{{sysItem.title}}</el-radio-button>
                        </el-radio-group>
                    </div>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" class="xxCard">

                    <el-radio-group v-model="viewRange" size="small">
                        <el-radio-button label="1">本岗位</el-radio-button>
                        <el-radio-button label="2">本部门</el-radio-button>
                        <el-radio-button label="3">本分部</el-radio-button>
                        <el-radio-button label="4" disabled>指定行政组织</el-radio-button>
                        <el-radio-button label="5">所有</el-radio-button>
                    </el-radio-group>

                </el-col>
            </el-row>
            <el-scrollbar style="max-height:90%">
                <el-table
                    :data="systemRoleMenuList"
                    style="width: 100%;margin-bottom: 20px;"
                    row-key="id"
                    border
                    default-expand-all
                    :tree-props="{children: 'child', hasChildren: 'hasChildren'}">
                    <el-table-column
                    label="菜单名称"
                    >
                        <template slot-scope="{ row }">
                            <el-checkbox   v-model="row.istrue" :label="row.name" @change="menuSelect(row)"></el-checkbox>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                    >
                        <template slot-scope="{ row }">
                            <el-checkbox v-model="mItem.istrue"  v-for="(mItem,mIndex) in row.menuOperation" :label="mItem.name" :key="mIndex" @change="menuOperationSelect(row,mItem)"></el-checkbox>
                        </template>
                    </el-table-column>
                </el-table>
                
                
                <div style="margin: 2px 0 20px 0;">
                    <el-button type="primary" :loading="buttonLoading" @click="subewport">确定授权</el-button>
                </div>
            </el-scrollbar>









            <!--新增角色-->
            <el-dialog :close-on-click-modal="false" :visible.sync="addDialogForm" :before-close="closeAddDialog" title="新增" width="30%">
                <el-form ref="addForm" :model="addDiaFormDatal" :rules="addrules" label-width="80px" >
                    <el-form-item label="角色名称" prop="name">
                        <el-input  v-model="addDiaFormDatal.name" autocomplete="off" placeholder="请输入角色名称" />
                    </el-form-item>
                    <el-form-item label="排序" >
                        <el-input-number v-model="addDiaFormDatal.sort" controls-position="right" :min="1" :max="999999999999" value="50" placeholder="请输入序号" ></el-input-number>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer"> 
                    <el-button size="small" @click="closeAddDialog">取 消</el-button>
                    <el-button size="small" type="primary" @click="enterAddDialog">确 定</el-button>
                    </div>
                </template>
            </el-dialog>

            <!--编辑角色-->
            <el-dialog :close-on-click-modal="false" :visible.sync="editDialogForm" :before-close="closeEditDialog" title="新增" width="30%">
                <el-form ref="editForm" :model="editSystemRoleCont" :rules="addrules" label-width="80px" >
                    <el-form-item label="角色名称" prop="name">
                        <el-input  v-model="editSystemRoleCont.name" autocomplete="off" placeholder="请输入角色名称" />
                    </el-form-item>
                    <el-form-item label="排序" >
                        <el-input-number v-model="editSystemRoleCont.sort" controls-position="right" :min="1" :max="999999999999" value="50" placeholder="请输入序号" ></el-input-number>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer"> 
                    <el-button size="small" @click="closeEditDialog">取 消</el-button>
                    <el-button size="small" type="primary" @click="enterEditDialog">确 定</el-button>
                    </div>
                </template>
            </el-dialog>


        </el-main>
    </el-container>
</template>

<script>
import { getRoleList,editRoleCont,addRoleCont,editRoleInfo,getsystemlist,getSystemRoleMenuThree,editRolePower } from "@/api/systemaccredit/systemapi";  //行政组织相关
import { MessageBox, Message } from 'element-ui'
export default {
    data() {
        return {
            tablename:"",
            roleid:"",
            addDialogForm:false,    //现在角色框架
            editDialogForm:false, //编辑角色框架
            selectNAme:"",  //要搜索的角色名称
            rolelist:[],            //角色列表
            addDiaFormDatal:{
                name:"",
                sort:50
            },  //角色对象
            // 添加时验证规则
            addrules: {
                name: [{ required: true, message: '必填', trigger: 'blur' }],
            },
            editSystemRoleCont:{
                id:"",
                name:"",
                sort:50
            },
            viewRange:2,    //查看范围
            buttonLoading:false,
            choiceSystem:'kpi',
            systemList:[],
            systemRoleMenuList:[],  //  系统菜单
        }
    },
    created() {
        this.getRoleList()
        this.systemInit()
    },
    methods: {
        //获取角色列表
        async getRoleList(){
            const from = {
                name: this.selectNAme,
            };
            const res = await getRoleList(from);
            this.rolelist = res.data
            console.log("获取角色列表----》",res.data)
        },
        
        //搜索角色
        selectRoleNAme(){
            this.getRoleList()
        },
        //添加角色
        addSystemRole(){
            this.addDialogForm = true
        },
        // 添加框关闭
        closeAddDialog() {
            this.initAddForm()
            this.editSystemRoleCont.sort=50
            this.addDialogForm = false
        },
        // 重置添加表单
        initAddForm() {
            this.$refs.addForm.resetFields()
            this.editSystemRoleCont = {
                name:"",
                sort:50
            }
        },
        //提交添加数据
        enterAddDialog(){
            this.$refs.addForm.validate(async valid => {
                if (valid) {
                    this.addDiaFormDatal.sort =parseInt(this.addDiaFormDatal.sort)
                    const res = await addRoleCont(this.addDiaFormDatal)
                    if (res.code === 0) {
                        this.$message({
                            type: 'success',
                            message: '添加成功',
                            showClose: true
                        })
                    }
                    this.getRoleList();
                    this.closeAddDialog();
                }
            })
        },
        //编辑角色
        editcont(data){
            this.editDialogForm = true
            this.editSystemRoleCont = {
                id:data.id.toString(),
                name:data.name,
                sort:data.sort
            }
        },
        // 编辑框关闭
        closeEditDialog() {
            this.iniEditForm()
            this.addDiaFormDatal.sort=50
            this.editDialogForm = false
        },
        // 重置编辑表单
        iniEditForm() {
            this.$refs.editForm.resetFields()
            this.editSystemRoleCont = {
                id:"",
                name:"",
                sort:50
            }
        },
        //提交编辑角色表单
        enterEditDialog(){
            this.$refs.editForm.validate(async valid => {
                if (valid) {
                    this.editSystemRoleCont.sort =parseInt(this.editSystemRoleCont.sort)
                    this.editSystemRoleCont.id = this.editSystemRoleCont.id.toString()
                    const res = await editRoleInfo(this.editSystemRoleCont)
                    if (res.code === 0) {
                        this.$message({
                            type: 'success',
                            message: res.msg,
                            showClose: true
                        })
                    }
                    this.getRoleList();
                    this.closeEditDialog();
                }
            })
        },
        //删除角色
        delcont(data){
            this.$confirm('此操作将永久删除该角色, 是否继续操作?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {

                const delfrom = {
                    id: data.id.toString(),
                    state:3,
                    istrue:2
                };
                this.delSystemRoleCont(delfrom)
            });
        },
        //执行删除操作
        async delSystemRoleCont(data){
            const res = await editRoleCont(data);
            if (res.code === 0) {
                this.$message({
                    type: 'success',
                    message: res.msg,
                    showClose: true
                })
            }
            this.getRoleList();
        },
        //编辑角色状态
        async systemRoleState(data){
            console.log("编辑角色状态----》",data)
            let stateVal = 1;
            if(!data.istrue){
                stateVal = 2;
            }
            const from = {
                id: data.id.toString(),
                state:stateVal,
                istrue:2
            };
            const res = await editRoleCont(from);
            if(res.code != 0){
                data.istrue = !data.istrue
            }
            console.log("编辑角色状态返回----》",res)
        },
        //配置授权
        setupEmpower(data){
            console.log("配置授权----》",data)
            this.roleid = data.id
            this.getAboutSystemMenu()
        },
        //初始话要授权的系统
        async systemInit(){
            const from = {
                page: 1,
                pagesize: 100000,
            };
            const res = await getsystemlist(from);
            console.log("初始话要授权的系统----》",res.data)
            this.systemList = res.data.list
            if(res.data.list.length > 0){
                this.choiceSystem = res.data.list[0].coder
            }
            this.getAboutSystemMenu();      //系统菜单初始化
        },
        //选择系统
        systemChange(val){
            console.log("选择系统-----》",val)
            this.choiceSystem = val
            this.getAboutSystemMenu()
        },
        //获取相关系统菜单
        async getAboutSystemMenu(){
            const from = {
                name: this.choiceSystem,
                roleid:this.roleid.toString(),
            };
            const res = await getSystemRoleMenuThree(from);
            console.log("系统菜单树-----》",res)
            res.data.forEach(item =>{
                // console.log("系统菜单树-----》",item)
            })
            this.systemRoleMenuList = res.data;
        },
        //提交授权
        async subewport(){
            this.buttonLoading = true
            console.log("提交授权-----》",this.systemRoleMenuList)
            this.viewRange =parseInt(this.viewRange)
            const from = {
                systemname: this.choiceSystem,
                roleid:this.roleid.toString(),
                level:this.viewRange,
                power:this.systemRoleMenuList
            };
            const res = await editRolePower(from);
            console.log("系统菜单树-----》",res)
            if (res.code != 0){
                this.buttonLoading = false
            }else{
                Message({
                    message: res.msg || 'success',
                    type: 'success',
                    duration: 5 * 1000
                })
                this.buttonLoading = false
                // this.roleid=0
                this.viewRange = 2
                this.postList = []
                this.systemInit();      //系统初始化
            }
        },


        //菜单级操作
        menuSelect(val){
            // console.log("菜单级操作-----》",val)
            if(val.menuOperation){
                val.menuOperation.forEach(item =>{
                    item.istrue = val.istrue
                })
            }
            if(val.child){
                this.menuSunDigui(val.child,val.istrue)
            }
            if(val.parentid != "0"){
                this.menuParentDigui(val.parentid,val.istrue)
            }
        },
        //菜单子递归
        menuSunDigui(childList,enterClick){
            if(childList){
                childList.forEach(cItem=>{
                    cItem.istrue = enterClick
                    if(cItem.menuOperation){
                        cItem.menuOperation.forEach(cmitem =>{
                            cmitem.istrue = enterClick
                        })
                    }
                    this.menuSunDigui(cItem.child,enterClick)
                })
            }else{
                return
            }
        },
        //菜单上级递归
        menuParentDigui(parentId,enterClick){
            // console.log("菜单上级递归===>",parentId,enterClick);
            if (parentId == "0") return;
            if(enterClick == true){

            }
            let listAry = this.getParentId(this.systemMenuList,parentId,enterClick)
            // console.log("菜单上级递归==list==>",listAry);
        },
        
        getParentId(list,id,enterClick) {
            for (let i in list) {
                // console.log("菜单上级递归==1==>",list[i].id,id);
                if(list[i].id===id){
                    if(enterClick == true){
                        list[i].istrue = enterClick
                    }else{
                            if(list[i].child){
                                let falseNum = 0
                                list[i].child.forEach(lcItem =>{
                                    if(lcItem.istrue){
                                        falseNum++
                                    }
                                })
                                if(falseNum <=0){
                                    list[i].istrue = enterClick
                                }
                            }else{
                                list[i].istrue = enterClick
                            }
                        }
                    // console.log("菜单上级递归==2==>",list[i],id);
                    return [list[i]]
                }
                if(list[i].child!=null){
                    let node = this.getParentId(list[i].child,id,enterClick);
                    if(node!==undefined){
                        if(enterClick == true){
                            list[i].istrue = enterClick
                        }else{
                            if(list[i].child){
                                let falseNum = 0
                                list[i].child.forEach(lcItem =>{
                                    if(lcItem.istrue){
                                        falseNum++
                                    }
                                })
                                if(falseNum <=0){
                                    list[i].istrue = enterClick
                                }
                            }else{
                                list[i].istrue = enterClick
                            }
                        }
                        
                        // console.log("菜单上级递归==3==>",list[i],id);
                        return node.concat(list[i])
                    }
                }
            }
        },
        

        //按钮级操作
        menuOperationSelect(val,mation){
            if (mation.istrue){
                val.istrue = mation.istrue
            }else{
                var jiBuqian = 0
                val.menuOperation.forEach(item =>{
                    if(!item.istrue){
                        jiBuqian++;
                    }
                })
                if(jiBuqian == val.menuOperation.length){
                    val.istrue = false
                }
            }
            let listAry = this.getParentId(this.systemMenuList,val.parentid,mation.istrue)
        },
        //表格操作
        // 行鼠标点击事件
        selectRow(row, column, event) {
            console.log(row);
            console.log(column);
            console.log(event);
            this.tablename = row.name;
        },
        // 更改选中行背景色
        rowStyle({ row }) {
            console.log("更改选中行背景色",row);
            if (this.tablename === row.name) {
                return { 'background-color': '#F56C6C', cursor: 'pointer' };
            }
            return { cursor: 'pointer' };
        },



        








    }
}
</script>
<style>
    .el-aside {
        text-align: center;
        height: calc(103% - 2px);
        overflow: hidden;
        overflow-y: auto;
        overflow-x: hidden;
        border-right: 1px solid rgb(220, 223, 230);
        margin: 2px 0 0 0;
        padding-bottom: 10px;
    }
    .el-main{
        height: 105%;
    }
    .el-container {
        height:calc(100% - 50px);
        overflow: hidden;
    }
    .el-scrollbar {
        height: 100%;
    }
    .el-scrollbar__wrap {
        overflow: hidden;
        overflow-y: auto;
        overflow: scroll;
    }
    .xxCard{
        
        padding: 10px 0;
    }
    .roleTitle{
        color: #409EFF;
        cursor: pointer;
    }

    .el-table__row:hover > td {
      background-color: transparent;
    }

</style>