<template>
    <div class="flex-h card-height-full perm-mgr-div">
        <Panel title="功能权限管理" v-if="rightBlock" class="flex-2  full">
            <template slot="buttons">
                <el-button class="blue" icon="el-icon-fa-expand" @click="expandAll">展开</el-button>
                <el-button class="blue" icon="el-icon-fa-refresh" @click="load">刷新</el-button>
                <el-button class="blue" icon="el-icon-fa-wrench" @click="autoAligned">节点对齐</el-button>
                <el-button class="green" :icon="!leftBlock?'el-icon-caret-left':'el-icon-caret-right'" @click="leftBlock=!leftBlock"/>
            </template>
            <el-tree v-if='showPermTree'
                     ref="permTree"
                     node-key="uuid"
                     v-loading="saving"
                     :default-expand-all="expandedAll"
                     :expand-on-click-node="false"
                     :data="permTreeData"
                     :current-node-key="currPerm.uuid"
                     highlight-current
                     @current-change="currentChange">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                        <span>{{ data.ordeCode || "" }}</span>

                        <span><i v-if="data.iconUrl"
                                 :class="['margin-left-2', 'margin-right-2', 'el-icon-fa', 'el-icon-fa-' + data.iconUrl]"/></span>

                        <span>{{ data.permName }}</span>
                    </span>
                    <el-button-group>
                        <el-button icon="el-icon-fa-plus" @click.stop="addPerm(node)"/>
                        <el-button icon="el-icon-fa-minus" @click.stop="removePerm(node)" :disabled="data.uuid === 'none'"/>
                    </el-button-group>
                </span>
            </el-tree>
        </Panel>
        <Panel title="编辑权限" v-if="leftBlock" class="flex-2 margin-left-2 full">
            <template slot="buttons">
                <el-button class="blue" v-if="editable" @click="onSubmit" icon="el-icon-fa-save" :disabled="readonly">保存</el-button>
                <el-button class="green" :icon="rightBlock?'el-icon-caret-left':'el-icon-caret-right'" @click="rightBlock=!rightBlock"/>
            </template>
            <div class="text-center font-red" v-if="!editable">
                禁止编辑
            </div>
            <div v-if="editable">
                <el-form ref="form" :model="currPerm" label-position="top" :rules="rules">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="功能名称" prop="permName">
                                <el-input v-model="currPerm.permName" maxlength='32' :disabled="readonly"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item class="flex-1" label="功能编码" prop="permCode">
                                <el-input v-model="currPerm.permCode" maxlength='32' :disabled="readonly"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item class="flex-2 " label="功能地址" prop="funcUrl">
                                <el-input v-model="currPerm.funcUrl" maxlength='128' :disabled="readonly"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="菜单类型" prop="permType">
                                <el-radio-group v-model="currPerm.permType">
                                    <el-radio v-for="item in permTypes" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="最低数据权限" prop="lowDataAuth">
                                <el-select v-model="currPerm.lowDataAuth" placeholder="请选择" :disabled="readonly">
                                    <el-option v-for="item in lowDataAuths" :key="item.value" :label="item.label" :value="item.value"/>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="图标样式" prop="iconUrl">
                                <el-input v-model="currPerm.iconUrl" maxlength='128' :disabled="readonly"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="顺序编号" prop="ordeCode">
                                <el-input-number v-model="currPerm.ordeCode" :min="1" :disabled="readonly"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <!-- <el-form-item label="组件" prop="permComp">
                              <el-input v-model="currPerm.permComp"></el-input>
                            </el-form-item> -->
                            <el-form-item label="功能描述" prop="permDesc">
                                <el-input type="textarea" v-model="currPerm.permDesc" maxlength='256' :disabled="readonly"/>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <OptionHistory v-if="editable" :data="currPerm"/>

            </div>
        </Panel>
    </div>
</template>
<script>
import OptionHistory from "@/common/OptionHistory.vue";
import PermApi from "@/api/base/usrm/PermAPI";

