GTong 8 сар өмнө
parent
commit
65279fa92d

+ 2 - 2
config.toml

@@ -3,13 +3,13 @@ ip = "127.0.0.1"
 port = "8080"
 
 [database]
-oadb_ip = "127.0.0.1"
+oadb_ip = "10.28.20.233"
 oadb_port = "5138"
 oadb_db = "OAdb"
 oadb_user = "SYSDBA"
 oadb_password = "SYSDBA"
 
-licdb_ip = "127.0.0.1"
+licdb_ip = "10.28.20.233"
 licdb_port = "5138"
 licdb_db = "license"
 licdb_user = "SYSDBA"

+ 4 - 1
internal/controllers/roles_controllers.go

@@ -85,7 +85,10 @@ func CreateRole(c *gin.Context) {
 		c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintln("解析请求失败: ", err.Error())})
 		return
 	}
-
+	if newRole.Name == "" || newRole.Permissions == nil {
+		c.JSON(http.StatusBadRequest, gin.H{"error": "角色名称或权限不能为空"})
+		return
+	}
 	//检测角色是否已经存在
 	roleTmp, err := models.GetRoleInfo(newRole.Name)
 	if err != nil {

+ 2 - 0
internal/router.go

@@ -82,7 +82,9 @@ func SetupRouter() *gin.Engine {
 		protected.POST("/distributeLicense", middlewares.PermissionMiddleware(middlewares.DispatLicense), controllers.DistributeOALicenseController)
 		//分发按钮校验
 		protected.GET("/GetDistributeButtenCheckController", middlewares.PermissionMiddleware(middlewares.DispatLicense), controllers.GetDistributeButtenCheckController)
+		//分发给用户
 		protected.POST("/DistributeLicenseToUser", middlewares.PermissionMiddleware(middlewares.DispatLicense), controllers.DistributeLicenseToUsersController)
+		//分发给邮箱
 		protected.POST("/DistributeLicenseToEmail", middlewares.PermissionMiddleware(middlewares.DispatLicense), controllers.DistributeLicenseToEmailController)
 
 		//上传文件的license 弃用

+ 27 - 0
static/license_info/license_info.css

@@ -37,6 +37,33 @@ header h1 {
     margin-left: 10px; /* 两个子 div 之间的间距 */
 }
 
+
+
+/* iOS 风格 capture-license 按钮 */
+.capture-license-button {
+    background-color: #76b2f1; /* iOS 风格蓝色 */
+    color: white;
+    padding: 12px 0; /* 让按钮的高度保持一致,内容居中 */
+    border-radius: 15px; /* 圆角按钮 */
+    font-size: 14px; /* 较小字体以适应60px的宽度 */
+    font-weight: 600;
+    cursor: pointer; /* 鼠标悬停时的手型指针 */
+    transition: background-color 0.3s ease;
+    border: none;
+    width: 60px; /* 限制宽度为60px */
+    text-align: center; /* 内容居中对齐 */
+    overflow: hidden; /* 如果文字超过,隐藏多余部分 */
+    white-space: nowrap; /* 避免换行 */
+    text-overflow: ellipsis; /* 用省略号表示超出的文字 */
+    margin-left: 10px; /* 跟其他 div 保持一致的间距 */
+    flex-shrink: 0; /* 确保按钮不会缩放 */
+}
+
+.capture-license-button:hover {
+    background-color: #005bb5; /* 悬停时的颜色变深 */
+}
+
+
 /* iOS 风格 login-button 按钮 */
 .login-button {
     background-color: #76b2f1; /* iOS 风格蓝色 */

+ 3 - 1
static/license_info/license_info.html

@@ -13,7 +13,9 @@
     <header>
         <h1>XUGU License</h1>
         <div class="right-container">
-            <div>左边的子div</div>
+            <div id="capture-license-btn"  class="capture-license-button" style="display: none;">
+                主动抓取 License 数据
+            </div>
             <div class="login-button">点击显示用户信息</div>
         </div>
     </header>

+ 64 - 0
static/license_info/license_info.js

@@ -97,6 +97,68 @@ function logout() {
     window.location.href = '/';
 }
 
+// 定义检查权限并显示按钮的函数
+function checkPermissionsAndShowButton() {
+    console.log("checkPermissionsAndShowButton ", currentUserPermissions);
+    if (currentUserPermissions.includes('capture_license_once_to_db')) {
+        const captureLicenseBtn = document.getElementById('capture-license-btn');
+        captureLicenseBtn.style.display = 'block';
+
+        // 为按钮添加点击事件监听
+        captureLicenseBtn.addEventListener('click', CaptureLicenseOncefunc);
+    }
+}
+
+// 主动抓取一次License数据函数
+function CaptureLicenseOncefunc() {
+    // 显示加载模态框
+    const loadingModal = document.createElement('div');
+    loadingModal.classList.add('modal-content', 'apple-modal-content');
+    loadingModal.innerHTML = `
+        <h3>正在获取 License 信息...</h3>
+        <div class="progress-bar" style="width: 100%; height: 20px; background-color: #e0e0e0;">
+            <div class="progress" style="width: 50%; height: 100%; background-color: #007aff;"></div>
+        </div>
+    `;
+    document.body.appendChild(loadingModal);
+
+    // 定义超时函数
+    const timeoutPromise = new Promise((_, reject) => {
+        setTimeout(() => {
+            reject(new Error('获取超时'));
+        }, 10000); // 10秒超时
+    });
+
+    // 发起 GET 请求的 Promise
+    const fetchPromise = fetch('http://127.0.0.1:8080/api/admin/GetCaptureLicenseOnce', {
+        method: 'GET',
+        headers: {
+            'Authorization': `Bearer ${authToken}`, // 假设 token 已定义
+            'Content-Type': 'application/json'
+        }
+    }).then(response => response.json());
+
+    // 使用 Promise.race 来竞争两个 Promise,哪个先返回就使用哪个
+    Promise.race([fetchPromise, timeoutPromise])
+    .then(data => {
+        // 先关闭进度条
+        document.body.removeChild(loadingModal);
+
+        // 显示成功或失败提示
+        if (data.success) {
+            alert('License 获取成功!');
+        } else {
+            alert('获取失败:' + data.error);
+        }
+    })
+    .catch(error => {
+        // 先关闭进度条
+        document.body.removeChild(loadingModal);
+        
+        // 显示错误提示
+        alert(error.message); // 如果超时或请求失败
+    });
+}
 
 
 
@@ -130,6 +192,8 @@ function updateMenuVisibility() {
         roleManagementLink.style.display = currentUserPermissions.includes('get_role') ? 'block' : 'none';
         licenseInfoLink.style.display = (currentUserPermissions.includes('read_license') || currentUserPermissions.includes('read_all_license')) ? 'block' : 'none';
     }
+    // 调用函数检查权限并显示按钮
+checkPermissionsAndShowButton();
 }
 
 // 监听用户管理按钮的点击事件

+ 41 - 4
static/role/role.css

@@ -111,7 +111,6 @@
     height: 100%; /* 100% 高 */
     overflow: auto; /* 如果需要滚动条 */
     background-color: rgba(0, 0, 0, 0.4); /* 半透明背景 */
-    backdrop-filter: blur(5px); /* 背景模糊 */
 }
 
 .CreateRoleModal-modal-content {
@@ -181,7 +180,7 @@ form button:hover {
 
 /* 权限复选框容器 */
 #permissionsContainer div {
-    margin-bottom: 12px;
+    margin-bottom: 8px; /* 减少下方间距 */
 }
 
 #permissionsContainer label {
@@ -192,8 +191,32 @@ form button:hover {
 
 /* 子权限复选框容器 */
 .role-sub-permissions {
-    margin-left: 20px;
-    margin-top: 8px;
+    margin-left: 15px; /* 保持左侧缩进 */
+}
+
+.role-sub-permissions input[type="checkbox"] + label {
+    display: block; /* 使标签占据整行,便于添加边框 */
+    padding: 4px 0; /* 增加上下内边距,使边框不贴紧文本 */
+    /* 移除子权限项的上下边框 */
+    border: none;
+    margin: 0; /* 去除默认外边距 */
+}
+
+/* 父权限容器样式 */
+.parent-permission {
+    border-top: 1px solid #ccc;
+    border-bottom: 1px solid #ccc;
+    padding: 12px 0;
+}
+
+/* 移除第一个父权限容器的上边框 */
+.permissionsContainer .parent-permission:first-child {
+    border-top: none;
+}
+
+/* 移除最后一个父权限容器的下边框 */
+.permissionsContainer .parent-permission:last-child {
+    border-bottom: none;
 }
 
 /* 禁用按钮样式 */
@@ -229,3 +252,17 @@ form button:hover {
     }
 }
 
+/* 优化模态框内权限部分的布局 */
+.CreateRoleModal-modal-content form {
+    display: flex;
+    flex-direction: column;
+}
+
+.CreateRoleModal-modal-content form label {
+    margin-bottom: 4px; /* 减少标签下方间距 */
+}
+
+.CreateRoleModal-modal-content form input[type="text"] {
+    margin-bottom: 12px; /* 调整输入框下方间距 */
+}
+

+ 20 - 2
static/role/role.html

@@ -28,8 +28,8 @@
             <span class="CreateRoleModal-close">&times;</span>
             <h2>创建角色</h2>
             <form>
-                <label for="characterName">角色名称:</label>
-                <input type="text" id="characterName" name="characterName" required>
+                <label for="roleName">角色名称:</label>
+                <input type="text" id="roleName" name="roleName" required>
                 <br>
                 <h3>选择权限:</h3>
                 <div id="permissionsContainer"></div>
@@ -40,6 +40,24 @@
     </div>
     
     
+<!-- 修改角色模态框 -->
+<div id="ModifyRoleModal" class="CreateRoleModal-modal">
+    <div class="CreateRoleModal-modal-content">
+        <span class="CreateRoleModal-close">&times;</span>
+        <h2>修改角色</h2>
+        <form id="ModifyRoleForm">
+            <label for="modifyRoleName">角色名称:</label>
+            <input type="text" id="modifyRoleName" name="modifyRoleName" required>
+            <br>
+            <h3>选择权限:</h3>
+            <div id="modifyPermissionsContainer"></div>
+            <br>
+            <input type="submit" value="保存修改">
+        </form>
+    </div>
+</div>
+
+
     <script src="role.js"></script>
 
 </body>

+ 279 - 123
static/role/role.js

@@ -2,14 +2,20 @@
 
 fetchRoles()
 
-  // 处理修改用户按钮点击
-  document.getElementById("createRoleButton").onclick = () => {
-      
+//   // 处理修改用户按钮点击
+document.getElementById("createRoleButton").onclick = () => {
     // 调用函数以设置模态框
-ShowCreateRoleModal();
-
+    ShowCreateRoleModal();
 };
 
+// 绑定表单提交事件 创建角色
+document.getElementById('CreateRoleModa').addEventListener('submit', function(event) {
+    event.preventDefault(); // 阻止表单默认提交行为
+    createRole(); // 调用创建角色的函数
+});
+
+
+
 function fetchRoles() {
     
     fetch('http://127.0.0.1:8080/api/admin/GetRoles', {
@@ -94,16 +100,16 @@ function renderRole(container, roleInfo, permissionMap, isTopRole) {
     roleDiv.addEventListener('click', function(event) {
         event.stopPropagation();  // 阻止事件冒泡
         event.preventDefault();   // 阻止默认行为
-        showRoleActionMenu(event, roleInfo.Name);
+        showRoleActionMenu(event, roleInfo.Name,roleInfo);
     });
 
     roleDiv.addEventListener('contextmenu', function(event) {
         event.preventDefault();
-        showRoleActionMenu(event, roleInfo.Name);
+        showRoleActionMenu(event, roleInfo.Name,roleInfo);
     });
 }
 
-function showRoleActionMenu(event, roleName) {
+function showRoleActionMenu(event, roleName,roleInfo) {
     // 移除已有的菜单
     const existingMenu = document.getElementById('role-action-menu');
     if (existingMenu) {
@@ -135,7 +141,7 @@ function showRoleActionMenu(event, roleName) {
             modifyButton.textContent = '修改角色';
             modifyButton.className = 'role-info-button';
             modifyButton.addEventListener('click', function () {
-                modifyRole(roleName);
+                ShowModifyRoleModal(roleInfo);
                 menu.remove(); // 点击按钮后,关闭菜单栏
             });
             menu.appendChild(modifyButton);
@@ -174,101 +180,196 @@ function showRoleActionMenu(event, roleName) {
     });
 }
 
-//修改角色信息
-function modifyRole(roleName) {
-    console.log(`modifyRole called with roleName: ${roleName}`);
-    
-    fetchRoleInfo(roleName, function(roleInfo) {
-        console.log(`fetchRoleInfo returned:`, roleInfo);
+// 父选项框和子选项框的联动逻辑
+function toggleModifyChildCheckboxes(key, isChecked) {
+    const subContainer = document.getElementById("modify_" + key + "SubPermissions");
+    if (subContainer) {
+        const childCheckboxes = subContainer.querySelectorAll('input[type="checkbox"]');
+        childCheckboxes.forEach(checkbox => {
+            checkbox.checked = isChecked;
+        });
+    }
+}
 
-        if (!roleInfo) {
-            console.error('Role info is undefined or null');
-            return;
-        }
+// 打开修改角色模态框
+function ShowModifyRoleModal(roleInfo) {
+    console.log("打开修改角色模态框", roleInfo);
+
+    // 获取模态框
+    var modal = document.getElementById("ModifyRoleModal");
+
+    // 填充角色名称
+    var roleNameInput = document.getElementById("modifyRoleName");
+    roleNameInput.value = roleInfo.Name;
+
+    // 填充权限复选框
+    var container = document.getElementById("modifyPermissionsContainer");
+    container.innerHTML = ''; // 清空之前的内容
+
+    const permissionMap = {
+        'license': '许可证',
+        'user': '用户',
+        'role': '角色'
+    };
+
+    const subPermissions = {
+        'license': [
+            { id: 'generate_license', label: '生成许可证' },
+            { id: 'upload_license', label: '上传许可证(废弃)' },
+            { id: 'read_license', label: '读取许可证' },
+            { id: 'read_license_record', label: '读取许可证分发记录' },
+            { id: 'update_license', label: '修改许可证(废弃)' },
+            { id: 'delete_license', label: '删除许可证(废弃)' },
+            { id: 'dispat_license', label: '分发许可证' }
+        ],
+        'user': [
+            { id: 'create_user', label: '创建用户' },
+            { id: 'read_user', label: '读取用户' },
+            { id: 'update_user', label: '更新用户' },
+            { id: 'delete_user', label: '删除用户' }
+        ],
+        'role': [
+            { id: 'create_role', label: '创建角色' },
+            { id: 'delete_role', label: '删除角色' },
+            { id: 'update_role', label: '更新角色' },
+            { id: 'get_role', label: '获取角色' }
+        ]
+    };
 
-        const extraInfoContent = document.getElementById('extraInfoContent');
-        if (!extraInfoContent) {
-            console.error('Element with id "extraInfoContent" not found');
-            return;
+    // 生成复选框
+    for (const [key, value] of Object.entries(permissionMap)) {
+        var parentDiv = document.createElement("div");
+        parentDiv.classList.add('parent-permission');
+
+        var mainCheckbox = document.createElement("input");
+        mainCheckbox.type = "checkbox";
+        mainCheckbox.id = "modify_" + key;
+        mainCheckbox.value = key;
+        mainCheckbox.name = "permissions";
+
+        // 当角色拥有该权限时勾选
+        if (roleInfo.Permissions.includes(key)) {
+            mainCheckbox.checked = true;
         }
 
-        extraInfoContent.innerHTML = `
-            <h3>修改角色: ${roleInfo.Name}</h3>
-            <label for="roleName">角色名称:</label>
-            <input type="text" id="roleName" value="${roleInfo.Name}" required><br><br>
-            <label for="permissions">权限:</label><br>
-            <div id="permissions">
-                  <div>
-            <input type="checkbox" id="license" name="permissions" value="license" onchange="toggleSubPermissions('license', this)">
-            <label for="license">许可证</label>
-            <div id="licenseSubPermissions" style="margin-left: 20px;">
-                <input type="checkbox" id="generate_license" name="permissions" value="generate_license">
-                <label for="generate_license">生成许可证</label><br>
-                <input type="checkbox" id="upload_license" name="permissions" value="upload_license">
-                <label for="upload_license">上传许可证</label><br>
-                <input type="checkbox" id="read_license" name="permissions" value="read_license">
-                <label for="read_license">读取许可证</label><br>
-                <input type="checkbox" id="update_license" name="permissions" value="update_license">
-                <label for="update_license">更新许可证</label><br>
-                <input type="checkbox" id="delete_license" name="permissions" value="delete_license">
-                <label for="delete_license">删除许可证</label><br>
-            </div>
-        </div>
-        <div>
-            <input type="checkbox" id="user" name="permissions" value="user" onchange="toggleSubPermissions('user', this)">
-            <label for="user">用户</label>
-            <div id="userSubPermissions" style="margin-left: 20px;">
-                <input type="checkbox" id="create_user" name="permissions" value="create_user">
-                <label for="create_user">创建用户</label><br>
-                <input type="checkbox" id="read_user" name="permissions" value="read_user">
-                <label for="read_user">读取用户</label><br>
-                <input type="checkbox" id="update_user" name="permissions" value="update_user">
-                <label for="update_user">更新用户</label><br>
-                <input type="checkbox" id="delete_user" name="permissions" value="delete_user">
-                <label for="delete_user">删除用户</label><br>
-            </div>
-        </div>
-        <div>
-            <input type="checkbox" id="role" name="permissions" value="role" onchange="toggleSubPermissions('role', this)">
-            <label for="role">角色</label>
-            <div id="roleSubPermissions" style="margin-left: 20px;">
-                <input type="checkbox" id="create_role" name="permissions" value="create_role">
-                <label for="create_role">创建角色</label><br>
-                <input type="checkbox" id="delete_role" name="permissions" value="delete_role">
-                <label for="delete_role">删除角色</label><br>
-                <input type="checkbox" id="update_role" name="permissions" value="update_role">
-                <label for="update_role">更新角色</label><br>
-                <input type="checkbox" id="get_role" name="permissions" value="get_role">
-                <label for="get_role">获取角色</label><br>
-            </div>
-        </div>
-            </div><br><br>
-            <button onclick="saveRoleChanges('${roleInfo.Id}')">保存</button>
-        `;
-
-        console.log('Form content added to extraInfoContent');
-
-        const checkboxes = document.querySelectorAll('#permissions input[type="checkbox"]');
-
-// 遍历所有复选框
-checkboxes.forEach(checkbox => {
-    if (roleInfo.Permissions.includes(checkbox.value)) {
-        checkbox.checked = true; // 如果当前权限在roleInfo.Permissions中,则勾选
+        // 当父选项框改变时,联动子选项框
+        mainCheckbox.addEventListener('change', function() {
+            toggleModifyChildCheckboxes(key, this.checked);
+        });
+
+        var mainLabel = document.createElement("label");
+        mainLabel.htmlFor = "modify_" + key;
+        mainLabel.textContent = value;
+
+        parentDiv.appendChild(mainCheckbox);
+        parentDiv.appendChild(mainLabel);
+        parentDiv.appendChild(document.createElement("br"));
+
+        var subContainer = document.createElement("div");
+        subContainer.id = "modify_" + key + "SubPermissions";
+        subContainer.classList.add('role-sub-permissions');
+        subContainer.style.display = "block";
+
+        subPermissions[key].forEach(sub => {
+            var subCheckbox = document.createElement("input");
+            subCheckbox.type = "checkbox";
+            subCheckbox.id = "modify_" + sub.id;
+            subCheckbox.value = sub.id;
+            subCheckbox.name = "permissions";
+
+            if (roleInfo.Permissions.includes(sub.id)) {
+                subCheckbox.checked = true;
+            }
+
+            var subLabel = document.createElement("label");
+            subLabel.htmlFor = "modify_" + sub.id;
+            subLabel.textContent = sub.label;
+
+            subContainer.appendChild(subCheckbox);
+            subContainer.appendChild(subLabel);
+            subContainer.appendChild(document.createElement("br"));
+        });
+
+        parentDiv.appendChild(subContainer);
+        container.appendChild(parentDiv);
     }
-});
 
-        const extraInfoModal = document.getElementById('extraInfoModal');
-        if (!extraInfoModal) {
-            console.error('Element with id "extraInfoModal" not found');
-            return;
+    // 显示模态框
+    modal.style.display = "block";
+
+    // 绑定表单提交事件
+    document.getElementById('ModifyRoleForm').addEventListener('submit', function(event) {
+        event.preventDefault(); // 阻止默认提交行为
+
+        const roleId = roleInfo.Id; // 获取当前角色ID
+        modifyRole(roleId);  // 调用修改角色的函数
+    });
+
+    // 关闭按钮的事件处理
+    var closeModalButton = modal.querySelector(".CreateRoleModal-close");
+    closeModalButton.onclick = function() {
+        modal.style.display = "none";
+    };
+
+    // 当用户点击模态框外时关闭模态框
+    window.onclick = function(event) {
+        if (event.target == modal) {
+            modal.style.display = "none";
         }
+    };
+}
+
+// 修改角色信息
+function modifyRole(roleId) {
+    const roleNameInput = document.getElementById('modifyRoleName');
+    const roleName = roleNameInput.value.trim();
 
-        extraInfoModal.style.display = 'block';  // 强制显示模态框
-        console.log('Modal should be visible now');
+    if (!roleName) {
+        alert('请输入角色名称。');
+        return;
+    }
+
+    // 获取所有被选中的子权限复选框
+    const permissionCheckboxes = document.querySelectorAll('#modifyPermissionsContainer .role-sub-permissions input[type="checkbox"]:checked');
+    const permissions = Array.from(permissionCheckboxes).map(checkbox => checkbox.value);
+
+    // 构造请求体
+    const requestBody = {
+        id: roleId,  // 使用角色ID来修改角色信息
+        name: roleName,
+        permissions: permissions // 仅添加子权限的值
+    };
+
+    // 发送修改请求
+    fetch('http://127.0.0.1:8080/api/admin/UpdateRole', {
+        method: 'POST',
+        headers: {
+            'Authorization': `Bearer ${authToken}`,
+            'Content-Type': 'application/json'
+        },
+        body: JSON.stringify(requestBody)
+    })
+    .then(response => {
+        if (!response.ok) {
+            return response.json().then(errorData => {
+                throw new Error(errorData.message || '修改角色失败');
+            });
+        }
+        return response.json();
+    })
+    .then(data => {
+        alert('角色修改成功!');
+        document.getElementById('ModifyRoleModal').style.display = 'none';
+        fetchRoles(); // 刷新角色列表
+    })
+    .catch(error => {
+        console.error('修改角色失败:', error);
+        alert(`修改角色失败: ${error.message}`);
     });
 }
 
 
+
 // 示例的删除角色函数
 function deleteRole(roleName) {
     if (confirm(`确定要删除角色:${roleName} 吗?`)) {
@@ -282,7 +383,7 @@ function deleteRole(roleName) {
         })
         .then(response => response.json())
         .then(data => {
-            if (data.code === 200) {
+            if (data.success === true) {
                 alert('角色删除成功');
                 fetchRoles(); // 重新获取角色列表
             } else {
@@ -296,16 +397,22 @@ function deleteRole(roleName) {
 }
 
 
-// 修改后的 ShowCreateRoleModal 方法
+
+
+
+
+
+
+/**
+ * 显示创建角色模态框并初始化内容
+ */
 function ShowCreateRoleModal() {
+    console.log("模态框调用");
     // 获取模态框
     var modal = document.getElementById("CreateRoleModa");
 
-    // 获取按钮
-    var btn = document.getElementById("createRoleButton");
-
     // 获取关闭按钮
-    var span = document.getElementsByClassName("CreateRoleModal-close")[0];
+    var span = modal.querySelector(".CreateRoleModal-close");
 
     // 权限数据
     const permissionMap = {
@@ -343,29 +450,35 @@ function ShowCreateRoleModal() {
     container.innerHTML = ''; // 清空之前的内容
 
     for (const [key, value] of Object.entries(permissionMap)) {
+        // 创建父权限容器
+        var parentDiv = document.createElement("div");
+        parentDiv.classList.add('parent-permission');
+
         // 创建主权限复选框
         var mainCheckbox = document.createElement("input");
         mainCheckbox.type = "checkbox";
         mainCheckbox.id = key;
         mainCheckbox.value = key;
         mainCheckbox.name = "permissions";
-        mainCheckbox.onchange = function() {
-            toggleSubPermissions(key, this);
-        };
+
+        // 添加 change 事件监听器,当父复选框状态变化时,自动勾选或取消所有子复选框
+        mainCheckbox.addEventListener('change', function() {
+            toggleChildCheckboxes(key, this.checked);
+        });
 
         var mainLabel = document.createElement("label");
         mainLabel.htmlFor = key;
         mainLabel.textContent = value;
 
-        container.appendChild(mainCheckbox);
-        container.appendChild(mainLabel);
-        container.appendChild(document.createElement("br")); // 换行
+        parentDiv.appendChild(mainCheckbox);
+        parentDiv.appendChild(mainLabel);
+        parentDiv.appendChild(document.createElement("br"));
 
         // 创建子权限容器
         var subContainer = document.createElement("div");
         subContainer.id = `${key}SubPermissions`;
-        subContainer.style.marginLeft = "20px";
-        subContainer.style.display = "none"; // 默认隐藏
+        subContainer.classList.add('role-sub-permissions');
+        subContainer.style.display = "block"; // 始终显示
 
         // 创建子权限复选框
         subPermissions[key].forEach(sub => {
@@ -381,16 +494,15 @@ function ShowCreateRoleModal() {
 
             subContainer.appendChild(subCheckbox);
             subContainer.appendChild(subLabel);
-            subContainer.appendChild(document.createElement("br")); // 换行
+            subContainer.appendChild(document.createElement("br"));
         });
 
-        container.appendChild(subContainer);
+        parentDiv.appendChild(subContainer);
+        container.appendChild(parentDiv);
     }
 
-    // 当用户点击按钮时,打开模态框
-    btn.onclick = function() {
-        modal.style.display = "block";
-    }
+    // 显示模态框
+    modal.style.display = "block";
 
     // 当用户点击关闭按钮时,关闭模态框
     span.onclick = function() {
@@ -406,21 +518,65 @@ function ShowCreateRoleModal() {
 }
 
 /**
- * 切换子权限的显示与隐藏
+ * 切换所有子复选框的选中状态
  * @param {string} key 主权限的键
- * @param {HTMLElement} checkbox 主权限的复选框
+ * @param {boolean} isChecked 主权限复选框是否选中
  */
-function toggleSubPermissions(key, checkbox) {
+function toggleChildCheckboxes(key, isChecked) {
     var subContainer = document.getElementById(`${key}SubPermissions`);
-    if (checkbox.checked) {
-        subContainer.style.display = "block";
-    } else {
-        subContainer.style.display = "none";
-        // 取消所有子权限的选中状态
-        var subCheckboxes = subContainer.querySelectorAll('input[type="checkbox"]');
-        subCheckboxes.forEach(sub => {
-            sub.checked = false;
+    if (subContainer) {
+        var childCheckboxes = subContainer.querySelectorAll('input[type="checkbox"]');
+        childCheckboxes.forEach(checkbox => {
+            checkbox.checked = isChecked;
         });
     }
 }
 
+// 添加创建角色的函数
+function createRole() {
+    console.log("创建角色");
+    const roleNameInput = document.getElementById('roleName');
+    const roleName = roleNameInput.value.trim();
+
+    if (!roleName) {
+        alert('请输入角色名称。');
+        return;
+    }
+
+    // 仅选择 role-sub-permissions 类中的复选框
+    const permissionCheckboxes = document.querySelectorAll('#permissionsContainer .role-sub-permissions input[type="checkbox"]:checked');
+    const permissions = Array.from(permissionCheckboxes).map(checkbox => checkbox.value);
+
+    const requestBody = {
+        name: roleName,
+        permissions: permissions
+    };
+    console.log("requestBody", requestBody);
+
+    fetch('http://127.0.0.1:8080/api/admin/CreateRole', {
+        method: 'POST',
+        headers: {
+            'Authorization': `Bearer ${authToken}`,
+            'Content-Type': 'application/json'
+        },
+        body: JSON.stringify(requestBody)
+    })
+    .then(response => {
+        console.log("创建角色响应", response);
+        if (!response.ok) {
+            return response.json().then(errorData => {
+                throw new Error(errorData.message || '创建角色失败');
+            });
+        }
+        return response.json();
+    })
+    .then(data => {
+        alert('角色创建成功!');
+        document.getElementById('CreateRoleModa').style.display = 'none';
+        fetchRoles();
+    })
+    .catch(error => {
+        console.error('创建角色失败:', error);
+        alert(`创建角色失败: ${error.message}`);
+    });
+}