<template>
    <dg-row gutter="1rem">
        <scroll-card header="人员列表" contentHeight="calc(100vh - 19rem)" :colSpan="11">
            <!-- 人员搜索栏 -->
            <search-bar :conditionForm="userConditionForm" @submitSearch="receiveSearch"></search-bar>
            <!-- 人员列表 -->
            <new-table
                ref="table"
                :tableUrl="userTableUrl"
                :tableHeader="userTableHeader"
                :condition="condition"
                @handleRowClick="handleRowClick"
            >
                <template #policeBusiness="{ row }">
                    {{ transferBusinessTag(row.policeBusiness) }}
                </template>
            </new-table>
        </scroll-card>
        <scrollCard header="角色列表" contentHeight="calc(100vh - 19rem)" :colSpan="13">
            <!-- 角色搜索栏 -->
            <search-bar :conditionForm="roleConditionForm" @submitSearch="receiveRoleSearch"></search-bar>
            <!-- 角色操作栏 -->
            <operate-bar :pageOptList="pageOptList" @submitPageOpt="receviceOpt"></operate-bar>
            <!-- 角色列表 -->
            <dg-table
                v-loading="myRoleTableLoading"
                ref="myRoleTable"
                :data="tableData"
                :pagination="false"
                :span-method="objectSpanMethod"
                border
                style="width: 100%"
                overflow="tooltip"
                @selection-change="handleSelectChange"
            >
                <dg-table-column type="selection" width="50" align="center"></dg-table-column>
                <dg-table-column prop="appName" label="应用系统名称" min-width="120" align="center"> </dg-table-column>
                <dg-table-column prop="name" label="角色名称" width="100" align="center">
                    <template slot-scope="{ row }">
                        <span style="cursor: pointer;color: #1890ff;" @click="viewRoleMenu(row, $event)">
                            {{ row.name }}
                        </span>
                    </template>
                </dg-table-column>
                <dg-table-column prop="code" label="角色代码" width="100" align="center"> </dg-table-column>
                <dg-table-column prop="roleLevel" label="角色层级" code="DM_ROLE_LEVEL" width="100" align="center">
                </dg-table-column>
                <dg-table-column prop="policeCategory" label="警种" code="T_MD_POLICE_TYPE" align="center">
                </dg-table-column>
                <dg-table-column
                    prop="roleBusiness"
                    label="业务域"
                    min-width="100"
                    code="DM_POLICE_BUSINESS"
                    align="center"
                >
                    <template slot-scope="{ row }">
                        {{ row.roleBusiness }}
                    </template>
                </dg-table-column>
                <dg-table-column prop="activeTime" label="权限有效期" min-width="90" align="center">
                    <template slot-scope="{ row }">
                        <a href="javascript:;" @click="handleValidateChoose(row)">{{ row.activeTime }}</a>
                    </template>
                </dg-table-column>
            </dg-table>
        </scrollCard>
    </dg-row>
</template>

<script>
import newTable from "@/components/new-table"
import { mapGetters } from "vuex"
import * as roleAuthInfoApi from "@/api/role-auth-info"
import Termvalidate from "./term-validity"
import transferBusinessTagMixin from "@/mixins/transfer-business-tag"
import searchBar from "@/components/search-bar"
import { searchOpt } from "@/mixins/page-opt"
import { userConditionForm, userTableHeader, roleConditionForm } from "./DataConfig.js"
import operateBar from "@/components/operate-bar"
import scrollCard from "@/components/scroll-card"
import roleMenuTree from "./role-menu-tree.vue"

