<template>
    <el-dialog :title="dialogTitle" :visible.sync="show" destroy-on-close :before-close="onClose">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="角色名称：" prop="name">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="角色描述：" prop="describle">
                <el-input type="textarea" v-model="form.describle" :rows="3" maxlength="300" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="授权菜单：" prop="menus">
                <el-tree
                    v-loading="isLoading"
                    element-loading-text="数据加载中..."
                    class="custom-tree"
                    ref="tree"
                    node-key="id"
                    :default-checked-keys="form.menuIdList"
                    :props="treeProps"
                    :data="treeData"
                    show-checkbox
                    @check-change="handleCheckChange">
                </el-tree>
            </el-form-item>
            <el-form-item>
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
import { updateRole, addRole, getRoleDetail, getRoleMenu } from '@/api/role';
import { getMenus } from '@/api/menu';

export default {
    props: ['show', 'id'],
    data () {
        return {
            form: {
                name: '',
                describle: '',
                menuIdList: '',
            },
            rules: {
                name: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                ],
            },
            treeProps: {
                label: 'name',
                children: 'sub_menus',
            },
            treeData: [],
            isLoading: false,
            selectedMenuIds: null,
        }
    },
    watch: {
        show: {
            handler(n) {
                if (n) {
                    this.refreshFromData();
                }
            },
            immediate: true,
        },
    },
    computed: {
        dialogTitle() {
            return this.id && this.id > 0 ? '编辑角色' : '新增角色';
        },
    },
    methods: {
        refreshFromData() {
            this.form.name = '';
            this.form.describle = '';
            this.form.menuIdList = [];
            this.selectedMenuIds = new Set();
            // this.$refs.tree && this.$refs.$tree.setCheckedKeys([]);
            if (this.id > 0) {
                getRoleDetail(this.id).then(res => {
                    if (res) {
                        this.form.name = res.name;
                        this.form.describle = res.describle;
                    }
                });

                getRoleMenu(this.id).then(res => {
                    if (res && res.data) {
                        let set = new Set();
                        this.initMenuData(set, res.data);
                        this.form.menuIdList = [...set];
                        this.selectedMenuIds = set;
                    }
                });
            }
            
            this.loadTreeMenuData();
        },
        initMenuData(set, list) {
            if (list && list.length > 0) {
                list.map(item => {
                    if (item.sub_menus && item.sub_menus.length > 0) {
                        this.initMenuData(set, item.sub_menus);
                    }
                    else {
                        set.add(item.id);
                    }
                });
            }
        },
        loadTreeMenuData() {
            this.isLoading = true;
            getMenus().then(res => {
                if (res && res.data) {
                    this.treeData = res.data || [];
                }
                this.isLoading = false;
            });
        },
        onClose() {
            this.$emit('update:show', false);
            this.$emit('close');
        },
        handleCheckChange() {
            const res = this.$refs.tree.getCheckedNodes(true);
            let arr = [];
            if (res && res.length > 0) {
                res.map(item => {
                    arr.push(item.id);
                });
            }
            this.selectedMenuIds = arr;
        },
        submitForm() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.form.menuIdList = [...this.selectedMenuIds];
                    // debugger
                    if (this.id > 0) {
                        updateRole(this.id, this.form).then(res => {
                            this.$message({
                                message: '修改成功',
                                type: 'success'
                            });
                            this.onClose();
                        });
                    }
                    else {
                        addRole(this.form).then(res => {
                            this.$message({
                                message: '新增成功',
                                type: 'success'
                            });
                            this.onClose();
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm() {
            this.$refs.form.resetFields();
            this.refreshFromData();
        }
    }
}
</script>

<style lang="scss" scoped>
.custom-tree {
    margin-top: 10px;
    margin-right: 20%;
    height: 300px;
    overflow: auto;
}
</style>