<template>
    <ap-container>
        <ap-aside margin="1111" width="30%">
            <div class="layout-aside-header">
                <div class="layout-aside-header-title">用户</div>
            </div>
            <div>
                <el-input placeholder="关键字过滤" v-model="treeFilterText"></el-input>
            </div>
            <div class="layout-aside-content" v-loading="loadingTreeFlag">
                <el-tree
                    ref="userTree"
                    node-key="fdId"
                    :data="treeData"
                    :props="{children: 'children',label: 'fdName'}"
                    :check-on-click-node="true"
                    :highlight-current="true"
                    :expand-on-click-node="false"
                    :check-strictly="false"
                    :filter-node-method="filterTreeNode"
                    @node-click="clickTreeEvent">
                    <div slot-scope="{ node, data }" style="width: 100%">
                        <template v-if="data.isUser != 1">
                            <div class="tree-node">
                                <span style="color: #2e6d91">{{ data.fdName }}</span>
                            </div>
                        </template>
                        <template v-if="data.isUser == 1">
                            <div class="tree-node ap-ellipse">
                                <span style="color: #1890FF">
                                    <i class="el-icon-s-custom"/>&nbsp;&nbsp;{{ data.fdName }}
                                    <template v-if="data.personName != null">
                                        {{ ' - [' + data.personName + ']' }}
                                    </template>
                                </span>
                            </div>
                        </template>
                    </div>
                </el-tree>
            </div>
        </ap-aside>
        <ap-split-panel></ap-split-panel>
        <ap-container>
            <ap-header margin="1110">
                <div class="flex ">
                    <div>
                        已选择：
                        <el-input v-model="selectedName" :disabled="true" style="width: 200px;"></el-input>
                    </div>
                    <div class="flex-1" style="text-align: right;">
                        <ap-button type="primary" icon="el-icon-check" :click="saveSysAuth">保存</ap-button>
                        <el-button type="primary" icon="el-icon-copy" @click="showCopyAuth">复制用户权限</el-button>
                    </div>
                </div>
            </ap-header>
            <ap-main margin="0110" style="padding: 0px;">
                <ap-container>
                    <ap-aside style="border-right: 1px dashed #cccccc;" width="50%">
                        <div class="layout-aside-header">
                            <div class="layout-aside-header-title">功能角色</div>
                        </div>
                        <div>
                            <el-input placeholder="关键字过滤" v-model="functionRoleTreeFilterText"></el-input>
                        </div>
                        <div class="layout-aside-content">
                            <el-tree
                                ref="functionRoleTree"
                                node-key="fdId"
                                :data="functionRoleTreeData"
                                :default-checked-keys="functionRoleCheckedKeys"
                                :props="{children: 'children',label: 'fdName'}"
                                default-expand-all
                                show-checkbox
                                :check-on-click-node="true"
                                :highlight-current="true"
                                :expand-on-click-node="false"
                                :check-strictly="true"
                                :filter-node-method="filterFunctionRoleTreeNode">
                            </el-tree>
                        </div>
                    </ap-aside>

                    <ap-aside width="50%">
                        <div class="layout-aside-header">
                            <div class="layout-aside-header-title">组织帐套角色</div>
                        </div>
                        <div>
                            <el-input placeholder="关键字过滤" v-model="orgRoleTreeFilterText"></el-input>
                        </div>
                        <div class="layout-aside-content">
                            <el-tree
                                ref="orgRoleTree"
                                node-key="fdId"
                                :data="orgRoleTreeData"
                                :default-checked-keys="orgRoleCheckedKeys"
                                :props="{children: 'children',label: 'fdName'}"
                                default-expand-all
                                show-checkbox
                                :check-on-click-node="true"
                                :highlight-current="true"
                                :expand-on-click-node="false"
                                :check-strictly="true"
                                :filter-node-method="filterOrgRoleTreeNode">
                            </el-tree>

                        </div>
                    </ap-aside>
                </ap-container>
            </ap-main>
        </ap-container>
        <el-dialog title="功能角色权限复制：给 [目标用户] 授权，将 [来源用户] 的权限，复制给 [目标用户]" :visible.sync="showCopyAuthFlag" width="800px" :append-to-body="true">
            <div class="flex-center">
                <div class="flex-1 flex-col" style="height: 400px;border-right: 1px solid #eeeeee;padding-right: 20px;">
                    <div class="flex-justify-start">
                        <div style="font-weight: bold">来源用户：</div>
                        <ap-search-tree :options.sync="sourceUserOption">
                        <span slot="tree" slot-scope="scope">
                            <template v-if="scope.data.isUser != 1">
                                <div class="tree-node">
                                    <span style="color: #2e6d91">{{ scope.data.fdName }}</span>
                                </div>
                            </template>
                            <template v-if="scope.data.isUser == 1">
                                <div class="tree-node ap-ellipse">
                                    <span style="color: #1890FF">
                                        <i class="el-icon-s-custom"/>&nbsp;&nbsp;{{ scope.data.fdName }}
                                        <template v-if="scope.data.personName != null">
                                            {{ ' - [' + scope.data.personName + ']' }}
                                        </template>
                                    </span>
                                </div>
                            </template>
                        </span>

                        </ap-search-tree>
                    </div>

                    <ap-aside-tree ref="sourceUserRoleRef" :options.sync="sourceUserRoleOptions" class="flex-1">
                        <span v-if="scope.data.compareId == null" slot="tree" slot-scope="scope" class="ap-color-red">
                            {{ scope.data.fdName }}
                        </span>
                        <span v-else slot="tree" slot-scope="scope" class="ap-color-green">
                            {{ scope.data.fdName }}
                        </span>
                    </ap-aside-tree>
                </div>

                <div class="flex-1 flex-col" style="height: 400px;margin-left: 20px;">
                    <div class="flex-justify-start">
                        <div style="font-weight: bold">目标用户：</div>
                        <ap-search-tree :options.sync="targetUserOption">
                            <span slot="tree" slot-scope="scope">
                                <template v-if="scope.data.isUser != 1">
                                    <div class="tree-node">
                                        <span style="color: #2e6d91">{{ scope.data.fdName }}</span>
                                    </div>
                                </template>
                                <template v-if="scope.data.isUser == 1">
                                    <div class="tree-node ap-ellipse">
                                        <span style="color: #1890FF">
                                            <i class="el-icon-s-custom"/>&nbsp;&nbsp;{{ scope.data.fdName }}
                                            <template v-if="scope.data.personName != null">
                                                {{ ' - [' + scope.data.personName + ']' }}
                                            </template>
                                        </span>
                                    </div>
                                </template>
                            </span>
                        </ap-search-tree>
                    </div>
                    <ap-aside-tree ref="targetUserRoleRef" :options.sync="targetUserRoleOptions" class="flex-1">
                        <span v-if="scope.data.compareId == null" slot="tree" slot-scope="scope" class="ap-color-red">
                            {{ scope.data.fdName }}
                        </span>
                        <span v-else slot="tree" slot-scope="scope" class="ap-color-green">
                            {{ scope.data.fdName }}
                        </span>
                    </ap-aside-tree>
                </div>
            </div>
            <span slot="footer">
                <el-button @click="showCopyAuthFlag = false">取 消</el-button>
                <ap-button type="primary" :click="copyUserAuth">复制权限</ap-button>
            </span>
        </el-dialog>
    </ap-container>
