<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.keyword"
                                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%">
                            <el-table-column type="index" label="序号" width="70" align="center" :index="formatIndex"></el-table-column>
                            <el-table-column prop="name" label="角色名称" min-width="200"></el-table-column>
                            <el-table-column prop="desc" label="权限描述" min-width="320"></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">
                                    <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>
                            </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="960px"
            class="role-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">
                <div class="role-info">
                    <div class="role-tabs">
                        <div class="tab-item">
                            <div class="tab-label">角色名称</div>
                            <el-input v-model="addForm.name" style="border: 1px solid #ededed;" placeholder="请输入角色名称" size="small"></el-input>
                        </div>
                        <div class="tab-item">
                            <div class="tab-label">权限描述</div>
                            <el-input v-model="addForm.desc" style="border: 1px solid #ededed;" placeholder="请输入权限描述" size="small"></el-input>
                        </div>
                    </div>
                    <div class="role-tabs">
                        <div class="tab-item single">
                            <div class="tab-label">权限分配</div>
                        </div>
                    </div>
                </div>

                <div class="permission-tree">
                    <el-tree
                        ref="permissionTree"
                        :data="quanxianDate"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :props="permissionTreeProps"
                        :default-checked-keys="checkedPermissionKeys">
                    </el-tree>
                </div>
            </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 { save, deletes, role, detail,all } from '@/api/system/Permission/user'
