/** * 组件名称；权限配置-角色管理 * @author:laiyh * @Date:2020-07-27 */

<template>
    <dg-row :gutter="10" class="role-edit-box">
        <dg-col :span="14">
            <dg-card shadow="never" header="角色信息">
                <el-form ref="form" :model="reportForm" label-suffix=":" inline>
                    <el-form-item label="名称" prop="name.value"
                        ><el-input
                            clearable
                            placeholder="请输入名称"
                            v-model="reportForm.name.value"
                            style="width: 160px"
                            @keyup.enter.native="handleSearchClick"
                        ></el-input
                    ></el-form-item>
                    <el-form-item label="层级" prop="role_level.value">
                        <dg-select
                            filterable
                            clearable
                            v-model="reportForm.role_level.value"
                            placeholder="请选择层级"
                            code="DM_ROLE_LEVEL"
                            style="width: 160px"
                        ></dg-select
                    ></el-form-item>
                    <el-form-item
                        ><dg-button type="primary" icon="el-icon-search" @click="handleSearchClick"
                            >查询</dg-button
                        ></el-form-item
                    >
                </el-form>
                <div class="u-table-top__btn">
                    <dg-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAddDialog"
                        >新增</dg-button
                    >
                </div>
                <Table
                    ref="myRoleTable"
                    :url="roleTableUrl"
                    :headerData="titleData"
                    :condition="reportForm"
                    :maxheight="620"
                    @handleRowClick="handleRowClick"
                >
                    <dg-table-column label="操作" width="120" align="center">
                        <template slot-scope="scope">
                            <div class="u-table__operation">
                                <el-tooltip class="item" effect="dark" content="修改"
                                    ><i class="el-icon-edit" @click="handleRoleEdit(scope.row)"></i
                                ></el-tooltip>
                                <el-tooltip class="item" effect="dark" content="删除"
                                    ><i class="el-icon-delete" @click="handleRoleDelete(scope.row)"></i
                                ></el-tooltip>
                            </div>
                        </template>
                    </dg-table-column>
                </Table>
            </dg-card>
        </dg-col>
        <dg-col :span="10">
            <dg-card shadow="never" header="资源信息">
                <div class="u-table-top__btn">
                    <dg-button type="primary" icon="el-icon-folder-checked" @click="handleSaveMenu">保存</dg-button>
                </div>
                <!--树形表格-->
                <dg-table
                    :data="tableData"
                    :pagination="false"
                    style="width: 100%; margin-bottom: 20px"
                    row-key="id"
                    border
                    default-expand-all
                    ref="table"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                    @select="select"
                    @select-all="selectAll"
                    @selection-change="selectionChange"
                >
                    <dg-table-column type="selection" width="50"> </dg-table-column>
                    <dg-table-column prop="name" label="资源名称"> </dg-table-column>
                </dg-table>
            </dg-card>
        </dg-col>
    </dg-row>
</template>

<script>
import Table from "@/components/table"
import * as roleinfoManageApi from "@/api/roleinfo-manage"
import * as appfunMenuApi from "@/api/common"
import roleMange from "./role-manage.vue"

