<template>
    <div style="margin-bottom: 10px; height: 100%; padding-left: 1%; padding-right: 1%;">
        <el-config-provider :locale="zhCn">
            <div style="display: flex;justify-content: space-between;">
                <el-row>
                    <el-input v-model="roleNameQuery" style="width: 216px; margin-right: 10px;" placeholder="角色名"
                        :suffix-icon="Search" />
                    <el-button type="primary" @click="search()">搜索</el-button>
                    <el-button type="warning" @click="reset()">重置</el-button>
                </el-row>
                <el-row>
                    <el-button type="success" @click="openAddRoleDialog()">新增角色</el-button>
                </el-row>
            </div>
            <br />
            <el-table :data="roleList" stripe border v-loading="loading" class="table-class" highlight-current-row
                max-height="650px" @row-click="getCurrentRow" :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }">
                <el-table-column width="65px" fixed="left">
                    <template v-slot="scope">
                        <el-radio :label="scope.row.roleId" v-model="roleId">&nbsp;</el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="roleId" label="id" fixed="left" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="roleName" label="角色名" min-width="120px" show-overflow-tooltip />
                <el-table-column fixed="right" label="操作" width="216px">
                    <template v-slot="scope">
                        <div style="display: flex;justify-content: space-between;">
                            <el-button plain type="primary" @click="editCurrentRow(scope.row)">编辑角色</el-button>
                            <el-button plain type="danger" @click="deleteCurrentRow(scope.row)">删除角色</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <br />
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 25, 50]"
                :small="false" :disabled="false" :background="false" :default-page-size="10"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="search"
                @current-change="search" />
            <el-dialog v-model="dialogVisible" title="编辑角色信息" width="40%" draggable :show-close="false">
                <div
                    style="max-width: 100%; max-height: 350px; overflow: auto; display: flex; justify-content: center;">
                    <el-form ref="roleFormRef" :model="roleFormEntity" :label-position="labelPosition"
                        label-width="100px" style="width: 95%;" :rules="rules" status-icon>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="角色id" prop="roleId">
                                    <el-input v-model="roleFormEntity.roleId" disabled />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="角色名" prop="roleName">
                                    <el-input v-model="roleFormEntity.roleName" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="权限" prop="permission">
                                    <el-tree ref="permissionRef" style="max-width: 600px"
                                        :data="roleFormEntity.permissionTreeData" show-checkbox default-expand-all
                                        node-key="id" highlight-current :props="defaultProps" />
                                </el-form-item></el-col>
                        </el-row>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitInfo(roleFormEntity)">
                            确认更新
                        </el-button>
                    </span>
                </template>
            </el-dialog>
            <el-dialog v-model="addRoleDialogVisible" title="添加角色信息" width="40%" draggable :show-close="false">
                <div
                    style="max-width: 100%; max-height: 350px; overflow: auto; display: flex; justify-content: center;">
                    <el-form ref="addRoleFormRef" :model="addRoleFormEntity" :label-position="labelPosition"
                        label-width="100px" style="width: 95%;" :rules="rules" status-icon>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="角色id" prop="roleId">
                                    <el-input v-model="addRoleFormEntity.roleId" disabled />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="角色名" prop="roleName">
                                    <el-input v-model="addRoleFormEntity.roleName" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="权限" prop="permission">
                                    <el-tree ref="addRolePermissionRef" style="max-width: 600px"
                                        :data="addRoleFormEntity.permissionTreeData" show-checkbox default-expand-all
                                        node-key="id" highlight-current :props="defaultProps" />
                                </el-form-item></el-col>
                        </el-row>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="addRoleDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitAddRole(addRoleFormEntity)">
                            确认添加
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </el-config-provider>
    </div>
</template>

