{% extends "base.html" %}

{% block title %}权限管理 - AI 视界{% endblock %}

{% block content %}
<div class="w-full h-full overflow-y-auto p-8 lg:p-12 custom-scrollbar">
    <div class="max-w-6xl mx-auto space-y-12">
        <!-- 头部 -->
        <div class="flex items-center justify-between">
            <div class="flex items-center gap-4">
                <div class="w-12 h-12 bg-indigo-600 text-white rounded-2xl flex items-center justify-center shadow-lg shadow-indigo-200">
                    <i data-lucide="shield-check" class="w-7 h-7"></i>
                </div>
                <div>
                    <h1 class="text-3xl font-black text-slate-900 tracking-tight">动态 RBAC 权限中心</h1>
                    <p class="text-slate-400 text-sm">动态配置系统角色与权限资产</p>
                </div>
            </div>
            <a href="/" class="btn-primary px-6 py-3 rounded-xl text-sm font-bold shadow-lg">返回工作台</a>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 左侧：编辑/创建角色 -->
            <div class="lg:col-span-1 space-y-6">
                <div class="bg-white p-8 rounded-[2.5rem] shadow-xl border border-slate-100">
                    <h3 id="formTitle" class="text-lg font-black text-slate-900 mb-6 flex items-center gap-2">
                        <i data-lucide="plus-circle" class="w-5 h-5 text-indigo-500"></i>创建新角色
                    </h3>
                    <div class="space-y-4">
                        <input type="hidden" id="editRoleId">
                        <input id="newRoleName" type="text" placeholder="角色名称 (如: 审核员)" class="w-full bg-slate-50 border border-slate-100 rounded-2xl p-4 text-sm font-bold outline-none focus:border-indigo-500">
                        <textarea id="newRoleDesc" placeholder="角色描述" class="w-full bg-slate-50 border border-slate-100 rounded-2xl p-4 text-sm font-medium outline-none focus:border-indigo-500 h-24 resize-none"></textarea>
                        
                        <div class="space-y-2">
                            <label class="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">分配权限</label>
                            <div id="permissionCheckboxes" class="grid grid-cols-1 gap-2 bg-slate-50 p-4 rounded-2xl">
                                <!-- 动态加载 -->
                            </div>
                        </div>

                        <div class="flex gap-3">
                            <button id="cancelEditBtn" class="hidden flex-1 px-4 py-4 rounded-2xl border border-slate-100 text-slate-400 font-bold hover:bg-slate-50 transition-all">取消</button>
                            <button id="saveRoleBtn" class="flex-[2] btn-primary py-4 rounded-2xl shadow-lg font-bold">保存角色</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧：现有角色 & 用户管理 -->
            <div class="lg:col-span-2 space-y-8">
                <!-- 角色列表 -->
                <div class="bg-white rounded-[2.5rem] shadow-xl border border-slate-100 overflow-hidden">
                    <div class="p-8 border-b border-slate-50">
                        <h3 class="text-lg font-black text-slate-900 flex items-center gap-2">
                            <i data-lucide="users" class="w-5 h-5 text-indigo-500"></i>角色资产列表
                        </h3>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left">
                            <thead>
                                <tr class="bg-slate-50">
                                    <th class="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">角色名称</th>
                                    <th class="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">描述</th>
                                    <th class="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">权限集</th>
                                    <th class="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">操作</th>
                                </tr>
                            </thead>
                            <tbody id="roleTableBody">
                                <!-- 动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- 用户列表 -->
                <div class="bg-white rounded-[2.5rem] shadow-xl border border-slate-100 overflow-hidden">
                    <div class="p-8 border-b border-slate-50">
                        <h3 class="text-lg font-black text-slate-900 flex items-center gap-2">
                            <i data-lucide="user-cog" class="w-5 h-5 text-indigo-500"></i>用户角色分配
                        </h3>
                    </div>
                    <table class="w-full text-left">
                        <thead>
                            <tr class="bg-slate-50">
                                <th class="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">用户手机</th>
                                <th class="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">当前角色</th>
                                <th class="px-8 py-4 text-[10px] font-black text-slate-400 uppercase tracking-widest">操作</th>
                            </tr>
                        </thead>
                        <tbody id="userTableBody">
                            <!-- 动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let allRoles = [];

    async function loadPermissions() {
        const r = await fetch('/api/admin/permissions');
        const d = await r.json();
        const container = document.getElementById('permissionCheckboxes');
        container.innerHTML = d.permissions.map(p => `
            <label class="flex items-center gap-3 cursor-pointer group">
                <input type="checkbox" value="${p.name}" class="w-4 h-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500">
                <span class="text-xs font-bold text-slate-600 group-hover:text-slate-900">${p.description}</span>
            </label>
        `).join('');
    }

    async function loadRoles() {
        const r = await fetch('/api/admin/roles');
        const d = await r.json();
        allRoles = d.roles;
        const container = document.getElementById('roleTableBody');
        container.innerHTML = d.roles.map(role => `
            <tr class="border-b border-slate-50 hover:bg-slate-50/50 transition-colors">
                <td class="px-8 py-5">
                    <div class="font-black text-slate-900">${role.name}</div>
                    <div class="text-[10px] text-slate-400 font-bold uppercase tracking-tighter">ID: ${role.id}</div>
                </td>
                <td class="px-8 py-5 text-xs text-slate-500 max-w-[150px] truncate">${role.description || '-'}</td>
                <td class="px-8 py-5">
                    <div class="flex flex-wrap gap-1 max-w-[240px]">
                        ${role.permissions.map(p => `<span class="px-1.5 py-0.5 bg-indigo-50 text-indigo-500 text-[9px] font-black rounded uppercase border border-indigo-100/50">${p}</span>`).join('')}
                    </div>
                </td>
                <td class="px-8 py-5">
                    <div class="flex gap-2">
                        <button onclick='editRole(${JSON.stringify(role)})' class="p-2 text-indigo-400 hover:bg-indigo-50 rounded-xl transition-all">
                            <i data-lucide="edit-2" class="w-4 h-4"></i>
                        </button>
                        ${role.name !== '超级管理员' ? `
                            <button onclick="deleteRole(${role.id})" class="p-2 text-rose-300 hover:bg-rose-50 rounded-xl transition-all">
                                <i data-lucide="trash-2" class="w-4 h-4"></i>
                            </button>
                        ` : ''}
                    </div>
                </td>
            </tr>
        `).join('');
        lucide.createIcons();
    }

    function editRole(role) {
        document.getElementById('formTitle').innerHTML = `<i data-lucide="edit-3" class="w-5 h-5 text-indigo-500"></i>编辑角色`;
        document.getElementById('editRoleId').value = role.id;
        document.getElementById('newRoleName').value = role.name;
        document.getElementById('newRoleDesc').value = role.description || '';
        document.getElementById('cancelEditBtn').classList.remove('hidden');
        
        // 重置并勾选权限
        document.querySelectorAll('#permissionCheckboxes input').forEach(cb => {
            cb.checked = role.permissions.includes(cb.value);
        });
        lucide.createIcons();
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    document.getElementById('cancelEditBtn').onclick = resetForm;

    function resetForm() {
        document.getElementById('formTitle').innerHTML = `<i data-lucide="plus-circle" class="w-5 h-5 text-indigo-500"></i>创建新角色`;
        document.getElementById('editRoleId').value = '';
        document.getElementById('newRoleName').value = '';
        document.getElementById('newRoleDesc').value = '';
        document.getElementById('cancelEditBtn').classList.add('hidden');
        document.querySelectorAll('#permissionCheckboxes input').forEach(cb => cb.checked = false);
        lucide.createIcons();
    }

    async function deleteRole(id) {
        if(!confirm('确定要删除此角色吗？所有关联该角色的用户将失去权限。')) return;
        const r = await fetch('/api/admin/roles/delete', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ id })
        });
        const d = await r.json();
        if(d.message) {
            showToast(d.message, 'success');
            loadRoles();
            loadUsers();
        } else {
            showToast(d.error, 'error');
        }
    }

    async function loadUsers() {
        const r = await fetch('/api/admin/users');
        const d = await r.json();
        const body = document.getElementById('userTableBody');
        body.innerHTML = d.users.map(user => `
            <tr class="border-b border-slate-50">
                <td class="px-8 py-4 text-sm font-bold text-slate-700">${user.phone}</td>
                <td class="px-8 py-4">
                    <span class="px-3 py-1 bg-indigo-50 text-indigo-600 rounded-full text-xs font-black">${user.role}</span>
                </td>
                <td class="px-8 py-4">
                    <select onchange="assignRole(${user.id}, this.value)" class="bg-white border border-slate-200 rounded-xl px-3 py-1.5 text-xs font-bold outline-none">
                        <option value="">更改角色...</option>
                        ${allRoles.map(role => `<option value="${role.id}">${role.name}</option>`).join('')}
                    </select>
                </td>
            </tr>
        `).join('');
    }

    async function assignRole(userId, roleId) {
        if(!roleId) return;
        const r = await fetch('/api/admin/users/assign', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ user_id: userId, role_id: roleId })
        });
        const d = await r.json();
        if(d.message) {
            showToast(d.message, 'success');
            loadUsers();
        }
    }

    document.getElementById('saveRoleBtn').onclick = async () => {
        const id = document.getElementById('editRoleId').value;
        const name = document.getElementById('newRoleName').value;
        const description = document.getElementById('newRoleDesc').value;
        const permissions = Array.from(document.querySelectorAll('#permissionCheckboxes input:checked')).map(i => i.value);
        
        if(!name) return showToast('请输入角色名称', 'warning');

        const r = await fetch('/api/admin/roles', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ id, name, description, permissions })
        });
        const d = await r.json();
        if(d.message) {
            showToast(d.message, 'success');
            loadRoles();
            loadUsers();
            resetForm();
        } else {
            showToast(d.error, 'error');
        }
    };

    async function init() {
        await loadPermissions();
        await loadRoles();
        await loadUsers();
    }
    init();
</script>
{% endblock %}