<template>
  <div class="role-form-container">
    <!-- 头部：返回按钮和标题 -->
    <div class="header-section">
      <el-button :icon="ArrowLeft" text @click="handleBack"> 返回 </el-button>
      <h2 class="page-title">
        {{ isEdit ? "编辑角色" : "创建角色" }}
      </h2>
    </div>

    <!-- 表单内容 -->
    <div class="form-content">
      <el-form ref="roleFormRef" :model="roleForm" :rules="roleFormRules" label-width="120px">
        <!-- 角色类型 -->
        <el-form-item label="角色类型" prop="roleName">
          <template #label>
            <span>角色类型</span>
            <el-tooltip content="请输入角色类型名称" placement="top">
              <el-icon class="question-icon">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="roleForm.roleName" placeholder="请输入" maxlength="50" clearable @blur="checkRoleNameDuplicate" />
        </el-form-item>

        <!-- 子账号权限 -->
        <el-form-item label="子账号权限" prop="permissions" required>
          <template #label>
            <span>子账号权限</span>
            <span class="required-star">*</span>
          </template>
          <div class="permission-tree-container">
            <el-tree
              ref="permissionTreeRef"
              :data="permissionTreeData"
              :props="treeProps"
              show-checkbox
              node-key="id"
              :default-expand-all="false"
              :check-strictly="checkStrictly"
              :default-checked-keys="defaultCheckedKeys"
              :expand-on-click-node="false"
              @check="handlePermissionCheck"
            >
              <template #default="{ node, data }">
                <span class="tree-node-label">
                  <span>{{ data.label }}</span>
                </span>
              </template>
            </el-tree>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <div class="form-footer">
      <el-button @click="handleCancel"> 取消 </el-button>
      <el-button type="primary" @click="handleSave" :loading="saveLoading"> 保存 </el-button>
    </div>
  </div>
</template>

<script setup lang="ts" name="roleCreate">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { ArrowLeft, QuestionFilled } from "@element-plus/icons-vue";
import {
  getMenuTree,
  createRole,
  updateRole,
  getRolePermissionTable,
  type MenuItem,
  type RolePermissionItem
} from "@/api/modules/accountRoleManagement";
import { localGet } from "@/utils";

// 路由
const router = useRouter();
const route = useRoute();

// 判断是编辑还是创建
const roleId = computed(() => route.query.roleId as string | undefined);
const isEdit = computed(() => route.query.type === "edit");

// 表单引用
const roleFormRef = ref<FormInstance>();
const permissionTreeRef = ref<any>();

// 表单数据
const roleForm = reactive({
  roleName: "",
  description: "",
  permissions: [] as number[]
});

// 表单验证规则
const roleFormRules: FormRules = {
  roleName: [{ required: true, message: "请输入角色类型", trigger: "blur" }],
  permissions: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error("请至少选择一个权限"));
        } else {
          callback();
        }
      },
      trigger: "change"
    }
  ]
};

// 树形组件配置
const treeProps = {
  children: "children",
  label: "label",
  disabled: "disabled"
};

// 权限树数据
const permissionTreeData = ref<any[]>([]);

// 递归设置节点及其子级的 disabled，并打标供 updateNodeDisabledState 保留
const setStoreDecorateDisabledRecursive = (nodes: any[]) => {
  nodes.forEach((n: any) => {
    n.disabled = true;
    n.disableByStoreDecorate = true;
    if (n.children?.length) setStoreDecorateDisabledRecursive(n.children);
  });
};

// 转换菜单数据为树形组件需要的格式；一级为「门店装修」时禁用该节点及所有子级
const transformMenuData = (menuList: MenuItem[]): any[] => {
  return menuList.map(menu => {
    const node: any = {
      id: menu.menuId,
      label: menu.menuName,
      menuId: menu.menuId,
      menuName: menu.menuName
    };
    if (menu.children && menu.children.length > 0) {
      node.children = transformMenuData(menu.children);
    }
    // 判断是否是门店装修
    // if (localGet("storeTickets") == 0) {
    //   if (menu.menuName === "门店装修") {
    //     node.disabled = true;
    //     node.disableByStoreDecorate = true;
    //     if (node.children?.length) setStoreDecorateDisabledRecursive(node.children);
    //   }
    // }

    return node;
  });
};

// 默认选中的权限（编辑时使用）
const defaultCheckedKeys = ref<number[]>([]);