export default {
    name: "PermMgr",
    components: {OptionHistory},
    data() {
        return {
            leftBlock: true,
            rightBlock: true,
            //树显示
            showPermTree: true,
            currPerm: {},
            currParentPerm: {},
            permTreeData: [],
            saving: false,
            expandedAll: false,
            currNode: "",
            editor: {
                error: {}
            },
            rules: {
                permName: [{required: true, message: "功能名称不能为空!"}],
                permCode: [{required: true, message: "功能编码不能为空!"}],
                permType: [{required: true, message: "菜单类型不能为空!"}],
                ordeCode: [
                    {required: true, message: "顺序编号不能为空!"},
                    {
                        min: 1,
                        max: 999,
                        type: "number",
                        message: "顺序编号在1到999之间",
                        trigger: "blur"
                    }
                ],
                lowDataAuths: [{required: true, message: "最低数据权限不能为空!"}],
                funcUrl: [
                    {
                        validator: (rule, value, callback) => {
                            if (!value && this.currPerm.permType !== '3') {
                                callback(new Error('功能地址不能为空'));
                            } else {
                                callback();
                            }
                        }, trigger: 'blur'
                    }
                ],
            },
            lowDataAuths: [
                {value: 0, label: "本人", disabled: true},
                {value: 1, label: "本组织"},
                {value: 2, label: "本组织及下属组织"},
                {value: 3, label: "所有组织"}
            ],
            permTypes: [{value: "1", label: "菜单"}, {value: "2", label: "按钮"}, {value: "3", label: "功能"}]
        };
    },
    mounted() {
        this.load();
    },
    computed: {
        editable() {
            return this.currPerm.uuid !== 'none';
        },
        readonly() {
            return this.currPerm.permComp === 'readonly';
        }
    },
    methods: {
        // 拖拽完成
        handleDrop(draggingNode, dropNode, dropType, ev) {
        },
        load() {
            this.currPerm = {};
            this.saving = true;
            // 读取系统菜单
            PermApi.loadPermTree().then(data => {
                this.permTreeData = data;
                this.saving = false;
            });
        },
        autoAligned() {
            this.confirm(
                null,
                "操作会自动排列菜单排序,以及功能编码,是否确定操作?"
            ).then(() => {
                this.saving = true;
                PermApi.autoAligned()
                    .then(() => {
                        this.saving = false;
                    })
                    .then(this.load);
            });
        },
        addPerm(node) {
            let newPerm = {
                permName: "新建菜单",
                ordeCode: node.childNodes.length + 1,
                permCode: "X",
                lowDataAuth: 0, // 服务器给的数据是字符串.
                parPermUuid: node.data.uuid,
                permType: "1",
                funcUrl: "/",
                iconUrl: "user"
            };
            this.saving = true;
            PermApi.savePerm(newPerm)
                .then(data => {
                    Object.assign(newPerm, {uuid: data.uuid}); // 合并刚才返回的UUID主键
                    this.saving = false; // 保存结束
                    node.insertChild({data: newPerm}); // 让当前节点追加一个新节点
                    node.expand(() => {
                        this.currPerm = newPerm;
                    }); // 如果没拉取子节点,先拉取子节点,然后设置当前节点
                })
                .then(this.loadTree);
        },
        //  展开/关闭 全部
        expandAll() {
            if (this.expandedAll) {
                this.saving = true;
                this.showPermTree = false;
                this.expandedAll = false;
                setTimeout(() => {
                    this.showPermTree = true;
                    this.saving = false;
                }, 200);
                return;
            }
            this.expandedAll = true;
            let expandFn = (element, expand) => {
                element.childNodes.forEach(function (element) {
                    element.expand(() => {
                        expandFn(element);
                    });
                }, this);
            };
            expandFn(this.$refs.permTree.root);
        },
        // 点击菜单树节点
        currentChange(data, node) {
            this.currParentPerm = node.parent.data || {};
            this.currPerm = data || {};
            this.currNode = node;
        },
        // 提交数据
        onSubmit() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.saving = true;
                    this.editor.error = {};
                    PermApi.savePerm(this.currPerm)
                        .then(data => {
                            this.saving = false;
                        })
                        .catch(error => {
                            this.editor.error = error.validError;
                            this.saving = false;
                        });
                }
            });
        },
        // 加载树内容
        loadTree(node, resolve) {
            if (node.data && node.data.permType !== "0") {
                PermApi.getPermByPID(node.data.uuid)
                    .then(resp => resp.data)
                    .then(resolve);
            } else {
                resolve([]);
            }
            this.saving = false;
        },
        // 删除菜单
        async removePerm(node) {
            try {
                await this.confirm();
                this.saving = true;
                let resp = await PermApi.deletePerm(node.data.uuid);
                this.saving = false;
                node.parent.removeChild(node);
            } finally {
                this.saving = false;
            }
        }
    }
};
</script>

<style lang="scss">
.perm-mgr-div {
    & > .la-panel {
        height: calc(100vh - 117px);

        & > .la-panel__body {
            overflow-y: auto;
        }
    }
}
</style>
