<template>
    <div class="authManage_container">
        <div class="auth_cont_top">
            <div>
                <span>{{$t('SystemManage.RoleManage.role_name')}}：</span>
                <span>{{Role.RoleName}}</span>
                <!-- <el-select v-model="role" placeholder="请选择角色" style="width:360px;marginLeft:30px;">
                    <el-option v-for="item in roleList" :key="item.RoleId" :label="item.RoleName" :value="item.RoleId">
                    </el-option>
                </el-select> -->
            </div>
            <el-button style="margin-left:auto;marginRight:50px;width:140px;" @click="$router.back()" v-if="!isLook">{{$t('Dialog.cancel_btn')}}
            </el-button>
            <el-button type="primary" style="marginRight:50px;width:140px;" @click="saveAuth" v-if="!isLook">{{$t('Dialog.confirm_save_btn')}}
            </el-button>
        </div>
        <div class="auth_bot">
            <div class="menu_auth_cont">
                <h3 style="color:#333;fontSize:14px;">{{$t('SystemManage.RoleManage.permission_set')}}</h3>
                <div class="auth-wrap">
                    <el-tree ref="checkboxTree" :data="authList" :props="{label:'Name',children:'Children',disabled:'Disabled'}"
                        :default-expand-all="false" show-checkbox node-key="MenuId"
                        :default-checked-keys="defaultCheckedKeys">
                    </el-tree>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {departInterence} from '@/api/api.js';