// 保存加载状态
const saveLoading = ref(false);

// 标志位：防止自动勾选"查看"权限时触发递归
const isAutoCheckingView = ref(false);
const isAutoUncheckingParent = ref(false);

// 控制父子节点是否严格独立（false表示父子关联，true表示严格独立）
// 设置为true，使父子节点独立，选择某一级时不会自动勾选下级
const checkStrictly = ref(true);

// 加载菜单树数据
const loadMenuTree = async () => {
  try {
    const res = await getMenuTree();
    // res.code 可能是 string 或 number，需要转换比较
    const code = typeof res.code === "string" ? parseInt(res.code) : res.code;
    if (code === 200 && res.data) {
      // 转换数据格式，res.data 是 MenuItem[]
      permissionTreeData.value = transformMenuData(res.data);
    } else {
      ElMessage.error(res.msg || "获取菜单列表失败");
    }
  } catch (error) {
    console.error("获取菜单列表失败:", error);
  }
};

// 初始化数据
onMounted(async () => {
  // 先加载菜单树数据
  await loadMenuTree();

  if (isEdit.value) {
    // 编辑模式：加载角色数据
    await loadRoleData();
  } else {
    // 创建模式：初始化空数据
    roleForm.roleName = "";
    roleForm.permissions = [];
  }
});

// 通过权限名称匹配菜单ID（递归查找，支持转换后的树形数据）
const findMenuIdByName = (menuList: any[], permissionName: string): number | null => {
  for (const menu of menuList) {
    if (menu.menuName === permissionName || menu.label === permissionName) {
      return menu.menuId || menu.id;
    }
    if (menu.children && menu.children.length > 0) {
      const found = findMenuIdByName(menu.children, permissionName);
      if (found !== null) {
        return found;
      }
    }
  }
  return null;
};

// 在指定的父节点下查找子节点ID（用于查找三级权限）
const findChildMenuIdByName = (parentMenuList: any[], parentName: string, childName: string): number | null => {
  // 先找到父节点
  const parentMenu = findMenuNodeByName(parentMenuList, parentName);
  if (!parentMenu) {
    return null;
  }

  // 在父节点的子节点中查找
  if (parentMenu.children && parentMenu.children.length > 0) {
    for (const child of parentMenu.children) {
      if (child.menuName === childName || child.label === childName) {
        return child.menuId || child.id;
      }
    }
  }

  return null;
};

// 通过权限名称匹配菜单节点（返回节点对象，用于查找子节点）
const findMenuNodeByName = (menuList: any[], permissionName: string): any | null => {
  for (const menu of menuList) {
    if (menu.menuName === permissionName || menu.label === permissionName) {
      return menu;
    }
    if (menu.children && menu.children.length > 0) {
      const found = findMenuNodeByName(menu.children, permissionName);
      if (found !== null) {
        return found;
      }
    }
  }
  return null;
};

// 从权限详情数据中提取所有菜单ID
// 规则：一级权限只要有数据就勾选，二级和三级权限按需添加
const extractMenuIdsFromPermissions = (permissionList: RolePermissionItem[], menuTree: MenuItem[]): number[] => {
  const menuIds: number[] = [];
  const addedIds = new Set<number>();

  permissionList.forEach(permission => {
    // 处理一级权限：只要有数据就添加
    if (permission.level1Permission) {
      const menuId = findMenuIdByName(menuTree, permission.level1Permission);
      if (menuId !== null && !addedIds.has(menuId)) {
        menuIds.push(menuId);
        addedIds.add(menuId);
      }
    }

    // 处理二级权限：必须在对应的一级权限下查找，避免「编辑」「查看」等多处重名时取错节点
    if (permission.level2Permission && permission.level1Permission) {
      const menuId = findChildMenuIdByName(menuTree, permission.level1Permission, permission.level2Permission);
      if (menuId !== null && !addedIds.has(menuId)) {
        menuIds.push(menuId);
        addedIds.add(menuId);
      }
    }

    // 处理三级权限
    // 注意：level3Permission 可能包含多个权限名称（用空格分隔），需要拆分处理
    // 只有当 level3Permission 不为 null 且不为空字符串时才处理
    // 重要：必须在对应的二级权限下查找三级权限，避免跨范围匹配
    if (permission.level3Permission && permission.level3Permission.trim() && permission.level2Permission) {
      // 保存 level2Permission 到局部变量，确保类型安全
      const level2Permission = permission.level2Permission;
      // 将 level3Permission 按空格拆分为多个权限名称
      const level3PermissionNames = permission.level3Permission
        .split(/\s+/) // 按一个或多个空白字符拆分
        .map(name => name.trim()) // 去除首尾空格
        .filter(name => name.length > 0); // 过滤空字符串

      // 对每个权限名称分别在对应的二级权限下进行精确匹配
      level3PermissionNames.forEach(permissionName => {
        // 在对应的二级权限下查找三级权限，避免在其他二级权限下误匹配
        const menuId = findChildMenuIdByName(menuTree, level2Permission, permissionName);
        // 只有精确匹配到菜单项时才添加，避免误匹配
        if (menuId !== null && !addedIds.has(menuId)) {
          menuIds.push(menuId);
          addedIds.add(menuId);
        }
      });
    }
  });

  return menuIds;
};