export default {
    name: "role-list",
    // 接收父页面传过来的属性
    props: {},
    components: {
        newTable,
        searchBar,
        operateBar,
        scrollCard
    },
    mixins: [transferBusinessTagMixin, searchOpt],

    // 页面数据绑定
    data() {
        return {
            userTableUrl: roleAuthInfoApi.staffUserPage,
            userConditionForm,
            userTableHeader,
            roleConditionForm,
            pageOptList: ["保存"],
            r_titleData: [
                { label: "系统名称" },
                { type: "selection", width: "50px", label: "" },
                { label: "角色名称" },
                { label: "角色层级" },
                { label: "警种" },
                { label: "业务域" },
                {
                    label: "有效期至",
                    "class-name": "a-link",
                    state: [{ label: "长期有效", value: null }]
                }
            ],
            roleCondition: {
                appName: "",
                roleName: "",
                userId: "",
                orgId: ""
            },
            tableData: [],
            selections: [],
            deleteIds: [],
            perRow: null,
            count: 0,
            tagTree: [],
            myRoleTableLoading: false
        }
    },
    // 计算属性
    computed: {
        ...mapGetters(["user"])
    },
    // 方法
    methods: {
        viewRoleMenu(row, event) {
            event.stopPropagation()
            this.$dgLayer({
                title: "功能清单",
                area: ["540px", "500px"],
                content: roleMenuTree,
                props: {
                    row
                }
            })
        },
        // 构建新的一级标签树
        setNewTagTree() {
            let newTagTree = []
            for (let j = 0; j < this.tagTree.length; j++) {
                const item = this.tagTree[j]
                if (item.child && item.parent) {
                    newTagTree = [...newTagTree, ...item.child]
                }
            }
            return newTagTree
        },
        // 人员列表行点击
        handleRowClick(row) {
            this.roleCondition.userId = row.id
            this.roleCondition.orgId = row.orgId
            this.handleSearchRoleList()
        },
        receiveRoleSearch(val) {
            for (const key in val) {
                this.roleCondition[key] = val[key].value
            }
            this.handleSearchRoleList()
        },
        receviceOpt(opt, row) {
            this.handleSaveStaff()
        },
        handleSearchRoleList() {
            this.myRoleTableLoading = true
            const that = this
            const { roleCondition } = that
            this.tableData = []
            this.selections = []
            this.deleteIds = []
            roleAuthInfoApi
                .getStaffRoleList(roleCondition)
                .then(res => {
                    that.tableData = res
                    that.$nextTick(() => {
                        res.forEach(row => {
                            if (row.cause == 1) {
                                this.$refs.myRoleTable.toggleRowSelection(row, true)
                            }
                        })
                    })

                    that.setrowspans()
                })
                .finally(() => {
                    this.myRoleTableLoading = false
                })
        },
        handleSaveStaff() {
            const that = this
            if (this.selections.length == 0) {
                this.tableData.forEach(dd => {
                    this.deleteIds.push({
                        id: dd.id,
                        appId: dd.appId
                    })
                })
            } else {
                for (let i = 0; i < this.tableData.length; i++) {
                    let flag = true
                    for (let j = 0; j < this.selections.length; j++) {
                        if (this.tableData[i].id == this.selections[j].id) {
                            flag = false
                            break
                        }
                    }
                    if (flag) {
                        this.deleteIds.push({
                            id: this.tableData[i].id,
                            appId: this.tableData[i].appId
                        })
                    }
                }
            }
            const queryParams = {
                saveIds: this.selections,
                deleteIds: this.deleteIds,
                userId: this.roleCondition.userId,
                orgId: this.roleCondition.orgId
            }
            roleAuthInfoApi
                .saveRoleStaff(queryParams)
                .then(res => {
                    that.$message.success("保存成功！")
                })
                .catch(err => {
                    that.$message.error(err)
                })
        },
        handleSelectChange(selection) {
            this.selections = selection
            this.deleteIds = []
        },
        // 合并行
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 0) {
                return {
                    rowspan: row.rowspan,
                    colspan: 1
                }
            }
        },
        setrowspans() {
            // 先给所有的数据都加一个v.rowspan = 1
            this.tableData.forEach(v => {
                v.rowspan = 1
            })
            // 双层循环
            for (let i = 0; i < this.tableData.length; i++) {
                // 内层循环，上面已经给所有的行都加了v.rowspan = 1
                // 这里进行判断
                // 如果当前行的id和下一行的id相等
                // 就把当前v.rowspan + 1
                // 下一行的v.rowspan - 1
                for (let j = i + 1; j < this.tableData.length; j++) {
                    // 此处可根据相同字段进行合并，此处是根据的id
                    if (this.tableData[i].appName === this.tableData[j].appName) {
                        this.tableData[i].rowspan++
                        this.tableData[j].rowspan--
                    }
                }
                // 这里跳过已经重复的数据
                i = i + this.tableData[i].rowspan - 1
            }
        },

        // 有效期选择
        handleValidateChoose(row) {
            const that = this
            const layer = that.$dgLayer({
                title: "有效期选择",
                area: ["540px", "300px"],
                shade: [0.4, "#FFF"],
                content: Termvalidate,
                props: {
                    operatorRow: row
                },
                on: {
                    success: function(res) {
                        layer.closeAll(layer.dialogIndex)
                        row.activeTime = res.activeTime
                    }
                }
            })
        }
    },
    // 创建组件时调用
    created() {}
}
</script>

<style lang="scss" scoped>
@import url("./index.scss");
</style>