export default {
    name: '',
    components: {},
    data() {
        return {
            role: '', //角色
            roleList: [], //角色列表
            authList: [], //权限列表
            defaultCheckedKeys: [],
            loading: null, //loading
            isLook: false, //是否仅查看
            Role:{},//角色
            checkList:[],//角色应勾选的list
        };
    },
    watch: {
        // 监测角色改变对应的权限也改变
        role() {
            this.loading = this.$loading({
                lock: true,
                target: '.authManage_container',
                text: '切换角色中...',
                spinner: 'el-icon-loading',
                background: 'rgba(255, 255, 255, 0.8)'
            });
            this.getAuthList();
        }
    },
    methods: {
        /* 获取已有角色列表 */
        getRoles() {
            departInterence.getRole().then(res => {
                if (res.Ret === 200) {
                    this.roleList = res.Data.List||[];
                    if (res.Data.List.length && !this.role) {
                        this.role = res.Data.List[0].RoleId
                    } 
                    this.Role = this.roleList.find(i=>i.RoleId===this.role)||{}
                }
            })
        },
        /* 根据角色id获取已有权限 */
        getAuthList() {
            departInterence.getRoleAuth({
                RoleId: Number(this.role)
            }).then(res => {
                if (res.Ret !== 200) return
                this.loading && this.loading.close()
                if (!res.Data) return
                const {
                    List,
                    ChoiceList = [],
                    HalfChoiceList = []
                } = res.Data
                this.authList = List || []
                this.checkList = ChoiceList
                /* this.defaultCheckedKeys = ChoiceList.filter((item) => !HalfChoiceList.some((halfItem) =>
                    item === halfItem)) */
                const type = this.isLook?'all':''
                this.$nextTick(()=>{
                    this.authList.forEach(l=>{
                        this.formatTree(l,type)
                        })
                    this.defaultCheckedKeys=this.checkList
                })
                
            })
        },
        // 保存
        saveAuth() {
            const keys = this.$refs.checkboxTree.getCheckedKeys()
            const halfKeys = this.$refs.checkboxTree.getHalfCheckedKeys()
            if(!keys.length&&!halfKeys.length){
                this.$message.warning(this.$t('SystemManage.RoleManage.set_permission_msg01'))
                return
            }
            const ChoiceList = Array.from(new Set([...keys,...halfKeys]))
            departInterence.saveRoleAuth({
                RoleId:Number(this.role),
                MenuIds:ChoiceList,
                HalfMenuIds:halfKeys
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success(this.$t('SystemManage.RoleManage.set_permission_success'))
                // this.$router.back()
            })
        },
        formatTree(data,type){
            if(/* data.MenuType===2|| */type==='all'){
                data.Disabled = true
            }
            //非叶子节点递归
            if(data.Children && data.Children.length){
                data.Children = data.Children.map(i=>{
                    return this.formatTree(i,type)
                })
            }
            if(!data.Children||data.Children&&data.Children.length===0){
                //叶子节点向上检查MenuId
                this.checkDataList(data)
            }
            return data
        },
        //根据MenuId找到对应节点
        findTreeNode(MenuId){
            return this.$refs.checkboxTree.getNode(MenuId)
        },
        checkDataList(data){
            //获取data的MenuId 和 checkList对比 
            //如果MenuId不在checkList里，检查data.ParentId在不在checkList里，若在，则从checkList里去除
            if(!this.checkList.includes(data.MenuId)&&this.checkList.includes(data.ParentId)){
                const index = this.checkList.indexOf(data.ParentId)
                index!==-1&&this.checkList.splice(index,1)
                console.log('应该去除的节点',data.ParentId)
            }
            //向上检查MenuId
            const parentNode = this.findTreeNode(data.ParentId)
            if(parentNode){
                this.checkDataList(parentNode.data)
            }
        }
    },
    created() {
        if (this.$route.query.id) {
            this.role = Number(this.$route.query.id);
            //this.isLook = true;
        }
    },
    mounted() {
        this.getRoles();
    },
}
</script>
<style lang='scss'>
.authManage_container {
    * {
        box-sizing: border-box;
    }
    .auth_cont_top {
        font-size: 16px;
        color: #333;
        display: flex;
        // justify-content: space-between;
        align-items: center;
        border: 1px solid #ECECEC;
        padding: 20px 30px;
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
        justify-content: space-between;
    }

    .auth_bot {
        min-height: calc(100vh - 224px);
        padding: 30px;
        background: #fff;
        margin-top: 20px;
        position: relative;
        border: 1px solid #ECECEC;
        border-radius: 4px;
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);

        .el-tree {
            border-top: 1px solid #E5E7ED;
            border-left: 1px solid #E5E7ED;
            border-right: 1px solid #E5E7ED;
            width: 98%;
            margin-bottom: 40px;

            .el-tree-node__label {
                margin: 10px;
            }

            .el-tree-node__content {
                min-width: 200px;
                width: 200px;
                white-space: normal;
                box-sizing: border-box;
            }

            .el-tree-node {
                .el-tree-node {
                    .el-tree-node__children {
                        width: 100%;
                    }

                    .el-tree-node {
                        &:not(:first-child) {
                            /* .el-tree-node__content{
                        border-right: 1px solid #E5E7ED;
                    } */
                            border-top: 1px solid #E5E7ED;
                        }

                        .el-tree-node__content {
                            border-right: 1px solid #E5E7ED;
                        }
                    }

                }
            }

            .el-tree-node__content {
                padding: 5px 10px !important;
                height: auto;

                .el-tree-node__expand-icon.el-icon-caret-right {
                    //display: none;
                }
            }

            >.el-tree-node {
                padding: 0 !important;
                display: flex;
                border-bottom: 1px solid #E5E7ED;

                >.el-tree-node__children {
                    width: 100%;

                    >.el-tree-node {
                        &:not(:first-child) {
                            border-top: 1px solid #E5E7ED;
                        }

                        >.el-tree-node__content {
                            border-left: 1px solid #E5E7ED;
                            border-right: 1px solid #E5E7ED;
                        }
                    }
                }
            }

            .el-tree-node__children {
                display: flex;
                flex-direction: column;

                .el-tree-node {
                    display: flex;
                    flex:1;
                    padding: 0px !important;

                    .el-tree-node__content {
                        border-bottom: none;

                        .custom-tree-node {
                            height: 24px;
                            display: flex;
                            align-items: center;

                            .tree-btn {
                                margin-left: 10px;
                                display: none;
                            }

                            .el-button {
                                padding: 0px !important;
                                border-radius: 4px;
                                background: #363554;
                                color: #ffffff;
                            }
                        }
                    }

                    .el-tree-node__children {
                        .el-tree-node {
                            &:not(:first-child) {
                                .el-tree-node__content {
                                    //border-left: none;
                                }
                            }
                        }
                    }
                }
            }
        }
        .auth-wrap{
            margin-top: 20px;
        }
    }
}
</style>