// 加载角色数据（编辑时）
const loadRoleData = async () => {
  if (!roleId.value) {
    ElMessage.error("缺少角色ID参数");
    router.back();
    return;
  }

  try {
    // 从query中获取角色名称
    const queryRoleName = route.query.roleName as string;
    if (queryRoleName) {
      roleForm.roleName = queryRoleName;
    }

    // 调用接口获取权限详情
    const res = await getRolePermissionTable({ roleId: Number(roleId.value) });
    const code = typeof res.code === "string" ? parseInt(res.code) : res.code;

    if (code === 200 && res.data) {
      // 从权限详情中提取菜单ID
      const menuIds = extractMenuIdsFromPermissions(res.data, permissionTreeData.value as any);
      roleForm.permissions = menuIds;
      defaultCheckedKeys.value = menuIds;

      // 设置树形组件的选中状态
      // 由于 checkStrictly 为 true，父子节点独立，直接设置选中状态即可
      nextTick(() => {
        if (permissionTreeRef.value) {
          permissionTreeRef.value.setCheckedKeys(menuIds);
          // 更新权限列表
          const finalCheckedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
          roleForm.permissions = finalCheckedKeys;
          // 更新节点的禁用状态
          updateNodeDisabledState(permissionTreeData.value, finalCheckedKeys);
        }
      });
    } else {
      ElMessage.error(res.msg || "获取角色权限详情失败");
    }
  } catch (error) {
    console.error("加载角色数据失败:", error);
  }
};

// 检查角色名称是否重复
const checkRoleNameDuplicate = async () => {
  if (!roleForm.roleName) return;

  // TODO: 调用接口检查名称是否重复
  // 模拟检查
  const existingNames = ["管理员", "运营人员", "财务人员", "客服人员"];
  if (existingNames.includes(roleForm.roleName)) {
    ElMessage.warning("该角色名称已存在，请使用其他名称");
  }
};

// 检查同级是否有其他非"查看"权限被勾选
const hasOtherCheckedSiblings = (currentNode: any, checkedKeys: number[]): boolean => {
  if (!currentNode || !currentNode.parent) {
    return false;
  }

  const parentData = currentNode.parent.data;
  if (!parentData.children || parentData.children.length === 0) {
    return false;
  }

  // 检查同级中是否有非"查看"权限被勾选
  return parentData.children.some((child: any) => {
    // 排除当前节点和"查看"权限
    return child.id !== currentNode.data.id && child.label !== "查看" && checkedKeys.includes(child.id);
  });
};

// 检查节点是否有子节点被选中（通过数据源检查）
const hasCheckedChildrenInData = (nodeData: any, checkedKeys: number[]): boolean => {
  // 如果是叶子节点，返回 false
  if (!nodeData.children || nodeData.children.length === 0) {
    return false;
  }

  // 递归检查所有子节点是否有被选中的
  const checkChildren = (children: any[]): boolean => {
    return children.some((child: any) => {
      // 如果子节点本身被选中，返回 true
      if (checkedKeys.includes(child.id)) {
        return true;
      }
      // 如果子节点还有子节点，递归检查
      if (child.children && child.children.length > 0) {
        return checkChildren(child.children);
      }
      return false;
    });
  };

  return checkChildren(nodeData.children);
};