</template>

<script>
import {convertToTreeData} from 'ap-util/util/DataUtil'

export default {
    name: 'SysAuthUser',
    data() {
        return {
            // ----- 左侧树 -----
            loadingTreeFlag: false,
            treeFilterText: '',
            treeData: [],
            selectedId: "",
            selectedType: 0,
            selectedName: '',

            // ----- 右侧 -----
            functionRoleTreeFilterText: '',
            functionRoleTreeData: [],
            functionRoleCheckedKeys: [],
            orgRoleTreeFilterText: '',
            orgRoleTreeData: [],
            orgRoleCheckedKeys: [],
            // 弹框
            showCopyAuthFlag: false,
            sourceUserOption: this.getSourceUserOption(),
            sourceUserRoleOptions: this.getSourceUserRoleOptions(),
            sourceUserId: "",
            targetUserOption: this.getTargetUserOption(),
            targetUserRoleOptions: this.getTargetUserRoleOptions(),
            targetUserId: "",

        }
    },
    watch: {
        treeFilterText(val) {
            // 过滤值修改，更新tree
            this.$refs.userTree.filter(val);
        },
        functionRoleTreeFilterText(val) {
            this.$refs.functionRoleTree.filter(val);
        },
        orgRoleTreeFilterText(val) {
            this.$refs.orgRoleTree.filter(val);
        }
    },
    created() {
        this.loadTreeData();
    },
    methods: {
        // 左侧树：加载数据
        loadTreeData() {
            this.loadingTreeFlag = true;

            // 加载数据
            this.$request({
                url: '/apm/sys/sysAuth/getUserList',
                method: 'post',
                data: {
                    type: 0
                }
            }).then(response => {
                let res = response.data;
                // 数据格式转换：数组 -> tree
                this.treeData = convertToTreeData(res, {
                    idKey: "fdId",
                    parentKey: "fdParentId",
                    childrenKey: "children",
                });
            }).finally(() => {
                this.loadingTreeFlag = false;
            })
        },
        // 左侧树：重新加载数据
        reLoadTreeData() {
            // 重置当前选择节点
            this.$refs.userTree.setCurrentKey();
            this.loadTreeData();
        },
        // 左侧树：过滤节点
        filterTreeNode(value, data) {
            if (!value) return true;
            if (data.personName != null && data.personName.indexOf(value) !== -1) {
                return true;
            }
            if (data.fdName.indexOf(value) !== -1) {
                return true;
            }
        },
        // 左侧树：click事件
        clickTreeEvent(data, node, comp) {
            this.selectedName = data.personName != null ? data.fdName + ' - [' + data.personName + ']' : data.fdName;
            this.selectedId = data.fdId;
            this.selectedType = data.isUser == 1 ? 0 : 1;
            this.loadRoleTreeData();
        },
        filterFunctionRoleTreeNode(value, data) {
            if (!value) return true;
            return data.fdName.indexOf(value) !== -1;
        },
        filterOrgRoleTreeNode(value, data) {
            if (!value) return true;
            return data.fdName.indexOf(value) !== -1;
        },
        loadRoleTreeData() {
            this.functionRoleTreeData = [];
            this.$request({
                url: '/apm/sys/sysAuth/getSysUserRoleList',
                method: 'post',
                data: {
                    type: this.selectedType,
                    selectedId: this.selectedId
                }
            }).then(response => {
                let tempRoleList = response.data.roleList;
                let functionRoleList = [];
                let orgRoleList = [];
                for (let i = 0; i < tempRoleList.length; i++) {
                    if (tempRoleList[i].fdType == 0) {
                        functionRoleList.push(tempRoleList[i]);
                    } else if (tempRoleList[i].fdType == 1) {
                        orgRoleList.push(tempRoleList[i]);
                    }
                }
                let authListRes = response.data.authList;
                let authList = [];
                for (let i = 0; i < authListRes.length; i++) {
                    authList.push(authListRes[i].fdRoleId);
                }
                this.functionRoleTreeData = convertToTreeData(functionRoleList, {});
                this.functionRoleCheckedKeys = authList;

                this.orgRoleTreeData = convertToTreeData(orgRoleList, {});
                this.orgRoleCheckedKeys = authList;
            })
        },
        saveSysAuth() {
            let userAuth = [];
            let functionRole = this.$refs.functionRoleTree.getCheckedNodes(false);
            let orgRole = this.$refs.orgRoleTree.getCheckedNodes(false);
            let allRole = functionRole.concat(orgRole);
            for (let i = 0; i < allRole.length; i++) {
                userAuth.push({
                    fdType: this.selectedType,
                    fdTypeId: this.selectedId,
                    fdRoleId: allRole[i].fdId,
                })
            }
            return new Promise((resolve, reject) => {
                this.$request({
                    url: '/apm/sys/sysAuth/saveSysAuth',
                    method: 'post',
                    data: {
                        typeId: this.selectedId,
                        list: JSON.stringify(userAuth)
                    }
                }).then(response => {
                    this.$message.success("保存成功！");
                }).finally(() => {
                    resolve();
                });
            });
        },
        getSourceUserOption() {
            return {
                searchTreeValue: "",
                searchTreeUrl: "/apm/sys/sysAuth/getUserList",
                searchTreeExpandAll: false,
                filterNodeMethod: (value, data) => {
                    if (!value) return true;
                    if (data["personName"] != null && data["personName"].indexOf(value) !== -1) {
                        return true;
                    }
                    if (data["fdName"] != null && data["fdName"].indexOf(value) !== -1) {
                        return true;
                    }
                    return false;
                },
                searchTreeConfirm: (checkedNodes) => {
                    let node = checkedNodes[0];
                    if (node.isUser != 1) {
                        this.$message.error("请选择用户");
                        return false;
                    }
                    // 修改组件显示值
                    this.sourceUserOption.searchTreeText = node.personName == null ? node.fdName : node.fdName + ' - [' + node.personName + ']';
                    this.sourceUserId = node.fdId;
                    this.$refs.sourceUserRoleRef.reLoadTreeData();
                    if (this.targetUserId != null && this.targetUserId != "") {
                        this.$refs.targetUserRoleRef.reLoadTreeData();
                    }
                    return true;
                },
                searchTreeClear: () => {
                    this.sourceUserOption.searchTreeText = "";
                    this.sourceUserId = "";
                    return true;
                },
            }
        },
        getSourceUserRoleOptions() {
            return {
                title: "",
                initData: false,
                onClick: (data, node, comp) => {
                },
                loadOptions: {
                    url: "/apm/sys/sysAuth/getSysUserAuthedRoleList",
                    data: () => {
                        return {
                            userId: this.sourceUserId,
                            compareUserId: this.targetUserId
                        }
                    },
                    success: (response) => {
                    },
                    error() {
                    },
                    treeKey: {
                        idKey: "fdId",
                        parentKey: "fdParentId",
                        childrenKey: "children",
                        label: "fdName"
                    },
                },
            };
        },
        getTargetUserOption() {
            return {
                searchTreeValue: "",
                searchTreeUrl: "/apm/sys/sysAuth/getUserList",
                searchTreeExpandAll: false,
                filterNodeMethod: (value, data) => {
                    if (!value) return true;
                    if (data["personName"] != null && data["personName"].indexOf(value) !== -1) {
                        return true;
                    }
                    if (data["fdName"] != null && data["fdName"].indexOf(value) !== -1) {
                        return true;
                    }
                    return false;
                },
                searchTreeConfirm: (checkedNodes) => {
                    let node = checkedNodes[0];
                    if (node.isUser != 1) {
                        this.$message.error("请选择用户");
                        return false;
                    }
                    // 修改组件显示值
                    this.targetUserOption.searchTreeText = node.personName == null ? node.fdName : node.fdName + ' - [' + node.personName + ']';
                    this.targetUserId = node.fdId;
                    this.$refs.targetUserRoleRef.reLoadTreeData();
                    if (this.sourceUserId != null && this.sourceUserId != "") {
                        this.$refs.sourceUserRoleRef.reLoadTreeData();
                    }
                    return true;
                },
                searchTreeClear: () => {
                    this.targetUserOption.searchTreeText = "";
                    this.targetUserId = "";
                    return true;
                },
            }
        },
        getTargetUserRoleOptions() {
            return {
                title: "",
                initData: false,
                onClick: (data, node, comp) => {
                },
                loadOptions: {
                    url: "/apm/sys/sysAuth/getSysUserAuthedRoleList",
                    data: () => {
                        return {
                            userId: this.targetUserId,
                            compareUserId: this.sourceUserId
                        }
                    },
                    success: (response) => {
                    },
                    error() {
                    },
                    treeKey: {
                        idKey: "fdId",
                        parentKey: "fdParentId",
                        childrenKey: "children",
                        label: "fdName"
                    },
                },
            };
        },
        showCopyAuth() {
            this.showCopyAuthFlag = true;
        },
        copyUserAuth() {
            return new Promise((resolve) => {
                if (this.sourceUserId == null || this.sourceUserId == "") {
                    this.$message.error('请选择来源用户');
                    resolve();
                    return;
                }
                if (this.targetUserId == null || this.targetUserId == "") {
                    this.$message.error('请选择目标用户');
                    resolve();
                    return;
                }
                this.$confirm('确定将【' + this.sourceUserOption.searchTreeText + '】的权限，复制给【' + this.targetUserOption.searchTreeText + '】', '提示', {
                    confirmButtonText: '确定复制',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$request({
                        url: '/apm/sys/sysAuth/copyUserAuth',
                        method: 'post',
                        data: {
                            targetUserId: this.targetUserId,
                            sourceUserId: this.sourceUserId
                        },
                    }).then(response => {
                        this.$message.success(response.data);
                        this.$refs.targetUserRoleRef.reLoadTreeData();
                        this.$refs.sourceUserRoleRef.reLoadTreeData();
                    }).finally(() => {
                        resolve();
                    });
                }).finally(() => {
                    resolve();
                });


            });
        },


    }
}
</script>

<style scoped>
.tree-node {
    font-size: 15px;
}
</style>
