<template>
  <AdminLayout 
    title="系统管理" 
    subtitle="管理用户、角色、权限、部门等系统信息"
  >
    <div class="module-permission-manage">
      <div class="header">
        <h2>模块权限管理</h2>
        <el-button type="primary" @click="handleAddModule">
          <el-icon><Plus /></el-icon>
          新增模块
        </el-button>
      </div>

    <div class="content-wrapper">
      <!-- 左侧：模块树 -->
      <div class="left-panel">
        <div class="panel-header">
          <h3>模块列表</h3>
          <el-input
            v-model="moduleSearchText"
            placeholder="搜索模块"
            :prefix-icon="Search"
            clearable
            size="small"
          />
        </div>
        
        <div v-loading="moduleLoading" class="module-tree-wrapper">
          <div 
            v-for="module in filteredModules" 
            :key="module.moduleID"
            :class="['module-item', { active: currentModule?.moduleID === module.moduleID }]"
            @click="handleSelectModule(module)"
          >
            <div class="module-item-content">
              <el-icon v-if="module.icon" :class="module.icon" class="module-icon" />
              <div class="module-info">
                <span class="module-name">{{ module.name }}</span>
                <span class="module-code">{{ module.code }}</span>
              </div>
              <el-tag :type="module.status === 1 ? 'success' : 'info'" size="small">
                {{ module.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </div>
            <div class="module-actions" @click.stop>
              <el-button 
                type="primary" 
                size="small" 
                link
                @click="handleEditModule(module)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                link
                @click="handleDeleteModule(module)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：权限管理 -->
      <div class="right-panel">
        <div v-if="!currentModule" class="empty-state">
          <el-empty description="请选择左侧模块查看权限" />
        </div>
        
        <div v-else class="permission-panel">
          <!-- 模块信息栏 -->
          <div class="module-info-bar">
            <div class="info-content">
              <h4>{{ currentModule.name }}</h4>
              <div class="info-details">
                <span>模块代码：{{ currentModule.code }}</span>
                <span>模块ID：{{ currentModule.moduleID }}</span>
              </div>
            </div>
            <el-button type="primary" @click="handleAddPermission">
              <el-icon><Plus /></el-icon>
              创建权限
            </el-button>
          </div>

          <!-- 权限列表 -->
          <div v-loading="permissionLoading" class="permission-list">
            <div 
              v-for="permission in permissions" 
              :key="permission.permissionID"
              class="permission-card"
            >
              <div class="permission-info">
                <div class="permission-header">
                  <span class="permission-name">{{ permission.name }}</span>
                  <el-tag type="success" size="small">已绑定</el-tag>
                </div>
                <div class="permission-details">
                  <div class="detail-row">
                    <span class="detail-label">权限编码:</span>
                    <span class="detail-value">{{ permission.code }}</span>
                  </div>
                  <div class="detail-row" v-if="permission.description">
                    <span class="detail-label">描述:</span>
                    <span class="detail-value">{{ permission.description }}</span>
                  </div>
                </div>
              </div>
              <div class="permission-actions">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handleEditPermission(permission)"
                >
                  编辑
                </el-button>
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handleBindMenu(permission)"
                >
                  绑定菜单
                </el-button>
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handleBindRole(permission)"
                >
                  绑定角色
                </el-button>
                <el-button 
                  type="danger" 
                  size="small"
                  @click="handleDeletePermission(permission)"
                >
                  删除
                </el-button>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty 
              v-if="!permissionLoading && permissions.length === 0" 
              description="该模块暂无权限，点击上方按钮创建权限"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 模块编辑对话框 -->
    <el-dialog 
      v-model="moduleDialogVisible" 
      :title="isEditModule ? '编辑模块' : '新增模块'"
      width="600px"
      @close="resetModuleForm"
    >
      <div class="form-content">
        <div class="form-item">
          <span class="form-label required">模块名称</span>
          <el-input 
            v-model="moduleForm.name" 
            placeholder="请输入模块名称"
            clearable
          />
        </div>
        <div class="form-item">
          <span class="form-label required">模块代码</span>
          <el-input 
            v-model="moduleForm.code" 
            placeholder="请输入模块代码（如：system）"
            clearable
            :disabled="isEditModule"
          />
          <span class="form-tip">模块代码必须以小写字母开头，只能包含小写字母、数字和下划线</span>
        </div>
        <div class="form-item">
          <span class="form-label">模块图标</span>
          <el-input 
            v-model="moduleForm.icon" 
            placeholder="请输入图标类名（如：el-icon-setting）"
            clearable
          >
            <template #prefix>
              <el-icon v-if="moduleForm.icon" :class="moduleForm.icon" />
            </template>
          </el-input>
        </div>
        <div class="form-item">
          <span class="form-label required">排序号</span>
          <el-input-number 
            v-model="moduleForm.orderNum" 
            :min="0"
            :max="9999"
            controls-position="right"
            style="width: 100%"
          />
        </div>
        <div class="form-item">
          <span class="form-label required">模块状态</span>
          <el-radio-group v-model="moduleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </div>
        <div class="form-item">
          <span class="form-label">模块描述</span>
          <el-input 
            v-model="moduleForm.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入模块描述"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="moduleDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmitModule"
          :loading="submitting"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限编辑对话框 -->
    <el-dialog 
      v-model="permissionDialogVisible" 
      :title="isEditPermission ? '编辑权限' : '新增权限'"
      width="600px"
      @close="resetPermissionForm"
    >
      <div class="form-content">
        <div class="form-item">
          <span class="form-label required">权限名称</span>
          <el-input 
            v-model="permissionForm.name" 
            placeholder="请输入权限名称"
            clearable
          />
        </div>
        <div class="form-item">
          <span class="form-label required">权限编码</span>
          <el-input 
            v-model="permissionForm.code" 
            placeholder="请输入权限编码（如：system:module:create）"
            clearable
          />
          <span class="form-tip">建议格式：模块:功能:操作，如 system:user:create</span>
        </div>
        <div class="form-item">
          <span class="form-label">权限描述</span>
          <el-input 
            v-model="permissionForm.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmitPermission"
          :loading="submitting"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 绑定菜单对话框 -->
    <GenericSelector
      v-model:visible="bindMenuDialogVisible"
      :title="`绑定菜单 - ${currentPermission?.name || ''}`"
      left-title="可选菜单"
      right-title="已选菜单"
      :fetch-available-api="fetchAllMenus"
      :fetch-selected-api="fetchPermissionMenus"
      :filter-selected="filterMenus"
      :item-config="{ id: 'menuID', label: 'name', sublabel: 'url' }"
      :use-tree="true"
      :tree-transform="transformMenusToTree"
      :tree-props="{ children: 'children', label: 'name', id: 'menuID' }"
      :only-leaf-selectable="true"
      unit-name="个"
      search-placeholder="搜索菜单名称..."
      @confirm="handleMenuConfirm"
      @cancel="resetBindList"
    />

    <!-- 绑定角色对话框 -->
    <GenericSelector
      v-model:visible="bindRoleDialogVisible"
      :title="`绑定角色 - ${currentPermission?.name || ''}`"
      left-title="可选角色"
      right-title="已选角色"
      :fetch-available-api="fetchAllRoles"
      :fetch-selected-api="fetchPermissionRoles"
      :filter-selected="filterRoles"
      :item-config="{ id: 'roleID', label: 'name', sublabel: 'description' }"
      unit-name="个"
      search-placeholder="搜索角色名称..."
      @confirm="handleRoleConfirm"
      @cancel="resetBindList"
    />
    </div>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search } from '@element-plus/icons-vue';
import { moduleApi } from '@/apis/system/module';
import { permissionApi } from '@/apis/system/permission';
import { menuApi } from '@/apis/system/menu';
import { roleApi } from '@/apis/system/role';
import type { SysModule, SysPermission, SysMenu, SysRole } from '@/types';
import { AdminLayout } from '@/views/admin';
import { GenericSelector } from '@/components/base';

defineOptions({
  name: 'ModulePermissionManageView'
});

// 数据状态
const moduleLoading = ref(false);
const permissionLoading = ref(false);
const submitting = ref(false);
const moduleList = ref<SysModule[]>([]);
const permissions = ref<SysPermission[]>([]);

// 当前选中的模块和权限
const currentModule = ref<SysModule | null>(null);
const currentPermission = ref<SysPermission | null>(null);

// 搜索
const moduleSearchText = ref('');

// 对话框状态
const moduleDialogVisible = ref(false);
const permissionDialogVisible = ref(false);
const bindMenuDialogVisible = ref(false);
const bindRoleDialogVisible = ref(false);
const isEditModule = ref(false);
const isEditPermission = ref(false);

// 表单数据
const moduleForm = reactive<Partial<SysModule>>({
  name: '',
  code: '',
  description: '',
  icon: '',
  orderNum: 0,
  status: 1
});

const permissionForm = reactive<Partial<SysPermission>>({
  name: '',
  code: '',
  description: ''
});

// 过滤模块列表
const filteredModules = computed(() => {
  if (!moduleSearchText.value) return moduleList.value;
  const search = moduleSearchText.value.toLowerCase();
  return moduleList.value.filter(module => 
    module.name?.toLowerCase().includes(search) || 
    module.code?.toLowerCase().includes(search)
  );
});

// 加载模块列表
async function loadModuleList() {
  moduleLoading.value = true;
  try {
    const result = await moduleApi.getModuleList();
    if (result.success && result.dataList) {
      moduleList.value = result.dataList.sort((a, b) => (a.orderNum || 0) - (b.orderNum || 0));
    } else {
      ElMessage.error(result.message || '加载模块列表失败');
    }
  } catch (error) {
    console.error('加载模块列表失败:', error);
    ElMessage.error('加载模块列表失败');
  } finally {
    moduleLoading.value = false;
  }
}

// 加载权限列表
async function loadPermissions(moduleID: string) {
  permissionLoading.value = true;
  try {
    const result = await moduleApi.getModulePermissions(moduleID);
    if (result.success && result.dataList) {
      permissions.value = result.dataList;
    } else {
      permissions.value = [];
    }
  } catch (error) {
    console.error('加载权限列表失败:', error);
    ElMessage.error('加载权限列表失败');
    permissions.value = [];
  } finally {
    permissionLoading.value = false;
  }
}

// 选择模块
function handleSelectModule(module: SysModule) {
  currentModule.value = module;
  if (module.moduleID) {
    loadPermissions(module.moduleID);
  }
}

// 新增模块
function handleAddModule() {
  isEditModule.value = false;
  resetModuleForm();
  moduleDialogVisible.value = true;
}

// 编辑模块
function handleEditModule(module: SysModule) {
  isEditModule.value = true;
  Object.assign(moduleForm, module);
  moduleDialogVisible.value = true;
}

// 删除模块
async function handleDeleteModule(module: SysModule) {
  try {
    await ElMessageBox.confirm(
      `确定要删除模块"${module.name}"吗？删除后该模块下的所有权限也会被删除。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await moduleApi.deleteModule(module.moduleID!);
    if (result.success) {
      ElMessage.success('删除成功');
      if (currentModule.value?.moduleID === module.moduleID) {
        currentModule.value = null;
        permissions.value = [];
      }
      loadModuleList();
    } else {
      ElMessage.error(result.message || '删除失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除模块失败:', error);
      ElMessage.error('删除模块失败');
    }
  }
}

// 提交模块表单
async function handleSubmitModule() {
  if (!moduleForm.name) {
    ElMessage.warning('请输入模块名称');
    return;
  }
  if (!moduleForm.code) {
    ElMessage.warning('请输入模块代码');
    return;
  }
  if (!/^[a-z][a-z0-9_]*$/.test(moduleForm.code)) {
    ElMessage.warning('模块代码必须以小写字母开头，只能包含小写字母、数字和下划线');
    return;
  }

  submitting.value = true;
  try {
    let result;
    if (isEditModule.value) {
      result = await moduleApi.updateModule(moduleForm as SysModule);
    } else {
      result = await moduleApi.createModule(moduleForm as SysModule);
    }

    if (result.success) {
      ElMessage.success(isEditModule.value ? '更新成功' : '创建成功');
      moduleDialogVisible.value = false;
      await loadModuleList();
    } else {
      ElMessage.error(result.message || '操作失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  } finally {
    submitting.value = false;
  }
}

// 新增权限
function handleAddPermission() {
  isEditPermission.value = false;
  resetPermissionForm();
  permissionDialogVisible.value = true;
}

// 编辑权限
function handleEditPermission(permission: SysPermission) {
  isEditPermission.value = true;
  Object.assign(permissionForm, permission);
  permissionDialogVisible.value = true;
}

// 删除权限
async function handleDeletePermission(permission: SysPermission) {
  if (!currentModule.value) return;

  try {
    await ElMessageBox.confirm(
      `确定要删除权限"${permission.name}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const result = await moduleApi.deletePermissionInModule(
      currentModule.value.moduleID!,
      permission.permissionID!
    );

    if (result.success) {
      ElMessage.success('删除成功');
      loadPermissions(currentModule.value.moduleID!);
    } else {
      ElMessage.error(result.message || '删除失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error);
      ElMessage.error('删除权限失败');
    }
  }
}

// 提交权限表单
async function handleSubmitPermission() {
  if (!permissionForm.name) {
    ElMessage.warning('请输入权限名称');
    return;
  }
  if (!permissionForm.code) {
    ElMessage.warning('请输入权限编码');
    return;
  }
  if (!currentModule.value) {
    ElMessage.error('请先选择模块');
    return;
  }

  submitting.value = true;
  try {
    const permission: SysPermission = {
      ...permissionForm,
      moduleID: currentModule.value.moduleID
    };

    let result;
    if (isEditPermission.value) {
      result = await moduleApi.updatePermissionInModule(currentModule.value.moduleID!, permission);
    } else {
      result = await moduleApi.createPermissionInModule(currentModule.value.moduleID!, permission);
    }

    if (result.success) {
      ElMessage.success(isEditPermission.value ? '更新成功' : '创建成功');
      permissionDialogVisible.value = false;
      loadPermissions(currentModule.value.moduleID!);
    } else {
      ElMessage.error(result.message || '操作失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败');
  } finally {
    submitting.value = false;
  }
}

// 获取所有菜单的接口
async function fetchAllMenus() {
  return await menuApi.getAllMenuList();
}

// 获取权限已绑定菜单的接口
async function fetchPermissionMenus() {
  if (!currentPermission.value) {
    return { 
      success: true, 
      dataList: [],
      code: 200,
      message: '',
      login: true,
      auth: true
    };
  }
  const permission = { ...currentPermission.value, bindType: 'menu' as const };
  const result = await permissionApi.getPermissionBindingList(permission);
  return { 
    code: result.code || 200,
    message: result.message || '',
    success: result.success,
    login: result.login ?? true,
    auth: result.auth ?? true,
    dataList: result.dataList?.map(item => ({
      ...item,
      name: item.menuName,
      url: item.menuUrl
    })) || []
  };
}

// 获取所有角色的接口
async function fetchAllRoles() {
  const result = await roleApi.getAllRoles();
  if (result.success && result.dataList) {
    result.dataList = result.dataList.map(item => ({
      roleID: item.roleID,
      name: item.roleName,
      description: item.roleDescription
    }));
  }
  return result;
}

// 获取权限已绑定角色的接口
async function fetchPermissionRoles() {
  if (!currentPermission.value) {
    return { 
      success: true, 
      dataList: [],
      code: 200,
      message: '',
      login: true,
      auth: true
    };
  }
  const permission = { ...currentPermission.value, bindType: 'role' as const };
  const result = await permissionApi.getPermissionBindingList(permission);
  return { 
    code: result.code || 200,
    message: result.message || '',
    success: result.success,
    login: result.login ?? true,
    auth: result.auth ?? true,
    dataList: result.dataList?.map(item => ({
      ...item,
      name: item.roleName,
      description: item.roleDescription
    })) || []
  };
}

// 过滤已选菜单项
function filterMenus(available: any[], selected: any[]) {
  const selectedIds = new Set(selected.map(item => item.menuID));
  return available.filter(item => !selectedIds.has(item.menuID));
}

// 过滤已选角色项
function filterRoles(available: any[], selected: any[]) {
  const selectedIds = new Set(selected.map(item => item.roleID));
  return available.filter(item => !selectedIds.has(item.roleID));
}

// 将菜单扁平数据转换为树形结构（根据parentID构建）
function transformMenusToTree(flatData: any[]): any[] {
  if (!flatData || flatData.length === 0) {
    return [];
  }
  
  const tree: any[] = [];
  const map = new Map<string, any>();
  const maxDepth = flatData.length; // 最多遍历len层
  
  // 初始化所有节点
  flatData.forEach(item => {
    if (item.menuID) {
      map.set(item.menuID, { ...item, children: [] });
    }
  });
  
  // 循环构建树结构，最多遍历maxDepth次
  for (let depth = 0; depth < maxDepth; depth++) {
    let hasChanges = false;
    
    flatData.forEach(item => {
      if (!item.menuID) return;
      
      const node = map.get(item.menuID);
      if (!node) return;
      
      // 如果节点已经在树中，跳过
      if (isMenuNodeInTree(node, tree)) {
        return;
      }
      
      if (!item.parentID || item.parentID === '0' || item.parentID === '') {
        // 根节点
        if (!isMenuNodeInTree(node, tree)) {
          tree.push(node);
          hasChanges = true;
        }
      } else {
        // 查找父节点
        const parent = map.get(item.parentID);
        if (parent && isMenuNodeInTree(parent, tree)) {
          if (!parent.children) {
            parent.children = [];
          }
          if (!parent.children.includes(node)) {
            parent.children.push(node);
            hasChanges = true;
          }
        }
      }
    });
    
    // 如果没有变化，说明树构建完成
    if (!hasChanges) {
      break;
    }
  }
  
  // 清理空的children数组
  function cleanEmptyChildren(nodes: any[]) {
    nodes.forEach(node => {
      if (node.children && node.children.length === 0) {
        delete node.children;
      } else if (node.children && node.children.length > 0) {
        cleanEmptyChildren(node.children);
      }
    });
  }
  
  cleanEmptyChildren(tree);
  return tree;
}

// 检查菜单节点是否已经在树中
function isMenuNodeInTree(node: any, tree: any[]): boolean {
  for (const treeNode of tree) {
    if (treeNode.menuID === node.menuID) {
      return true;
    }
    if (treeNode.children && treeNode.children.length > 0) {
      if (isMenuNodeInTree(node, treeNode.children)) {
        return true;
      }
    }
  }
  return false;
}

// 绑定菜单
async function handleBindMenu(permission: SysPermission) {
  currentPermission.value = permission;
  bindMenuDialogVisible.value = true;
}

// 绑定角色
async function handleBindRole(permission: SysPermission) {
  currentPermission.value = permission;
  bindRoleDialogVisible.value = true;
}

// 菜单选择确认 - 在confirm时提交请求
async function handleMenuConfirm(items: SysMenu[]) {
  if (!currentPermission.value?.permissionID) {
    ElMessage.error('权限信息不完整');
    return;
  }
  
  try {
    submitting.value = true;
    
    // 获取当前已绑定的菜单
    const permission: SysPermission = { ...currentPermission.value, bindType: 'menu' };
    const bindingResult = await permissionApi.getPermissionBindingList(permission);
    const currentBoundIds = (bindingResult.data?.menus || []).map(m => m.menuID).filter((id): id is string => !!id);
    
    // 新选择的菜单ID
    const newSelectedIds = items.map(m => m.menuID).filter((id): id is string => !!id);
    
    // 找出需要绑定和解绑的菜单
    const menusToBind = newSelectedIds.filter(id => !currentBoundIds.includes(id));
    const menusToUnbind = currentBoundIds.filter(id => !newSelectedIds.includes(id));
    
    if (menusToBind.length > 0) {
      const menusToBindObjects = items.filter(m => m.menuID && menusToBind.includes(m.menuID));
      await permissionApi.bindMenu({
        ...currentPermission.value,
        menus: menusToBindObjects,
        permissions: [{ permissionID: currentPermission.value.permissionID }]
      });
    }
    
    if (menusToUnbind.length > 0) {
      const menusToUnbindObjects = menusToUnbind.map(id => ({ menuID: id }));
      await permissionApi.unbindMenu({
        ...currentPermission.value,
        menus: menusToUnbindObjects,
        permissions: [{ permissionID: currentPermission.value.permissionID }]
      });
    }
    
    ElMessage.success('菜单绑定保存成功');
    bindMenuDialogVisible.value = false;
    resetBindList();
  } catch (error) {
    console.error('保存菜单绑定失败:', error);
    ElMessage.error('保存菜单绑定失败');
  } finally {
    submitting.value = false;
  }
}

// 角色选择确认 - 在confirm时提交请求
async function handleRoleConfirm(items: SysRole[]) {
  if (!currentPermission.value?.permissionID) {
    ElMessage.error('权限信息不完整');
    return;
  }
  
  try {
    submitting.value = true;
    
    // 获取当前已绑定的角色
    const permission: SysPermission = { ...currentPermission.value, bindType: 'role' };
    const bindingResult = await permissionApi.getPermissionBindingList(permission);
    const currentBoundIds = (bindingResult.data?.roles || []).map(r => r.roleID).filter((id): id is string => !!id);
    
    // 新选择的角色ID
    const newSelectedIds = items.map(r => r.roleID).filter((id): id is string => !!id);
    
    // 找出需要绑定和解绑的角色
    const rolesToBind = newSelectedIds.filter(id => !currentBoundIds.includes(id));
    const rolesToUnbind = currentBoundIds.filter(id => !newSelectedIds.includes(id));
    
    if (rolesToBind.length > 0) {
      const rolesToBindObjects = items.filter(r => r.roleID && rolesToBind.includes(r.roleID));
      await permissionApi.bindRole({
        ...currentPermission.value,
        roles: rolesToBindObjects,
        permissions: [{ permissionID: currentPermission.value.permissionID }]
      });
    }
    
    if (rolesToUnbind.length > 0) {
      const rolesToUnbindObjects = rolesToUnbind.map(id => ({ roleID: id }));
      await permissionApi.unbindRole({
        ...currentPermission.value,
        roles: rolesToUnbindObjects,
        permissions: [{ permissionID: currentPermission.value.permissionID }]
      });
    }
    
    ElMessage.success('角色绑定保存成功');
    bindRoleDialogVisible.value = false;
    resetBindList();
  } catch (error) {
    console.error('保存角色绑定失败:', error);
    ElMessage.error('保存角色绑定失败');
  } finally {
    submitting.value = false;
  }
}

// 重置表单
function resetModuleForm() {
  Object.assign(moduleForm, {
    name: '',
    code: '',
    description: '',
    icon: '',
    orderNum: 0,
    status: 1
  });
}

function resetPermissionForm() {
  Object.assign(permissionForm, {
    name: '',
    code: '',
    description: ''
  });
}

function resetBindList() {
  currentPermission.value = null;
}

// 初始化
onMounted(() => {
  loadModuleList();
});
</script>

<style scoped lang="scss">
.module-permission-manage {
  background: #FFFFFF;
  padding: 24px;
  border-radius: 14px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #141F38;
    }
  }

  .content-wrapper {
    flex: 1;
    display: flex;
    gap: 20px;
    overflow: hidden;
  }

  .left-panel {
    width: 320px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    background: white;

    .panel-header {
      padding: 16px;
      border-bottom: 1px solid #e4e7ed;

      h3 {
        margin: 0 0 12px 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    .module-tree-wrapper {
      flex: 1;
      overflow-y: auto;
      padding: 8px;

      .module-item {
        padding: 12px;
        margin-bottom: 8px;
        border: 1px solid #e4e7ed;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
          border-color: #409eff;
        }

        &.active {
          background-color: #ecf5ff;
          border-color: #409eff;
        }

        .module-item-content {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 8px;

          .module-icon {
            font-size: 24px;
            color: #409eff;
          }

          .module-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 4px;

            .module-name {
              font-size: 14px;
              font-weight: 600;
              color: #303133;
            }

            .module-code {
              font-size: 12px;
              color: #909399;
            }
          }
        }

        .module-actions {
          display: flex;
          gap: 8px;
          justify-content: flex-end;
        }
      }
    }
  }

  .right-panel {
    flex: 1;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    background: white;
    overflow: hidden;

    .empty-state {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .permission-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .module-info-bar {
        padding: 16px;
        background-color: #f5f7fa;
        border-bottom: 1px solid #e4e7ed;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .info-content {
          flex: 1;

          h4 {
            margin: 0 0 8px 0;
            font-size: 18px;
            color: #303133;
          }

          .info-details {
            display: flex;
            gap: 20px;
            font-size: 13px;
            color: #606266;
          }
        }
      }

      .permission-list {
        flex: 1;
        overflow-y: auto;
        padding: 16px;

        .permission-card {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          padding: 16px;
          border: 1px solid #e4e7ed;
          border-radius: 8px;
          margin-bottom: 12px;
          transition: all 0.3s;
          background: white;

          &:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          }

          .permission-info {
            flex: 1;
            margin-right: 16px;

            .permission-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 12px;

              .permission-name {
                font-size: 16px;
                font-weight: 600;
                color: #303133;
              }
            }

            .permission-details {
              .detail-row {
                display: flex;
                align-items: flex-start;
                margin-bottom: 6px;
                font-size: 13px;

                .detail-label {
                  min-width: 80px;
                  color: #606266;
                  font-weight: 500;
                }

                .detail-value {
                  flex: 1;
                  color: #303133;
                  word-break: break-all;
                }
              }
            }
          }

          .permission-actions {
            display: flex;
            flex-direction: column;
            gap: 8px;
            :deep(.el-button) { margin: 0 !important;}
          }
        }
      }
    }
  }
  // 表单样式
  .form-content {
    .form-item {
      margin-bottom: 20px;

      .form-label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        color: #606266;
        font-weight: 500;

        &.required::before {
          content: '*';
          color: #f56c6c;
          margin-right: 4px;
        }
      }

      .form-tip {
        display: block;
        margin-top: 4px;
        font-size: 12px;
        color: #909399;
      }
    }
  }

}
</style>