// 更新树节点数据中的 disabled 状态
const updateNodeDisabledState = (treeData: any[], checkedKeys: number[]) => {
  const updateNode = (nodes: any[]): void => {
    nodes.forEach((node: any) => {
      // 一级为「门店装修」及其子级：始终保持禁用，不参与后续逻辑
      if (node.disableByStoreDecorate) {
        node.disabled = true;
        if (node.children?.length) updateNode(node.children);
        return;
      }
      // 如果是叶子节点，不禁用
      if (!node.children || node.children.length === 0) {
        node.disabled = false;
      } else {
        // 如果节点有子节点被选中，则禁用该节点
        node.disabled = hasCheckedChildrenInData(node, checkedKeys);
        if (node.children && node.children.length > 0) {
          updateNode(node.children);
        }
      }
    });
  };

  updateNode(treeData);
};

// 权限选择变化
const handlePermissionCheck = (data: any, checked: any) => {
  // 如果正在自动勾选"查看"权限，直接返回，避免递归
  if (isAutoCheckingView.value) {
    const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
    roleForm.permissions = checkedKeys;
    roleFormRef.value?.validateField("permissions");
    return;
  }
  // 如果正在自动取消勾选父级，仅同步状态后返回
  if (isAutoUncheckingParent.value) {
    const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
    roleForm.permissions = checkedKeys;
    updateNodeDisabledState(permissionTreeData.value, checkedKeys);
    roleFormRef.value?.validateField("permissions");
    return;
  }

  // 获取当前选中的 keys
  const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || [];

  // 判断是否是三级节点（叶子节点，没有子节点）
  const isLeafNode = !data.children || data.children.length === 0;

  // 判断当前节点是否被勾选
  const isChecked = checkedKeys.includes(data.id);

  // 通过 el-tree 的 getNode 方法获取节点对象
  const currentNode = permissionTreeRef.value?.getNode(data.id);

  // 有子级的父节点：若子级均未选中，则不允许单独勾选父级；仅一级无子级可自由勾选
  if (isChecked && !isLeafNode && currentNode) {
    const hasChildChecked = hasCheckedChildrenInData(data, checkedKeys);
    if (!hasChildChecked) {
      nextTick(() => {
        permissionTreeRef.value?.setChecked(data.id, false, false);
        const updatedCheckedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
        roleForm.permissions = updatedCheckedKeys;
        updateNodeDisabledState(permissionTreeData.value, updatedCheckedKeys);
        ElMessage.warning("子级均未选中时，父级不能单独勾选，请先勾选至少一个子级权限");
      });
      return;
    }
  }

  // 如果尝试取消勾选"查看"权限
  if (isLeafNode && data.label === "查看" && !isChecked && currentNode) {
    // 检查同级是否有其他非"查看"权限被勾选
    if (hasOtherCheckedSiblings(currentNode, checkedKeys)) {
      // 如果有其他权限被勾选，阻止取消"查看"权限，重新勾选
      isAutoCheckingView.value = true;
      nextTick(() => {
        permissionTreeRef.value?.setChecked(data.id, true, false);
        const updatedCheckedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
        roleForm.permissions = updatedCheckedKeys;
        ElMessage.warning("当同级有其他权限被勾选时，查看权限不能取消");
        nextTick(() => {
          isAutoCheckingView.value = false;
        });
      });
      return;
    }
  }

  // 更新权限列表
  roleForm.permissions = checkedKeys;

  // 如果勾选了子节点，自动勾选所有父节点
  if (isChecked && currentNode && currentNode.parent) {
    // 递归向上查找并勾选所有父节点
    let parent = currentNode.parent;
    while (parent && parent.data) {
      const parentId = parent.data.id;
      const parentNode = permissionTreeRef.value?.getNode(parentId);

      // 如果父节点存在且未被勾选，则勾选它
      if (parentNode && !parentNode.checked) {
        permissionTreeRef.value?.setChecked(parentId, true, false);
      }

      // 继续向上查找
      parent = parent.parent;
    }

    // 更新权限列表（包含新勾选的父节点）
    nextTick(() => {
      const updatedCheckedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
      roleForm.permissions = updatedCheckedKeys;
      // 更新节点的禁用状态
      updateNodeDisabledState(permissionTreeData.value, updatedCheckedKeys);
    });
  }

  // 如果尝试取消勾选父节点，但该父节点有子节点被选中，则阻止取消
  if (!isChecked && currentNode && currentNode.data.children && currentNode.data.children.length > 0) {
    // 使用最新的选中状态检查
    const latestCheckedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
    const hasChecked = hasCheckedChildrenInData(currentNode.data, latestCheckedKeys);
    if (hasChecked) {
      // 如果有子节点被选中，阻止取消勾选父节点，重新勾选
      nextTick(() => {
        permissionTreeRef.value?.setChecked(currentNode.data.id, true, false);
        const updatedCheckedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
        roleForm.permissions = updatedCheckedKeys;
        // 更新节点的禁用状态
        updateNodeDisabledState(permissionTreeData.value, updatedCheckedKeys);
        ElMessage.warning("当子级权限被选中时，父级权限不能取消");
      });
      return;
    }
  }

  // 取消勾选子级时：若某层父级已无任一子级被勾选，则自动取消该父级勾选
  if (!isChecked && isLeafNode && currentNode?.parent) {
    const keys = new Set<number>(permissionTreeRef.value?.getCheckedKeys() || []);
    const toUncheck: number[] = [];
    let p: any = currentNode.parent;
    while (p?.data) {
      const pid = p.data.id;
      if (!keys.has(pid)) {
        p = p.parent;
        continue;
      }
      if (!p.data.children?.length) {
        p = p.parent;
        continue;
      }
      if (hasCheckedChildrenInData(p.data, [...keys])) {
        p = p.parent;
        continue;
      }
      toUncheck.push(pid);
      keys.delete(pid);
      p = p.parent;
    }
    if (toUncheck.length) {
      isAutoUncheckingParent.value = true;
      nextTick(() => {
        toUncheck.forEach(id => permissionTreeRef.value?.setChecked(id, false, false));
        const updated = permissionTreeRef.value?.getCheckedKeys() || [];
        roleForm.permissions = updated;
        updateNodeDisabledState(permissionTreeData.value, updated);
        nextTick(() => {
          isAutoUncheckingParent.value = false;
        });
      });
      roleFormRef.value?.validateField("permissions");
      return;
    }
  }

  // 如果勾选的是三级权限（叶子节点），自动勾选同级的"查看"权限
  if (isChecked && isLeafNode && data.label !== "查看" && currentNode) {
    if (currentNode.parent) {
      // 获取父节点的数据
      const parentNode = currentNode.parent;
      const parentData = parentNode.data;

      // 在父节点的子节点中查找"查看"权限
      if (parentData.children && parentData.children.length > 0) {
        const viewPermission = parentData.children.find((child: any) => child.label === "查看");

        if (viewPermission) {
          // 检查"查看"权限是否已经被勾选
          const viewNode = permissionTreeRef.value?.getNode(viewPermission.id);
          if (viewNode && !viewNode.checked) {
            // 设置标志位，防止递归
            isAutoCheckingView.value = true;

            // 自动勾选"查看"权限（第三个参数 false 表示不深度勾选子节点）
            nextTick(() => {
              permissionTreeRef.value?.setChecked(viewPermission.id, true, false);
              // 更新权限列表
              const updatedCheckedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
              roleForm.permissions = updatedCheckedKeys;
              // 更新节点的禁用状态
              updateNodeDisabledState(permissionTreeData.value, updatedCheckedKeys);

              // 重置标志位
              nextTick(() => {
                isAutoCheckingView.value = false;
              });
            });
          }
        }
      }
    }
  }

  // 更新节点的禁用状态（每次权限变化后都更新）
  nextTick(() => {
    const finalCheckedKeys = permissionTreeRef.value?.getCheckedKeys() || [];
    updateNodeDisabledState(permissionTreeData.value, finalCheckedKeys);
  });

  // 触发表单验证
  roleFormRef.value?.validateField("permissions");
};