export default {
    name: "",
    components: {
        Table
    },
    // 接收父节点的参数
    props: {
        appId: {
            type: String,
            default: ""
        }
    },
    data() {
        return {
            roleTableUrl: roleinfoManageApi.appRoleTableUrl,
            reportForm: {
                name: { value: "", op: "like" },
                role_level: { value: "", op: "=" },
                app_id: { value: "", op: "=" }
            },
            titleData: [
                { label: "角色名称", prop: "name" },
                { label: "角色层级", code: "DM_ROLE_LEVEL", prop: "rolelevelCode" },
                { label: "警种", prop: "policeCategory", code: "T_MD_POLICE_TYPE" }
            ],
            treeProps: {
                label: "label",
                children: "children"
            },
            tableData: [],
            selectArr: [],
            roleId: ""
        }
    },
    // 方法
    methods: {
        // 查询角色
        handleSearchClick() {
            this.$refs.myRoleTable.handleSearchClick()
        },
        // 新增
        handleAddDialog() {
            const that = this
            const { appId } = that
            const layer = that.$dgLayer({
                title: "新增角色",
                area: ["550px", "650px"],
                shadow: [0.4, "#fff"],
                content: roleMange,
                props: {
                    appId,
                    type: "create"
                },
                on: {
                    success(bool = false) {
                        layer.close(layer.dialogIndex)
                        if (bool) {
                            that.reloadTable()
                        }
                    }
                }
            })
        },
        // 修改
        handleRoleEdit({ id }) {
            const that = this
            const { appId } = that
            roleinfoManageApi.getRoleInfo(id).then(res => {
                const layer = that.$dgLayer({
                    title: "修改角色",
                    area: ["490px", "650px"],
                    shadow: [0.4, "#fff"],
                    content: roleMange,
                    props: {
                        appId,
                        type: "update",
                        formData: res
                    },
                    on: {
                        success(bool = false) {
                            layer.close(layer.dialogIndex)
                            if (bool) {
                                that.reloadTable()
                            }
                        }
                    }
                })
            })
        },
        // 删除、
        handleRoleDelete({ id, name }) {
            const that = this
            that.$confirm(`是否确定删除角色[${name}]？`, "提示", {
                distinguishCancelAndClose: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消"
            }).then(_ => {
                roleinfoManageApi
                    .deleteRole(id)
                    .then(() => {
                        that.reloadTable()
                        that.$message.success("删除成功！")
                    })
                    .catch(() => {
                        that.$message.error("删除失败")
                    })
            })
        },
        // 刷新表格
        reloadTable() {
            const that = this
            that.$refs.myRoleTable.$refs.grid.reload()
        },
        /*
         ************应用菜单start********************
         */
        // 应用菜单--应用关联
        getAppfunMenu() {
            const that = this
            const { appId } = that
            appfunMenuApi.getAppfunMenu(appId).then(res => {
                if (res && res.length > 0) {
                    // that.tableData = that.loopTableData(res);
                    that.tableData = res
                }
            })
        },
        // 循环设置菜单表格data
        loopTableData(resArr) {
            let arr = []
            // debugger;
            function loopData(resArr2) {
                if (resArr2 && resArr2.length > 0) {
                    resArr2.forEach(item => {
                        arr.push(item)
                        if (item.children && item.children.length > 0) {
                            loopData(item.children)
                        }
                    })
                }
            }
            loopData(resArr)
            return arr
        },
        // 应用菜单-角色关联
        handleRowClick({ row }) {
            const roleId = row.id
            const that = this
            that.roleId = row.id
            roleinfoManageApi
                .getMenuChecked(roleId)
                .then(res => {
                    that.selectArr = []
                    that.$refs.table.clearSelection() // 清空用户选择

                    // 格式化tableData
                    let tempTableData = that.loopTableData(that.tableData)

                    if (res && res.length > 0) {
                        that.loopSetChecked(res, tempTableData)
                    }
                })
                .catch(error => {
                    that.$message.error(error)
                })
        },
        // 递归设置勾选
        loopSetChecked(checkList, allList) {
            for (let i = 0; i < checkList.length; i++) {
                for (let j = 0; j < allList.length; j++) {
                    if (checkList[i].funId === allList[j].id) {
                        this.toggleSelection(allList[j], true)
                        break
                    }
                    // else {
                    //     if (allList[j].children) {
                    //         this.loopSetChecked(checkList, allList[j].children);
                    //         break;
                    //     }
                    // }
                }
            }
        },
        // 保存菜单
        handleSaveMenu() {
            const that = this
            if (!that.roleId) {
                that.$message.warning("请选择角色！")
                return
            }
            if (that.selectArr.length == 0) {
                that.$message.warning("请选择菜单！")
                return
            }
            let rsGridList = that.selectArr.map(el => {
                return { id: el.id }
            })
            console.log(rsGridList)
            roleinfoManageApi
                .saveRsGrid({
                    rsGridLists: rsGridList,
                    roleId: that.roleId
                })
                .then(() => {
                    that.$message.success("保存成功")
                })
                .catch(error => {
                    that.$message.error("保存失败")
                })
        },
        select(selection, row) {
            const that = this
            if (
                selection.some(el => {
                    return row.id === el.id
                })
            ) {
                if (row.children) {
                    loopRowChild(row.children, true)
                    // row.children.map(j => {
                    //     this.toggleSelection(j, true);
                    // });
                }
            } else {
                if (row.children) {
                    // row.children.map(j => {
                    //     this.toggleSelection(j, false);
                    // });
                    loopRowChild(row.children, false)
                }
            }

            function loopRowChild(rows, flag) {
                rows.map(item => {
                    if (item.children) {
                        loopRowChild(item.children, flag)
                    }
                    that.toggleSelection(item, flag)
                })
            }
        },
        selectAll(selection) {
            const that = this
            // tabledata第一层只要有在selection里面就是全选
            const isSelect = selection.some(el => {
                const tableDataIds = this.tableData.map(j => j.id)
                return tableDataIds.includes(el.id)
            })
            // tableDate第一层只要有不在selection里面就是全不选
            const isCancel = !this.tableData.every(el => {
                const selectIds = selection.map(j => j.id)
                return selectIds.includes(el.id)
            })

            function loopRowChild(rows, flag) {
                rows.map(item => {
                    if (item.children) {
                        loopRowChild(item.children, flag)
                    }
                    that.toggleSelection(item, flag)
                })
            }
            if (isSelect) {
                selection.map(el => {
                    if (el.children) {
                        // el.children.map(j => {
                        //     this.toggleSelection(j, true);
                        // });
                        loopRowChild(el.children, true)
                    }
                })
            }
            if (isCancel) {
                this.tableData.map(el => {
                    if (el.children) {
                        // el.children.map(j => {
                        //     this.toggleSelection(j, false);
                        // });
                        loopRowChild(el.children, false)
                    }
                })
            }
        },
        selectionChange(selection) {
            this.selectArr = selection
        },
        toggleSelection(row, select) {
            if (row) {
                this.$nextTick(() => {
                    this.$refs.table && this.$refs.table.toggleRowSelection(row, select)
                })
            }
        }

        /*
         *********应用菜单end**********
         */
    },
    // 页面创建完成$data可访问 $el不可以访问
    created() {
        const that = this
        this.$set(this.reportForm.app_id, "value", this.appId)
        this.getAppfunMenu()
    }
}
</script>

<style lang="scss" scope>
.role-edit-box {
    .text-right {
        text-align: right;
    }
}
</style>