export default {
    data() {
        return {
            quanxianDate:[],
            queryForm: {
                keyword: ''
            },
            currentPage: 1,
            pageSize: 10,
            addDialogVisible: false,
            editMode: false, // 标记是编辑还是新增
            addForm: {
                id: null,
                name: '', // 与接口字段保持一致
                desc: '', // 与接口字段保持一致
                rules: '' // 权限ID字符串（保存时使用）
            },
            loading: false,
            tableData: [],
            total: 0, // 总记录数
            permissionTreeProps: {
                children: 'children',
                label: 'title' // 根据接口数据结构，使用 title 字段
            },
            permissionTreeData: [
                {
                    id: 'overview',
                    label: '企业总览'
                },
                {
                    id: 'resource',
                    label: '资源资料',
                    children: [
                        { id: 'finance', label: '财务管理' },
                        { id: 'hr', label: '人力资源' },
                        {
                            id: 'achievement',
                            label: '成果管理',
                            children: [
                                {
                                    id: 'ip',
                                    label: '知识产权',
                                    children: [
                                        { id: 'patent', label: '发明专利' },
                                        { id: 'software', label: '软件著作' },
                                        { id: 'ic', label: '集成电路布图设计专有权' }
                                    ]
                                },
                                { id: 'paper', label: '论文管理' },
                                { id: 'contract', label: '合同登记' }
                            ]
                        }
                    ]
                },
                {
                    id: 'projects',
                    label: '项目管理'
                },
                {
                    id: 'apply',
                    label: '申报中心'
                },
                {
                    id: 'hightech',
                    label: '高企认定'
                },
                {
                    id: 'special',
                    label: '专精特新'
                },
                {
                    id: 'deduction',
                    label: '加计扣除'
                }
            ],
        }
    },
    mounted() {
        this.fetchRoleList()
        this.getall()
    },
    computed: {
        pagedData() {
            // 如果后端支持分页，直接使用 tableData
            return this.tableData
        },
        // 将 rules 字符串转换为数组，用于权限树回显
        checkedPermissionKeys() {
            if (!this.addForm.rules || typeof this.addForm.rules !== 'string') {
                return []
            }
            try {
                // 尝试解析为数组（可能是逗号分隔的字符串或JSON字符串）
                if (this.addForm.rules.startsWith('[') || this.addForm.rules.startsWith('{')) {
                    // JSON格式
                    const parsed = JSON.parse(this.addForm.rules)
                    return Array.isArray(parsed) ? parsed.map(id => Number(id)) : []
                } else {
                    // 逗号分隔的字符串
                    return this.addForm.rules.split(',').filter(id => id.trim()).map(id => Number(id.trim()))
                }
            } catch (error) {
                console.error('解析权限字符串失败:', error)
                return []
            }
        }
    },
    methods: {
        //获取菜单
        async getall() {
            try {
                const response = await all()
                if (response && response.code === 1 && response.data) {
                    this.quanxianDate = response.data
                    console.log('获取的菜单数据:', this.quanxianDate)
                } else {
                    console.error('获取菜单失败:', response?.msg)
                    this.quanxianDate = []
                }
            } catch (error) {
                console.error('获取菜单异常:', error)
                this.quanxianDate = []
            }
        },
        // 获取角色列表
        async fetchRoleList() {
            this.loading = true
            try {
                const response = await role({
                    keyword: this.queryForm.keyword || '',
                    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.tableData = []
                this.total = 0
            } finally {
                this.loading = false
            }
        },
        handleSearch() {
            this.currentPage = 1
            this.fetchRoleList()
        },
        handleAdd() {
            this.editMode = false
            this.resetAddDialog()
            this.addDialogVisible = true
            this.$nextTick(() => {
                if (this.$refs.permissionTree) {
                    this.$refs.permissionTree.setCheckedKeys(this.checkedPermissionKeys)
                }
            })
        },
        async handleEdit(row) {
            this.editMode = true
            try {
                const response = await detail(row.id)
                if (response && response.code === 1 && response.data) {
                    // 处理权限字段，优先使用 rules，如果没有则尝试其他字段
                    let rulesStr = ''
                    if (response.data.rules) {
                        rulesStr = typeof response.data.rules === 'string' ? response.data.rules : String(response.data.rules)
                    } else if (response.data.permissions) {
                        // 兼容处理：如果是数组，转换为字符串
                        if (Array.isArray(response.data.permissions)) {
                            rulesStr = response.data.permissions.join(',')
                        } else {
                            rulesStr = String(response.data.permissions)
                        }
                    } else if (row.rules) {
                        rulesStr = typeof row.rules === 'string' ? row.rules : String(row.rules)
                    }
                    
                    this.addForm = {
                        id: response.data.id || row.id,
                        name: response.data.name || response.data.roleName || row.name || '',
                        desc: response.data.desc || response.data.description || row.desc || '',
                        rules: rulesStr
                    }
                    this.addDialogVisible = true
                    this.$nextTick(() => {
                        if (this.$refs.permissionTree) {
                            this.$refs.permissionTree.setCheckedKeys(this.checkedPermissionKeys)
                        }
                    })
                } else {
                    // 如果接口失败，使用当前行数据
                    const rulesStr = row.rules ? (typeof row.rules === 'string' ? row.rules : String(row.rules)) : ''
                    this.addForm = {
                        id: row.id,
                        name: row.name || '',
                        desc: row.desc || '',
                        rules: rulesStr
                    }
                    this.addDialogVisible = true
                    this.$nextTick(() => {
                        if (this.$refs.permissionTree) {
                            this.$refs.permissionTree.setCheckedKeys(this.checkedPermissionKeys)
                        }
                    })
                }
            } catch (error) {
                console.error('获取角色详情失败:', error)
                // 如果接口失败，使用当前行数据
                const rulesStr = row.rules ? (typeof row.rules === 'string' ? row.rules : String(row.rules)) : ''
                this.addForm = {
                    id: row.id,
                    name: row.name || '',
                    desc: row.desc || '',
                    rules: rulesStr
                }
                this.addDialogVisible = true
                this.$nextTick(() => {
                    if (this.$refs.permissionTree) {
                        this.$refs.permissionTree.setCheckedKeys(this.checkedPermissionKeys)
                    }
                })
            }
        },
        async handleDelete(row) {
            this.$confirm(`确认删除【${row.name || row.roleName || '该角色'}】吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const response = await deletes(row.id)
                    if (response && response.code === 1) {
                        this.$message.success('删除成功')
                        this.fetchRoleList() // 刷新列表
                    } else {
                        this.$message.error(response?.msg || '删除失败')
                    }
                } catch (error) {
                    console.error('删除角色失败:', error)
                    this.$message.error('删除失败')
                }
            }).catch(() => {})
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.currentPage = 1
            this.fetchRoleList() // 重新获取数据
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.fetchRoleList() // 重新获取数据
        },
        formatIndex(index) {
            return (this.currentPage - 1) * this.pageSize + index + 1
        },
        rowClassName() {
            return 'role-row'
        },
        cellStyle({ column }) {
            const leftAlignedProps = ['name', 'desc', 'create_time']
            return {
                textAlign: leftAlignedProps.includes(column.property) ? 'left' : 'center',
                color: '#363636'
            }
        },
        cancelAdd() {
            this.addDialogVisible = false
        },
        async submitAdd() {
            if (!this.addForm.name || !this.addForm.name.trim()) {
                this.$message.warning('请输入角色名称')
                return
            }
            // 获取选中的权限ID（只获取叶子节点，true表示只返回叶子节点）
            const permissionIds = this.$refs.permissionTree ? this.$refs.permissionTree.getCheckedKeys(true) : []
            // 将权限ID数组转换为字符串（逗号分隔）
            const rulesStr = permissionIds.join(',')
            
            try {
                const response = await save({
                    id: this.editMode ? this.addForm.id : undefined,
                    name: this.addForm.name.trim(),
                    desc: this.addForm.desc || '',
                    rules: rulesStr // 权限ID字符串（逗号分隔）
                })
                
                if (response && response.code === 1) {
                    this.$message.success(this.editMode ? '修改成功' : '添加成功')
                    this.addDialogVisible = false
                    this.resetAddDialog()
                    this.fetchRoleList() // 刷新列表
                } else {
                    this.$message.error(response?.msg || '保存失败')
                }
            } catch (error) {
                console.error('保存角色失败:', error)
                this.$message.error('保存失败')
            }
        },
        resetAddDialog() {
            this.editMode = false
            this.addForm = {
                id: null,
                name: '',
                desc: '',
                rules: ''
            }
            if (this.$refs.permissionTree) {
                this.$refs.permissionTree.setCheckedKeys([])
            }
        },
        formatDateTime(date) {
            const pad = (n) => (n < 10 ? `0${n}` : n)
            const year = date.getFullYear()
            const month = pad(date.getMonth() + 1)
            const day = pad(date.getDate())
            const hours = pad(date.getHours())
            const minutes = pad(date.getMinutes())
            const seconds = pad(date.getSeconds())
            return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
        }
    }
}
</script>

<style scoped>
.coentent {
    width: 100%;
    height: 100%;
    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 .role-row td {
    color: #363636;
}

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

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

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

.role-add-dialog ::v-deep .el-dialog__body {
    padding: 0 32px 24px;
}

.role-add-dialog ::v-deep .el-dialog__footer {
    padding: 20px 32px 28px;
    border-top: none;
}

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

.role-info {
    padding: 12px 0;
}

.role-tabs {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
    margin-bottom: 12px;
}

.role-tabs .tab-item.single {
    grid-column: 1 / -1;
}

.tab-item {
    display: flex;
    align-items: center;
    gap: 12px;
}

.tab-label {
    font-size: 13px;
    color: #6A6E8C;
    margin-bottom: 0;
    width: 90px;
    flex-shrink: 0;
}

.tab-item:not(.single) .el-input {
    flex: 1;
}

.tab-item.single {
    display: block;
}

.tab-item.single .tab-label {
    margin-bottom: 6px;
    width: auto;
}

.permission-tree {
    max-height: 360px;
    overflow: auto;
    border: 1px solid #E0E3F5;
    border-radius: 8px;
    padding: 16px 20px;
    background: #F8F9FF;
}

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

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