<script setup>
import store from '@/store'
import { getRoleList, getPermissionList, updateRoleInfo, deleteRoleInfo, addRoleInfo } from '@/api/user.js'
import { errorBox } from '@/utils/myMessageBox.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'
import { dateFormatter, timeFormatter } from '@/utils/formatter.js'
import { Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
</script>
<script>
export default {
    name: 'role_permission',
    data() {
        return {
            roleList: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,
            roleNameQuery: '',
            loading: true,
            dialogVisible: false,
            roleId: '',
            roleFormEntity: reactive({}),
            roleFormRef: ref(),
            labelPosition: 'top',
            rules: reactive({}),
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            addRoleDialogVisible: false,
            addRoleFormEntity: reactive({}),
            addRoleFormRef: ref(),
        }
    },
    mounted() {
        this.search()
    },
    methods: {
        search() {
            this.loading = true
            const request = {
                pageNo: this.currentPage,
                pageSize: this.pageSize,
                userName: store.getters.getUserName,
                roleId: store.getters.getUser.roleId,
                roleName: this.roleNameQuery.trim()
            }
            getRoleList(request).then(res => {
                const tableResponse = res.data
                if (tableResponse.code == 0) {
                    this.roleList = tableResponse.returnData.lists
                    this.total = tableResponse.returnData.total
                } else {
                    errorBox(tableResponse.message)
                }
            }).catch(err => {
                console.log(err)
                errorBox('查询角色列表错误')
            })
            this.loading = false
        },
        dateFormat: (row, column, cellValue, index) => {
            return dateFormatter(cellValue)
        },
        timeFormat: (row, column, cellValue, index) => {
            return timeFormatter(cellValue)
        },
        reset() {
            this.standIdQuery = ''
            this.standTypeQuery = -99
            this.search()
        },
        editCurrentRow(row) {
            this.roleId = row.roleId
            if (store.getters.getUser.roleId != 1) {
                errorBox("操作人必须是管理员级别。")
                return
            }
            // 获取权限
            this.loading = true
            const request = {
                roleId1: store.getters.getUser.roleId,
                roleId2: row.roleId,
                userName: store.getters.getUserName
            }
            getPermissionList(request).then(res => {
                const response = res.data
                if (response.code == 0) {
                    this.roleFormEntity = {
                        roleId: row.roleId,
                        roleName: row.roleName,
                        permissionTreeData: response.returnData.menu
                    }
                    // 设置选中
                    this.$refs.permissionRef.setCheckedKeys(response.returnData.menuIds, false)
                } else {
                    errorBox(response.message)
                    this.dialogVisible = false
                }
            }).catch(err => {
                console.log(err)
                errorBox('查询权限列表错误')
                this.dialogVisible = false
            })
            this.loading = false
            this.dialogVisible = true
        },
        openAddRoleDialog() {
            if (store.getters.getUser.roleId != 1) {
                errorBox("操作人必须是管理员级别。")
                return
            }
            // 获取权限
            this.loading = true
            const request = {
                roleId1: store.getters.getUser.roleId,
                roleId2: null,
                userName: store.getters.getUserName
            }
            getPermissionList(request).then(res => {
                const response = res.data
                if (response.code == 0) {
                    this.addRoleFormEntity = {
                        roleId: '',
                        roleName: '',
                        permissionTreeData: response.returnData.menu
                    }
                    // 设置选中
                    this.$refs.addRolePermissionRef.setCheckedKeys([], false)
                } else {
                    errorBox(response.message)
                    this.addRoleDialogVisible = false
                }
            }).catch(err => {
                console.log(err)
                errorBox('查询权限列表错误')
                this.addRoleDialogVisible = false
            })
            this.loading = false
            this.addRoleDialogVisible = true
        },
        submitInfo(formData) {
            const params = {
                roleId1: store.getters.getUser.roleId,
                roleId2: formData.roleId,
                role2Name: formData.roleName,
                menuIds: this.$refs.permissionRef.getCheckedKeys(false),
                userName: store.getters.getUserName
            }
            updateRoleInfo(params).then(res => {
                if (res.data.code == 0) {
                    this.dialogVisible = false
                    ElMessage.success('更新角色信息成功。')
                    this.search()
                } else {
                    errorBox(res.data.message)
                }
            }).catch(err => {
                console.log(err)
                errorBox('更新角色信息失败。')
            })
        },
        submitAddRole(formData) {
            const params = {
                roleId1: store.getters.getUser.roleId,
                roleId2: formData.roleId,
                role2Name: formData.roleName,
                menuIds: this.$refs.addRolePermissionRef.getCheckedKeys(false),
                userName: store.getters.getUserName
            }
            addRoleInfo(params).then(res => {
                if (res.data.code == 0) {
                    this.addRoleDialogVisible = false
                    ElMessage.success('添加角色信息成功。')
                    this.search()
                } else {
                    errorBox(res.data.message)
                }
            }).catch(err => {
                console.log(err)
                errorBox('添加角色信息失败。')
            })
        },
        deleteCurrentRow(row) {
            this.roleId = row.roleId
            if (store.getters.getUser.roleId != 1) {
                errorBox("操作人员必须是管理员级别。")
                return
            }
            ElMessageBox.confirm(
                '该操作会从数据库中删除角色。\n是否继续',
                '警告',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                const params = {
                    roleId1: store.getters.getUser.roleId,
                    roleId2: row.roleId,
                    userName: store.getters.getUserName
                }
                deleteRoleInfo(params).then(res => {
                    if (res.data.code == 0) {
                        ElMessage.success('删除角色信息成功。')
                        this.search()
                    } else {
                        errorBox(res.data.message)
                    }
                }).catch(err => {
                    console.log(err)
                    errorBox('删除角色信息失败。')
                })
            }).catch(() => {
                ElMessage.info('操作取消')
            })
        },
        getCurrentRow(row) {
            this.roleId = row.roleId
        },
    },
}
</script>

<style scoped>
.el-pagination {
    padding-left: 5px;
}

.el-row .el-button {
    width: 72px;
    margin-left: 0px;
    margin-right: 5px;
}

.table-class {
    width: 100%;
}

.el-row .el-form-item {
    width: 10% inherit;
    justify-content: center;
}

.el-row .el-form-item .el-select-v2 {
    width: 100% !important;
}

.el-row .el-form-item .el-input-number {
    width: 100% !important;
}

.el-row .el-form-item .el-button {
    margin: auto;
}

.title-area {
    display: flex;
    /* min-height: 10%; */
    max-height: max-content;
    margin-bottom: 10px;
    min-width: inherit;
    border: solid 1px;
    border-radius: 10px;
    box-shadow: 0px 15px 10px -15px #000;
    overflow: auto;
    flex-direction: column;
    padding: 10px;
}
</style>