// 返回
const handleBack = () => {
  router.back();
};

// 取消
const handleCancel = () => {
  router.back();
};

// 获取所有需要传递的菜单ID（包括父节点）
const getAllCheckedMenuIds = (): number[] => {
  if (!permissionTreeRef.value) return [];

  const checkedKeys = permissionTreeRef.value.getCheckedKeys() || [];
  const allMenuIds = new Set<number>();

  // 先添加所有被勾选的节点ID（过滤掉null和undefined）
  checkedKeys.forEach((key: any) => {
    if (key !== null && key !== undefined && typeof key === "number") {
      allMenuIds.add(key);
    }
  });

  // 遍历所有被勾选的节点，找到它们的父节点并添加到列表中
  checkedKeys.forEach((key: any) => {
    if (key === null || key === undefined) return;

    const node = permissionTreeRef.value?.getNode(key);
    if (node && node.parent) {
      // 递归向上查找所有父节点
      let parent = node.parent;
      while (parent && parent.data) {
        const parentId = parent.data.id;
        // 只添加有效的数字ID
        if (parentId !== null && parentId !== undefined && typeof parentId === "number") {
          allMenuIds.add(parentId);
        }
        parent = parent.parent;
      }
    }
  });

  return Array.from(allMenuIds);
};

// 保存
const handleSave = async () => {
  if (!roleFormRef.value) return;

  await roleFormRef.value.validate(async valid => {
    if (!valid) return;

    saveLoading.value = true;
    try {
      // 获取所有被勾选的菜单ID（包括父节点）
      const checkedKeys = getAllCheckedMenuIds();

      // 从缓存中获取 createdId，如果没有则从用户信息中获取 storeId
      const createdId = localGet("createdId") || localGet("geeker-user")?.userInfo?.storeId || "";

      const createRoleDto = {
        roleName: roleForm.roleName,
        menuIds: checkedKeys,
        storeId: createdId
      };

      const updateRoleDto = {
        roleName: roleForm.roleName,
        menuIds: checkedKeys,
        storeId: createdId
      };

      let res;
      if (isEdit.value && roleId.value) {
        // 编辑模式：调用更新接口
        res = await updateRole({
          ...updateRoleDto,
          roleId: Number(roleId.value)
        } as any);
      } else {
        // 创建模式：调用创建接口
        res = await createRole(createRoleDto);
      }

      // res.code 可能是 string 或 number，使用 == 进行宽松比较
      const code = typeof res.code === "string" ? parseInt(res.code) : res.code;
      if (code === 200) {
        ElMessage.success(isEdit.value ? "编辑成功" : "创建成功");
        // 返回列表页
        router.push("/accountRoleManagement/roleManagement");
      }
    } catch (error) {
      ElMessage.error(isEdit.value ? "编辑失败，请重试" : "创建失败，请重试");
    } finally {
      saveLoading.value = false;
    }
  });
};
</script>

