<template>
    <el-dialog :title="type === 'add' ? '添加角色' : '修改角色'" top="10vh" :visible.sync="dialogVisible" width="900px" id="userDialog">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px" class="demo-ruleForm">
            <el-form-item label="角色名" prop="name">
                <el-input style="width: 350px" v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="可使用的菜单" prop="menu">
                <el-tree ref="tree" :data="menuList" show-checkbox node-key="id" :default-expand-all="true" :props="defaultProps"> </el-tree>
            </el-form-item>
        </el-form>
        <div slot="footer">
            <el-button size="small" @click="dialogVisible = false">取 消</el-button>
            <el-button size="small" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";
import { updateRoleMenu, createRoleMenu, queryMenu } from "@/api/system/persagy-sso-server";

export default {
    components: {},
    props: {
        type: String, // 新增/编辑(add/edit)
    },
    data() {
        return {
            dialogVisible: false,
            menuList: [],
            defaultProps: {
                children: "menuChildrens",
                label: "name",
            },
            changeData: null,
            ruleForm: {
                name: "",
            },
            rules: {
                name: [
                    { required: true, message: "请输入用户名", trigger: "blur" },
                    { max: 16, message: "长度不得超过16个字符", trigger: "blur" },
                ],
            },
        };
    },
    computed: {
        ...mapGetters("layout", ["projectId", "projects"]),
        projectList() {
            return this.projects.map((item) => {
                item.key = item.id;
                item.label = item.name;
                return item;
            });
        },
    },
    created() {},
    methods: {
        // 显示弹窗
        async showDialog(type, data) {
            await this.getMenuTree();
            if (data && type === "edit") {
                setTimeout(() => {
                    this.changeData = data;
                    let { name, menuList } = data;
                    this.ruleForm.name = name;
                    this.$refs.tree && this.$refs.tree.setCheckedNodes(menuList);
                })
            } else {
                setTimeout(() => {
                    this.changeData = null;
                    this.ruleForm.name = "";
                    this.$refs.tree && this.$refs.tree.setCheckedNodes([]);
                });
            }
            this.dialogVisible = true;
        },
        /**
         * 查询全部菜单树
         */
        async getMenuTree() {
            const res = await queryMenu();
            if (res.code === "Success" && res.data && res.data.length) {
                this.menuList = res.data;
            } else {
                res.data = [];
            }
        },
        /**
         * 提交用户信息
         */
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    // 修改
                    if (this.type === "edit" && this.changeData.id) {
                        let params = {
                            data: {
                                id: this.changeData.id,
                                name: this.ruleForm.name,
                                listMenu: this.$refs.tree.getCheckedNodes(true, true),
                            },
                        };
                        const res = await updateRoleMenu(params);
                        if (res.code === "Success") {
                            this.$message.success("角色修改成功！");
                            this.dialogVisible = false;
                            this.$emit("refresh");
                        } else {
                            this.$message.error(`角色修改失败，失败原因：${res.message}`);
                        }
                    } else {
                        // 添加
                        const params = {
                            data: {
                                name: this.ruleForm.name,
                                listMenu: this.$refs.tree.getCheckedNodes(true, true),
                            },
                        };
                        const res = await createRoleMenu(params);
                        if (res.code === "Success") {
                            this.$message.success("角色添加成功！");
                            this.dialogVisible = false;
                            this.$emit("refresh");
                        } else {
                            this.$message.error(`角色添加失败，失败原因：${res.message}`);
                        }
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
    },
};
</script>
<style lang="less" scoped>
#userDialog {
    /deep/ .el-dialog__body {
        max-height: 550px;
        overflow-y: auto;
    }
    /deep/ .el-transfer__button:first-child {
        margin-bottom: 0;
    }
}
</style>
