<template>
    <div>
        <div class="coentent">
            <div class="contents-area">
                <div class="areas">
                    <div class="headers">
                        <div class="headers-left">
                            <div class="headers-name">用户列表</div>
                        </div>
                        <div class="headers-right">
                            <el-input
                                placeholder="输入姓名"
                                v-model="queryForm.nickname"
                                class="search-input"
                                size="small"
                                clearable>
                                <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                            </el-input>
                            <el-button type="primary" size="small" class="add-btn" @click="handleAdd">添加用户</el-button>
                        </div>
                    </div>

                    <div class="content-table">
                        <el-table
                            :data="pagedData || []"
                            border
                            v-loading="loading"
                            :header-cell-style="{ background: '#EDEFFE', color: '#363636', textAlign: 'center' }"
                            :cell-style="cellStyle"
                            :row-class-name="rowClassName"
                            style="width: 100%"
                            v-if="!loading || pagedData.length > 0">
                            <el-table-column type="index" label="序号" width="70" align="center" :index="formatIndex"></el-table-column>
                            <el-table-column prop="nickname" label="姓名" min-width="120"></el-table-column>
                            <el-table-column prop="department" label="所属部门" min-width="140" #default="scope">
                                <span v-if=" scope.row.user" style="    display: flex;justify-content: center;"> {{ scope.row.user.department.name ||"" }}</span>
                            </el-table-column>
                            <el-table-column prop="position" label="职务" min-width="120" #default="scope">
                                <span v-if=" scope.row.user" style="    display: flex;justify-content: center;"> {{ scope.row.user.position.name ||"" }}</span>
                            </el-table-column>
                            <el-table-column prop="phone" label="账号（手机号）" min-width="180" >
                        
                            </el-table-column>
                            <el-table-column prop="role" label="角色" min-width="200" align="center">
                                <template #default="scope">
                                    <span style="display: flex; justify-content: center;">
                                        {{ getRoleName(scope.row) }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="create_time" label="添加时间" min-width="180"></el-table-column>
                            <el-table-column label="操作" width="160" align="center">
                                <template #default="scope">
                                    <template v-if="scope.row.id === 1">
                                        <el-button type="text" class="link-btn" @click="handleTransfer(scope.row)">移交超管</el-button>
                                    </template>
                                    <template v-else>
                                        <el-button type="text" class="link-btn" @click="handleEdit(scope.row)">修改</el-button>
                                        <el-button type="text" class="danger-btn" @click="handleDelete(scope.row)">删除</el-button>
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="footer">
                            <el-pagination
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="currentPage"
                                :page-sizes="[10, 20, 30, 50]"
                                :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total">
                            </el-pagination>
                        </div>
                        </div>
                </div>
            </div>
        </div>

        <el-dialog
            :visible.sync="addDialogVisible"
            width="920px"
            class="user-add-dialog"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            @closed="resetAddDialog">
            <template #title>
                <div class="dialog-title">{{ editMode ? '修改用户' : '添加用户' }}</div>
            </template>
            <div class="dialog-content">
                <el-form :model="addForm" ref="addForm" label-width="0">
                    <div class="form-grid">
                        <div class="form-row">
                            <div class="form-label">选择人员</div>
                            <div class="form-field">
                                <el-select 
                                    v-model="addForm.uid" 
                                    placeholder="请选择" 
                                    size="small" 
                                    filterable
                                    @change="handleStaffChange">
                                    <el-option 
                                        v-for="item in staffOptions" 
                                        :key="item.id || item.uid" 
                                        :label="item.name || item.nickname" 
                                        :value="item.id || item.uid">
                                    </el-option>
                                </el-select>
                            </div>
                            <div class="form-label">账号（手机号码）</div>
                            <div class="form-field">
                                <el-input v-model="addForm.phone" placeholder="请输入" size="small"></el-input>
                            </div>
                           
                        </div>
                        <div class="form-row">
                            <div class="form-label">角色</div>
                            <div class="form-field">
                                <el-select v-model="addForm.group_id" placeholder="请选择" size="small" filterable>
                                    <el-option 
                                        v-for="item in roleOptions" 
                                        :key="item.id || item.group_id" 
                                        :label="item.name || item.title" 
                                        :value="item.id || item.group_id">
                                    </el-option>
                                </el-select>
                            </div>
                            <div class="form-label">设置密码</div>
                            <div class="form-field">
                                <el-input 
                                    v-model="addForm.password" 
                                    :placeholder="editMode ? '不修改请留空' : '请输入密码'" 
                                    type="password"
                                    size="small">
                                </el-input>
                            </div>
                           
                        </div>
                      
                    </div>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="small" @click="cancelAdd">取消</el-button>
                    <el-button type="primary" size="small" @click="submitAdd">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { admin,save,detail,deletes,role,staffList} from '@/api/system/Permission/role'
export default {
    name: 'Role',
    data() {
        return {
            queryForm: {
                nickname: ''
            },
            currentPage: 1,
            pageSize: 10,
            addDialogVisible: false,
            editMode: false, // 标记是编辑还是新增
            addForm: {
                id: null,
               "uid": "", 
                "phone": "", 
                "group_id": "", 
                "password": "" 
            },
            staffOptions: [], // 人员列表
            roleOptions: [], // 角色列表
            tableData: [],
            loading: false,
            total: 0 // 总记录数
        }
    },
    mounted() {
        console.log('Role component mounted, route:', this.$route.path)
        // 延迟加载数据，确保组件先渲染
        this.$nextTick(() => {
            this.fetchUserList()
            this.fetchStaffList()
            this.fetchRoleList()
        })
    },
    errorCaptured(err, instance, info) {
        // 捕获组件错误
        console.error('Role component error:', err, info)
        this.$message.error('页面渲染出错，请刷新重试')
        return false
    },
    computed: {
        // 如果后端支持分页，直接使用 tableData
        // 如果后端不支持分页，使用前端分页
        pagedData() {
            // 如果后端返回了分页数据，直接使用
            return this.tableData
        }
    },
    methods: {
        // 获取用户列表
        async fetchUserList() {
            this.loading = true
            try {
                const response = await admin({
                    keyword: this.queryForm.nickname || '',
                    page: this.currentPage,
                    pageSize: this.pageSize
                })
                if (response && response.code === 1 && response.data) {
                    // 如果返回的是分页数据
                    if (response.data.list) {
                        this.tableData = response.data.list
                        this.total = response.data.total || response.data.list.length
                    } else if (response.data.data && Array.isArray(response.data.data)) {
                        // 另一种可能的数据结构
                        this.tableData = response.data.data
                        this.total = response.data.total || response.data.data.length
                    } else if (Array.isArray(response.data)) {
                        // 直接返回数组
                        this.tableData = response.data
                        this.total = response.data.length
                    } else {
                        this.tableData = []
                        this.total = 0
                    }
                } else {
                    this.tableData = []
                    this.total = 0
                }
            } catch (error) {
                console.error('获取用户列表失败:', error)
                // 不显示错误提示，避免干扰用户，只在控制台记录
                // this.$message.error('获取用户列表失败')
                this.tableData = []
                this.total = 0
            } finally {
                this.loading = false
            }
        },
        handleSearch() {
            this.currentPage = 1
            this.fetchUserList()
        },
        handleAdd() {
            this.editMode = false
            this.resetAddDialog()
            this.addDialogVisible = true
        },
        async handleEdit(row) {
            this.editMode = true
            try {
                const response = await detail(row.id)
                if (response && response.code === 1 && response.data) {
                    this.addForm = {
                        id: response.data.id || row.id,
                        uid: response.data.uid || row.uid || '',
                        phone: response.data.phone || row.phone || '',
                        group_id: response.data.group_id || row.group_id || '',
                        password: '' // 编辑时不显示密码
                    }
                    this.addDialogVisible = true
                } else {
                    // 如果接口失败，使用当前行数据
                    this.addForm = {
                        id: row.id,
                        uid: row.uid || '',
                        phone: row.phone || '',
                        group_id: row.group_id || '',
                        password: '' // 编辑时不显示密码
                    }
                    this.addDialogVisible = true
                }
            } catch (error) {
                console.error('获取用户详情失败:', error)
                // 如果接口失败，使用当前行数据
                this.addForm = {
                    id: row.id,
                    uid: row.uid || '',
                    phone: row.phone || '',
                    group_id: row.group_id || '',
                    password: '' // 编辑时不显示密码
                }
                this.addDialogVisible = true
            }
        },
        async handleDelete(row) {
            this.$confirm(`确认删除【${row.nickname || row.name || '该用户'}】吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const response = await deletes(row.id)
                    if (response && response.code === 1) {
                        this.$message.success('删除成功')
                        this.fetchUserList() // 刷新列表
                    } else {
                        this.$message.error(response?.msg || '删除失败')
                    }
                } catch (error) {
                    console.error('删除用户失败:', error)
                    this.$message.error('删除失败')
                }
            }).catch(() => {})
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.currentPage = 1
            this.fetchUserList() // 重新获取数据
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.fetchUserList() // 重新获取数据
        },
        formatIndex(index) {
            return (this.currentPage - 1) * this.pageSize + index + 1
        },
        rowClassName() {
            return 'user-row'
        },
        cellStyle({ column }) {
            const leftAlignedProps = ['name', 'department', 'position', 'account', 'role', 'createdAt']
            return {
                textAlign: leftAlignedProps.includes(column.property) ? 'left' : 'center',
                color: '#363636'
            }
        },
        cancelAdd() {
            this.addDialogVisible = false
            this.resetAddDialog()
        },
        async submitAdd() {
            // 表单验证
            if (!this.addForm.uid) {
                this.$message.warning('请选择人员')
                return
            }
            if (!this.addForm.phone) {
                this.$message.warning('请输入账号（手机号）')
                return
            }
            if (!this.addForm.group_id) {
                this.$message.warning('请选择角色')
                return
            }
            // 新增时密码必填，编辑时密码可选
            if (!this.editMode && !this.addForm.password) {
                this.$message.warning('请输入密码')
                return
            }
            
            try {
                const submitData = {
                    id: this.editMode ? this.addForm.id : undefined,
                    uid: this.addForm.uid,
                    phone: this.addForm.phone,
                    group_id: this.addForm.group_id
                }
                // 只有填写了密码才提交密码字段
                if (this.addForm.password) {
                    submitData.password = this.addForm.password
                }
                
                const response = await save(submitData)
                
                if (response && response.code === 1) {
                    this.$message.success(this.editMode ? '修改成功' : '添加成功')
                    this.addDialogVisible = false
                    this.resetAddDialog()
                    this.fetchUserList() // 刷新列表
                } else {
                    this.$message.error(response?.msg || '保存失败')
                }
            } catch (error) {
                console.error('保存用户失败:', error)
                this.$message.error('保存失败')
            }
        },
        resetAddDialog() {
            this.editMode = false
            this.addForm = {
                id: null,
                "uid": '', 
                "phone": "", 
                "group_id": "", 
                "password": "" 
            }
        },
        // 获取人员列表
        async fetchStaffList() {
            try {
                const response = await staffList({})
                if (response && response.code === 1 && response.data) {
                    // 处理不同的数据结构
                    if (Array.isArray(response.data)) {
                        this.staffOptions = response.data
                    } else if (response.data.list && Array.isArray(response.data.list)) {
                        this.staffOptions = response.data.list
                    } else if (response.data.data && Array.isArray(response.data.data)) {
                        this.staffOptions = response.data.data
                    } else {
                        this.staffOptions = []
                    }
                } else {
                    this.staffOptions = []
                }
            } catch (error) {
                console.error('获取人员列表失败:', error)
                this.staffOptions = []
            }
        },
        // 获取角色列表
        async fetchRoleList() {
            try {
                const response = await role({})
                if (response && response.code === 1 && response.data) {
                    // 处理不同的数据结构
                    if (Array.isArray(response.data)) {
                        this.roleOptions = response.data
                    } else if (response.data.list && Array.isArray(response.data.list)) {
                        this.roleOptions = response.data.list
                    } else if (response.data.data && Array.isArray(response.data.data)) {
                        this.roleOptions = response.data.data
                    } else {
                        this.roleOptions = []
                    }
                } else {
                    this.roleOptions = []
                }
            } catch (error) {
                console.error('获取角色列表失败:', error)
                this.roleOptions = []
            }
        },
        // 处理选择人员变化
        handleStaffChange(value) {
            if (value) {
                const selectedStaff = this.staffOptions.find(item => (item.id || item.uid) === value)
                if (selectedStaff) {
                    // 自动填充手机号
                    this.addForm.phone = selectedStaff.phone || selectedStaff.mobile || ''
                }
            } else {
                this.addForm.phone = ''
            }
        },
        // 获取角色名称
        getRoleName(row) {
            if (!row.role || !Array.isArray(row.role) || row.role.length === 0) {
                return ''
            }
            const firstRole = row.role[0]
            if (firstRole && firstRole.position && firstRole.position.name) {
                return firstRole.position.name
            }
            if (firstRole && firstRole.name) {
                return firstRole.name
            }
            return ''
        },
        // 处理移交超管
        handleTransfer(row) {
            this.$confirm(`确认将【${row.nickname || row.name || '该用户'}】移交超管吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    // 这里可以调用移交超管的接口
                    // const response = await transferToSuperAdmin(row.id)
                    // 暂时使用提示
                    this.$message.success('移交超管成功')
                    this.fetchUserList() // 刷新列表
                } catch (error) {
                    console.error('移交超管失败:', error)
                    this.$message.error('移交超管失败')
                }
            }).catch(() => {
                // 用户取消，不做任何操作
            })
        }
    }
}
</script>

