<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="userNameQuery" 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="addOneUser()">新增用户</el-button>
                </el-row>
            </div>
            <br />
            <el-table :data="userList" 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.userId" v-model="userId">&nbsp;</el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="userId" label="id" fixed="left" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="userName" label="用户名" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="roleId" label="角色" :formatter="roleFormat" min-width="120px"
                    show-overflow-tooltip />
                <el-table-column prop="loginAccount" label="登录账户" min-width="120px" show-overflow-tooltip />
                <el-table-column prop="addTime" label="增加时间" :formatter="timeFormat" show-overflow-tooltip
                    min-width="120px" />
                <el-table-column prop="updateTime" label="更新时间" :formatter="timeFormat" min-width="120px"
                    show-overflow-tooltip />
                <el-table-column prop="addUser" label="添加用户" min-width="120px" show-overflow-tooltip />
                <el-table-column fixed="right" label="操作" min-width="120px">
                    <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: 500px; overflow: auto; display: flex; justify-content: center;">
                    <el-form ref="userFormRef" :model="userFormEntity" :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="userId">
                                    <el-input v-model="userFormEntity.userId" disabled />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="用户名" prop="userName">
                                    <el-input v-model="userFormEntity.userName" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="登录账户" prop="loginAccount">
                                    <el-input v-model="userFormEntity.loginAccount" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="角色" prop="roleId">
                                    <el-select-v2 v-model="userFormEntity.roleId" placeholder="请选择角色"
                                        :options="roleOptions"></el-select-v2>
                                </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(userFormEntity)">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
            <el-dialog v-model="addUserDialogVisible" 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="addUserFormRef" :model="addUserFormEntity" :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="角色" prop="roleIdUpdate">
                                    <el-select-v2 v-model="addUserFormEntity.roleIdUpdate" placeholder="请选择角色"
                                        :options="roleOptions"></el-select-v2>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="用户名" prop="userNameUpdate">
                                    <el-input v-model="addUserFormEntity.userNameUpdate" clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="16">
                            <el-col :span="12" :offset="0">
                                <el-form-item label="登录账户" prop="loginAccountUpdate">
                                    <el-input v-model="addUserFormEntity.loginAccountUpdate" clearable />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="登录密码" prop="loginPasswordUpdate">
                                    <el-input v-model="addUserFormEntity.loginPasswordUpdate" show-password clearable />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="addUserDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitAddUser(addUserFormEntity)">
                            确认添加
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </el-config-provider>
    </div>
</template>

<script setup>
import store from '@/store'
import { getUserList, getRoleOptions, updateUserInfo, addUserInfo, deleteUserInfo } 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_user',
    data() {
        return {
            userList: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,
            userNameQuery: '',
            loading: true,
            dialogVisible: false,
            userId: '',
            userFormEntity: reactive({}),
            userFormRef: ref(),
            labelPosition: 'top',
            rules: reactive({}),
            roleOptions: [],
            addUserDialogVisible: false,
            addUserFormEntity: reactive({}),
            addUserFormRef: ref(),
        }
    },
    mounted() {
        this.getRoleOptions()
        this.search()
    },
    methods: {
        getRoleOptions() {
            const request = {
                roleId: store.getters.getUser.roleId,
            }
            getRoleOptions(request).then(res => {
                const tableResponse = res.data
                if (tableResponse.code == 0) {
                    this.roleOptions = tableResponse.returnData
                } else {
                    this.roleOptions = []
                }
            }).catch(err => {
                console.log(err)
                this.roleOptions = []
            })
        },
        search() {
            this.loading = true
            const request = {
                pageNo: this.currentPage,
                pageSize: this.pageSize,
                userName: this.userNameQuery.trim(),
                roleId: store.getters.getUser.roleId,
            }
            getUserList(request).then(res => {
                const tableResponse = res.data
                if (tableResponse.code == 0) {
                    this.userList = 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)
        },
        roleFormat(row, column, cellValue, index) {
            const roleOptionInfo = this.roleOptions.find(item => {
                return item.value == cellValue
            })
            return roleOptionInfo == null|undefined ? '未知角色' : roleOptionInfo.label
        },
        reset() {
            this.userNameQuery = ''
            this.search()
        },
        editCurrentRow(row) {
            this.userId = row.userId
            this.userFormEntity = {
                userId: row.userId,
                userName: row.userName,
                loginAccount: row.loginAccount,
                roleId: row.roleId,
            }
            this.dialogVisible = true
        },
        deleteCurrentRow(row) {
            this.userId = row.userId
            if (store.getters.getUser.roleId != 1) {
                errorBox("操作人员必须是管理员级别。")
                return
            }
            ElMessageBox.confirm(
                '该操作会从数据库中删除用户。\n是否继续',
                '警告',
                {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                const params = {
                    userIdUpdate: row.userId,
                    roleId1: store.getters.getUser.roleId,
                    userName: store.getters.getUserName
                }
                deleteUserInfo(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('操作取消')
            })
        },
        addOneUser() {
            this.addUserFormEntity = {
                roleIdUpdate: null,
                userNameUpdate: '',
                loginAccountUpdate: '',
                loginPasswordUpdate: '',
            }
            this.addUserDialogVisible = true
        },
        submitInfo(formData) {
            const params = {
                roleIdUpdate: formData.roleId,
                userIdUpdate: formData.userId,
                userNameUpdate: formData.userName,
                loginAccountUpdate: formData.loginAccount,
                roleId1: store.getters.getUser.roleId,
                userName: store.getters.getUserName
            }
            updateUserInfo(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('更新用户信息失败。')
            })
        },
        submitAddUser(formData) {
            const params = {
                roleIdUpdate: formData.roleIdUpdate,
                userNameUpdate: formData.userNameUpdate,
                loginAccountUpdate: formData.loginAccountUpdate,
                loginPasswordUpdate: formData.loginPasswordUpdate,
                roleId1: store.getters.getUser.roleId,
                userName: store.getters.getUserName
            }
            addUserInfo(params).then(res => {
                if (res.data.code == 0) {
                    this.addUserDialogVisible = false
                    ElMessage.success('添加用户信息成功。')
                    this.search()
                } else {
                    errorBox(res.data.message)
                }
            }).catch(err => {
                console.log(err)
                errorBox('添加用户信息失败。')
            })
        },
        getCurrentRow(row) {
            this.userId = row.userId
        },
    },
}
</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>