<template>
    <div>
        <el-tabs type="border-card" v-loading="view.loading">
            <el-tab-pane label="角色编辑">
                <el-form class="etong" ref="form" :model="data" label-position="top" :rules="rules">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item class="flex-1" label="角色编码" prop="roleCode">
                                <el-input v-model="data.roleCode" maxlength='64'></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item class="flex-1" label="角色名称" prop="roleName">
                                <el-input v-model="data.roleName" maxlength='64'></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item class="flex-1" label="角色类型" prop="roleType">
                                <el-select v-model="data.roleType" placeholder="请选择类型"
                                           @change="v=> {if(v === '2') data.dataAuth = null}">
                                    <el-option v-for="item in roleTypes" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24" v-if="data.roleType !== '2'">
                            <el-form-item class="flex-1 " label="数据权限" prop="dataAuth">
                                <el-select v-model="data.dataAuth" placeholder="请选择">
                                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="角色描述" prop="roleDesc">
                                <el-input type="textarea" v-model="data.roleDesc" maxlength='256'></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <OptionHistory v-if="data.uuid" :data="data" log></OptionHistory>
            </el-tab-pane>
            <el-tab-pane label="分配用户" :disabled="data.roleType === '2'">
                <Panel title="用户查询">
                    <template slot="buttons">
                        <el-button class="blue" @click="queryUserData" icon="el-icon-fa-search">查询</el-button>
                        <el-button class="yellow" @click="resetQuery" icon="el-icon-fa-reply-all">重置</el-button>
                    </template>
                    <el-form :inline="true" :model="queryform" ref="queryform">
                        <el-form-item label="登录账号" prop="userid">
                            <el-input v-model="queryform.userid" placeholder="登录账号" maxlength='32'
                                      @keyup.native.enter="queryUserData"></el-input>
                        </el-form-item>
                        <el-form-item label="用户名称" prop="username">
                            <el-input v-model="queryform.username" placeholder="用户名称" maxlength='32'
                                      @keyup.native.enter="queryUserData"></el-input>
                        </el-form-item>
                    </el-form>
                </Panel>
                <Panel title="用户列表">
                    <PageTable hide-title ref="multipleTable" row-key="uuid" border @load-data="dataTableLoad" :auto-load="false"
                               :data="table.data"
                               @selection-change="handleSelectionChange">
                        <el-table-column type="selection" align='center' width="50" fixed='left'
                                         :reserve-selection="true"></el-table-column>
                        <el-table-column prop="userid" label="登录账号"></el-table-column>
                        <el-table-column prop="username" label="用户名称"></el-table-column>
                        <!--            <el-table-column prop="usercode" label="用户工号"></el-table-column>-->
                        <el-table-column prop="orgname" label="隶属机构" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="crtime" :formatter="formatterDateTime" label="创建时间" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="optime" :formatter="formatterDateTime" label="最后修改时间" show-overflow-tooltip
                                         width="100"></el-table-column>
                    </PageTable>
                </Panel>
            </el-tab-pane>
            <el-tab-pane label="功能分配" :disabled="data.roleType === '2'">
                <el-tree ref="permTree" node-key="uuid" :data="permTreeData" :props="permTreeProp" :default-expand-all="true"
                         highlight-current
                         show-checkbox></el-tree>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script>
import RoleAPI from "@/api/base/usrm/RoleAPI";
import PermApi from "@/api/base/usrm/PermAPI";
import UserAPI from "@/api/base/usrm/UserAPI";
import OptionHistory from "@/common/OptionHistory.vue";

let dafaultData = {
    uuid: "",
    orgUuid: "",
    roleCode: "",
    roleName: "",
    roleDesc: "",
    roleType: "",
    parRoleUuid: "",
    dataAuth: null
};

export default {
    components: {OptionHistory},
    props: {
        uuid: {
            type: String,
            default: null
        },
        orgUuid: {
            type: String,
            default: null
        }
    },
    watch: {
        uuid(uuid) {
            if (uuid) {
                this.loadInfo();
            } else {
                this.data = Object.assign({}, dafaultData);
            }
        }
    },
    data() {
        return {
            dirty: false,
            multipleSelection: [],
            data: Object.assign({}, dafaultData),
            roleTypes: [
                {value: "1", label: "角色"},
                {value: "2", label: "目录"}
            ],
            permTreeData: [],
            view: {
                loading: false
            },
            queryform: {
                username: "",
                userid: "",
                uuid: this.uuid
            },
            table: {
                data: []
            },
            rules: {
                roleName: [{required: true, message: "角色名称不能为空!"}]
            },
            permTreeProp: {label: "permName", children: "children"},
            options: [
                {value: 0, label: "本人"},
                {value: 1, label: "本组织"},
                {value: 2, label: "本组织及下属组织"},
                {value: 3, label: "所有组织"}
            ]
        };
    },
    mounted() {
        // 读取系统菜单
        PermApi.loadPermTree().then(data => {
            this.permTreeData = data;
        });
    },
    methods: {
        resetQuery() {
            this.$refs.queryform.resetFields();
        },
        queryUserData() {
            this.$refs.multipleTable.load(this.queryform);
        },
        dataTableLoad(params, resolve) {
            params.orgUuid = this.data.orgUuid;
            UserAPI.getRoleUserByOrgId(params)
                .then(resolve) // 让表格解析你提供的数据 (主要解析页码等)
                .then(respData => (this.table.data = respData.datarows)); // 本地也记录一下数据 (提供给表示显示的数据)
        },
        // 获取选中值
        handleSelectionChange(val) {
            this.data.userIds = [];
            val.forEach(element => {
                this.data.userIds.push(element.uuid);
            }, this);
        },
        // 加载编辑器需要的信息
        async loadInfo() {
            try {
                this.view.loading = true;
                this.$refs.multipleTable.clearSelection();
                this.data.userIds = [];
                this.queryform.uuid = this.uuid;
                let resp = await RoleAPI.loadRoleEditInfo(this.uuid);
                this.data = resp;
                this.view.loading = false;
                // 在功能页上回显数据
                this.$refs.permTree.setCheckedKeys([]);
                resp.permIds.forEach(uuid => {
                    this.$refs.permTree.setChecked(uuid, true, false);
                });

                resp.userIds.forEach(uuid => {
                    this.$refs.multipleTable.toggleRowSelection({uuid}, true);
                });
                this.queryUserData();
            } finally {
                this.view.loading = false;
            }
        },
        // 提交数据
        async submit() {
            try {
                await this.$refs.form.validate();
                this.view.loading = true;
                let data = Object.assign({}, this.data);
                if (this.orgUuid) {
                    data.orgUuid = this.orgUuid;
                }
                let permTree = this.$refs.permTree;
                data.permIds = permTree
                    .getCheckedKeys()
                    .concat(permTree.getHalfCheckedKeys())
                    .filter(uuid => uuid !== "none");

                // 处理选中节点的数组，遍历，把uuid放入userIds才可以
                let resp = RoleAPI.editRoleNode(data);
                this.$emit("onsave", this.data);
                return resp;
            } finally {
                this.view.loading = false;
            }
        }
    }
};
</script>