<style lang="scss" scoped>
.role-form-container {
  min-height: calc(100vh - 84px);
  padding: 20px;
  background: #ffffff;
}

// 头部区域
.header-section {
  position: relative;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #e4e7ed;
  .page-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    text-align: center;
  }
  .header-tip {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    margin-top: 40px;
    .tip-alert {
      background: #f5f7fa;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      :deep(.el-alert__content) {
        .el-alert__title {
          font-size: 14px;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
}

// 表单内容
.form-content {
  max-width: 800px;
  padding: 24px 0;
  :deep(.el-form-item) {
    margin-bottom: 24px;
    .el-form-item__label {
      display: flex;
      align-items: center;
      font-weight: 500;
      .question-icon {
        margin-left: 4px;
        color: #909399;
        cursor: help;
      }
      .required-star {
        margin-left: 4px;
        color: #f56c6c;
      }
    }
  }
  .permission-tree-container {
    width: 100%;
    min-height: 300px;
    max-height: 500px;
    padding: 16px;
    overflow-y: auto;
    background: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    :deep(.el-tree) {
      background: transparent;
      .el-tree-node {
        .el-tree-node__content {
          height: 40px;
          padding: 0 12px;
          margin-bottom: 2px;
          border-radius: 4px;
          transition: background-color 0.2s;
          &:hover {
            background-color: #ecf5ff;
          }
          .tree-node-label {
            display: flex;
            flex: 1;
            align-items: center;
            font-size: 14px;
            color: var(--el-text-color-primary);
          }
        }
        .el-checkbox {
          margin-right: 8px;
        }

        // 树节点缩进
        .el-tree-node__children {
          padding-left: 20px;
        }
      }
      .el-tree-node__expand-icon {
        margin-right: 6px;
        font-size: 14px;
        color: #909399;
        transform: translateX(-5px);
      }

      // 隐藏默认的展开图标，使用自定义样式
      .el-tree-node__expand-icon.is-leaf {
        display: none;
      }
    }
  }
}

// 底部按钮
.form-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding: 24px 0;
  margin-top: 24px;
  border-top: 1px solid #e4e7ed;
}
</style>