<style scoped>
.coentent {
    width: 100%;
    height: 100%;
    min-height: 100%;
   
    box-sizing: border-box;
    background: white;
}

.contents-area {
    width: 100%;
    margin-top: 20px;

}

.areas {
    width: 97%;
    margin: 0 auto;
}

.headers {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 16px;
    padding-top: 18px;
}

.headers-left {
    display: flex;
    align-items: center;
    gap: 20px;
}

.headers-name {
    font-size: 15px;
    color: #17192C;
}

.headers-right {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
}

.search-input {
    width: 220px;
    border: 1px solid #ededed;
}

.search-input ::v-deep .el-input-group__append {
    background: #5165F7;
    color: #fff;
}

.add-btn {
    background: #5165F7;
    border-color: #5165F7;
}

.content-table {
    background: #fff;
    border-radius: 8px;
}

.footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.link-btn {
    color: #5165F7;
    padding: 0;
}

.danger-btn {
    color: #F56C6C;
    padding: 0;
}

::v-deep .user-row td {
    color: #363636;
}

::v-deep .el-table__body tr:hover > td {
    background-color: #F7F8FF !important;
}

.user-add-dialog ::v-deep .el-dialog {
    border-radius: 12px;
}

.user-add-dialog ::v-deep .el-dialog__header {
    padding: 20px 24px 12px;
    border-bottom: 1px solid #EBEEF5;
    background: #F7F7FA;
    height: 30px;
}

.user-add-dialog ::v-deep .el-dialog__body {
    padding: 24px 36px 12px;
}

.user-add-dialog ::v-deep .el-dialog__footer {
    padding: 20px 36px 30px;
    border-top: none;
}

.dialog-title {
    font-size: 18px;
    font-weight: 600;
    color: #17192C;
    text-align: center;
}

.form-grid {
    border: 1px solid #E0E3F5;
    border-radius: 8px;
    overflow: hidden;
}

.form-row {
    display: grid;
    grid-template-columns: 160px 1fr 160px 1fr;
    border-bottom: 1px solid #E0E3F5;
}

.form-row:last-child {
    border-bottom: none;
}

.form-label {
    background: #F5F6FE;
    padding: 16px;
    font-size: 14px;
    color: #363636;
    display: flex;
    align-items: center;
}

.form-field {
    padding: 12px 16px;
    display: flex;
    align-items: center;
}

.dialog-footer {
    text-align: center;
}

.dialog-footer .el-button + .el-button {
    margin-left: 16px;
}
</style>