<template>
  <div class="permission-page">
    <TabsBar
      :tabs="permissionModuleTabs"
      v-model="activeTab"
    />

    <div v-show="activeTab === 'roles' && canManageRoles" class="permission-content">
          <div class="exam-header">
            <div class="header-left">
              <h1 class="page-title">角色管理</h1>
              <p class="page-desc">管理系统角色，分配角色权限</p>
            </div>
            <div class="header-right">
              <a-button type="primary" class="btn btn-primary" @click="showAddRoleModal = true">
                <template #icon><PlusOutlined /></template>
                新增角色
              </a-button>
            </div>
          </div>

          <div class="exam-card">
            <div class="card-title">
              <span>角色列表</span>
            </div>
            <a-spin :spinning="loading.roles">
              <a-table :dataSource="roles" :columns="roleColumns" :pagination="rolePagination">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'name'">
                    <div class="role-cell">
                      <span>{{ record.roleName }}</span>
                      <a-badge v-if="record.roleCode === 'admin'" color="var(--color-error)" text="系统默认" />
                    </div>
                  </template>
                  <template v-else-if="column.key === 'action'">
                    <div class="action-buttons">
                      <a-button 
                        class="btn btn-small"
                        :disabled="record.roleCode === 'admin'"
                        @click="handleEditRole(record)"
                      >
                        <template #icon><EditOutlined /></template>
                        编辑
                      </a-button>
                      <a-button 
                        class="btn btn-danger btn-small"
                        :disabled="record.roleCode === 'admin'"
                        @click="handleDeleteRole(record)"
                      >
                        <template #icon><DeleteOutlined /></template>
                        删除
                      </a-button>
                    </div>
                  </template>
                </template>
              </a-table>
            </a-spin>
          </div>
        </div>

      <div v-show="activeTab === 'permission' && canManagePermissions" class="permission-content">
          <div class="exam-header">
            <div class="header-left">
              <h1 class="page-title">权限配置</h1>
              <p class="page-desc">为角色分配系统权限</p>
            </div>
          </div>

          <div class="filter-bar">
            <span>选择角色：</span>
            <select
              v-model="selectedRole"
              class="form-select"
              @change="handleRoleSelect"
            >
              <option v-for="role in roles" :key="role.id" :value="role.id">
                {{ role.roleName }}
              </option>
            </select>
            <a-button type="primary" class="btn btn-primary" @click="handleSavePermissions" :loading="loading.permissions">
              <template #icon><SaveOutlined /></template>
              保存权限配置
            </a-button>
          </div>

          <div class="exam-card">
            <div class="card-title">
              <span>{{ roles.find(r => r.id === selectedRole)?.roleName }} - 权限配置</span>
              <a-tag v-if="isAdminRole" color="var(--color-error)">系统管理员</a-tag>
            </div>
            
            <a-alert
              v-if="isAdminRole"
              message="系统管理员默认拥有权限管理权限，不可取消"
              type="info"
              show-icon
              style="margin-bottom: 16px;"
            />
            
            <a-spin :spinning="loading.permissions">
              <div class="permission-tree-container">
                <a-tree
                  v-model:checkedKeys="checkedKeys"
                  checkable
                  :tree-data="permissionTree"
                  :default-expanded-keys="[1, 2, 3, 4, 5, 6, 7, 55, 60]"
                />
              </div>
            </a-spin>
          </div>
        </div>

      <div v-show="activeTab === 'users' && canManageUsers" class="permission-content">
          <div class="exam-header">
            <div class="header-left">
              <h1 class="page-title">用户管理</h1>
              <p class="page-desc">管理系统用户，分配用户角色</p>
            </div>
            <div class="header-right">
              <a-button type="primary" class="btn btn-primary" @click="showAddUserModal = true">
                <template #icon><PlusOutlined /></template>
                新增用户
              </a-button>
            </div>
          </div>

          <div class="exam-card">
            <div class="card-title">
              <span>用户列表</span>
            </div>
            <a-spin :spinning="loading.users">
              <a-table :dataSource="users" :columns="userColumns" :pagination="userPagination">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'roles'">
                    <div>
                      <div v-if="record.roles && record.roles.length > 0">
                        <a-badge 
                          v-for="(role, index) in record.roles" 
                          :key="index"
                          :color="getRoleColor(role.roleCode || 'general_user')"
                          :text="role.roleName || role.roleCode || '未知角色'"
                        />
                      </div>
                      <span v-else style="color: var(--text-tertiary);">无角色</span>
                    </div>
                  </template>
                  <template v-else-if="column.key === 'deptName'">
                    <span>{{ record.deptName || record.deptId ? (record.deptName || '部门ID: ' + record.deptId) : '-' }}</span>
                  </template>
                  <template v-else-if="column.key === 'status'">
                    <a-badge 
                      :status="record.status === 1 ? 'success' : 'error'" 
                      :text="record.status === 1 ? '活跃' : '禁用'"
                    />
                  </template>
                  <template v-else-if="column.key === 'action'">
                    <div class="action-buttons">
                      <a-button class="btn btn-small" @click="handleViewUser(record)">
                        <template #icon><EyeOutlined /></template>
                        查看
                      </a-button>
                      <a-button class="btn btn-small" @click="handleEditUser(record)">
                        <template #icon><EditOutlined /></template>
                        编辑
                      </a-button>
                      <a-button class="btn btn-danger btn-small" @click="handleDeleteUser(record)">
                        <template #icon><DeleteOutlined /></template>
                        删除
                      </a-button>
                    </div>
                  </template>
                </template>
              </a-table>
            </a-spin>
          </div>
        </div>

      <div v-show="activeTab === 'rules' && canViewRules" class="permission-content">
          <div class="exam-header">
            <div class="header-left">
              <h1 class="page-title">权限规则</h1>
              <p class="page-desc">查看和理解系统权限分配规则</p>
            </div>
          </div>

          <div class="card-row">
            <div class="exam-card" style="flex: 2;">
              <div class="card-title">
                <span>角色权限说明</span>
              </div>
              <a-spin :spinning="loading.roles">
                <div class="role-cards-grid">
                  <div 
                    v-for="role in roles" 
                    :key="role.id"
                    class="role-card"
                    @click="handleSelectRoleByCode(role.roleCode)"
                  >
                    <div class="role-card-header">
                      <h5 :style="{ color: getRoleColor(role.roleCode) }">
                        {{ role.roleName }}
                      </h5>
                      <div>
                        <a-tag v-if="role.roleCode === 'admin'" color="var(--color-error)">系统默认</a-tag>
                        <a-tag v-else-if="role.status === 0" color="var(--text-tertiary)">已禁用</a-tag>
                      </div>
                    </div>
                    <p>{{ role.description || getDefaultRoleDesc(role.roleCode) }}</p>
                    <div class="role-card-footer">
                      <span>角色代码: {{ role.roleCode }}</span>
                    </div>
                  </div>
                </div>
              </a-spin>
            </div>

            <div class="exam-card" style="flex: 1;">
              <div class="card-title">
                <span>权限分配原则</span>
              </div>
              <ul class="rules-list">
                <li><strong>最小权限原则：</strong>只授予用户完成工作所需的最小权限</li>
                <li><strong>职责分离原则：</strong>不同职责的权限应分配给不同角色</li>
                <li><strong>权限继承原则：</strong>高级角色继承低级角色的所有权限</li>
                <li><strong>定期审查原则：</strong>定期审查和更新权限分配</li>
              </ul>
            </div>
          </div>
        </div>

      <!-- 组织管理 -->
      <div v-show="activeTab === 'organization' && canManageOrganization" class="permission-content">
        <!-- 页面头部 -->
        <div class="exam-header">
          <div class="header-left">
            <h1 class="page-title">组织管理</h1>
            <p class="page-desc">统一管理公司和部门信息，维护完整组织架构</p>
          </div>
          <div class="header-right">
              <a-button type="primary" @click="showAddCompanyModal = true">
                <template #icon><PlusOutlined /></template>
                新增公司
              </a-button>
              <a-button type="primary" @click="showAddDeptModal = true">
                <template #icon><PlusOutlined /></template>
                新增部门
              </a-button>
            </div>
        </div>

        <!-- 使用 Ant Design 的 Tabs 组件 -->
        <a-tabs v-model:activeKey="orgActiveSubTab" type="card" style="margin-bottom: 16px;">
          <a-tab-pane key="companies" tab="公司管理">
            <!-- 公司管理内容 -->
            <div class="exam-card">
              <div class="card-title">
                <span>公司列表</span>
                <span class="card-subtitle">共 {{ filteredCompanies.length }} 家公司</span>
              </div>
              <div class="filter-bar">
                <a-input-search
                  v-model:value="companySearchText"
                  placeholder="搜索公司名称、代码..."
                  style="width: 300px"
                  @search="searchCompanies"
                />
                <div class="action-buttons">
                  <a-button @click="resetCompanySearch()">重置</a-button>
                </div>
              </div>
              <a-spin :spinning="loading.companies">
                <a-table
                  :dataSource="paginatedCompanies"
                  :columns="companyColumns"
                  :pagination="companyPagination"
                  rowKey="id"
                  :scroll="{x: 900}"
                >
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'status'">
                      <a-tag :color="record.status === 1 ? 'var(--text-secondary)' : 'var(--color-error)'">
                        {{ record.status === 1 ? '运营中' : '已停用' }}
                      </a-tag>
                    </template>
                    <template v-else-if="column.key === 'action'">
                      <a-space>
                        <a-button type="link" size="small" @click="handleEditCompany(record)">编辑</a-button>
                        <a-popconfirm title="确定要删除这家公司吗？" @confirm="handleDeleteCompany(record)">
                          <a-button type="link" size="small" danger>删除</a-button>
                        </a-popconfirm>
                      </a-space>
                    </template>
                  </template>
                </a-table>
              </a-spin>
            </div>
          </a-tab-pane>
          <a-tab-pane key="departments" tab="部门管理">
            <!-- 部门管理内容 -->
            <div class="exam-card">
              <div class="card-title">
                <span>部门列表</span>
                <span class="card-subtitle">共 {{ departments.length }} 个部门</span>
              </div>
              <div class="filter-bar">
                <a-input-search
                  v-model:value="deptSearchText"
                  placeholder="搜索部门名称..."
                  style="width: 300px"
                  @search="searchDepartments"
                />
                <a-select
                  v-model:value="deptCompanyFilter"
                  placeholder="选择公司"
                  style="width: 200px"
                  @change="fetchDepartments"
                  allow-clear
                >
                  <a-select-option value="">全部公司</a-select-option>
                  <a-select-option v-for="comp in companies" :key="comp.id" :value="comp.id">
                    {{ comp.name }}
                  </a-select-option>
                </a-select>
                <div class="action-buttons">
                  <a-button @click="resetDeptSearch()">重置</a-button>
                </div>
              </div>
              <a-spin :spinning="loading.departments">
                <a-table
                  :dataSource="filteredDepartments"
                  :columns="departmentColumns"
                  :pagination="deptPagination"
                  rowKey="id"
                  :scroll="{x: 900}"
                >
                  <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'deptName'">
                      <span>
                        {{ record.deptName || record.name || '-' }}
                        <a-tag v-if="record.parentId" color="var(--text-tertiary)" style="margin-left: var(--space-sm);">子部门</a-tag>
                      </span>
                    </template>
                    <template v-else-if="column.key === 'company'">
                      <a-tag color="var(--text-secondary)">{{ getCompanyName(record.companyId) || '-' }}</a-tag>
                    </template>
                    <template v-else-if="column.key === 'manager'">
                      <span>{{ record.managerName || '未设置' }}</span>
                    </template>
                    <template v-else-if="column.key === 'status'">
                      <a-tag :color="record.status === 1 ? 'var(--text-secondary)' : 'var(--color-error)'">
                        {{ record.status === 1 ? '正常' : '停用' }}
                      </a-tag>
                    </template>
                    <template v-else-if="column.key === 'action'">
                      <a-space>
                        <a-button type="link" size="small" @click="handleEditDepartment(record)">编辑</a-button>
                        <a-popconfirm title="确定要删除这个部门吗？删除后不可恢复！" @confirm="handleDeleteDepartment(record)">
                          <a-button type="link" size="small" danger>删除</a-button>
                        </a-popconfirm>
                      </a-space>
                    </template>
                  </template>
                </a-table>
              </a-spin>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>

    <!-- 无权限提示 -->
    <div v-if="!canManageRoles && !canManagePermissions && !canManageUsers && !canViewRules && !canManageOrganization" class="empty-state" style="height: 60vh; display: flex; flex-direction: column; justify-content: center; align-items: center;">
      <LockOutlined style="font-size: 64px; color: var(--border-default); margin-bottom: var(--space-lg);" />
      <h3 style="color: var(--text-tertiary); margin-bottom: var(--space-sm);">暂无权限</h3>
      <p style="color: var(--text-tertiary);">您没有权限管理模块的任何权限，请联系管理员</p>
    </div>

    <a-modal
      title="新增角色"
      v-model:open="showAddRoleModal"
      @ok="handleAddRole"
      @cancel="showAddRoleModal = false"
      :width="520"
    >
      <a-form layout="vertical">
        <a-form-item label="角色名称" required>
          <a-input 
            v-model:value="newRoleName"
            placeholder="请输入角色名称，如：文档管理员"
            :maxLength="50"
            show-count
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="角色代码" required>
          <a-input 
            v-model:value="newRoleCode"
            placeholder="请输入角色代码，如：doc_admin"
            :maxLength="50"
            show-count
            class="form-input"
          />
          <div class="form-tip">
            角色代码用于系统识别，建议使用英文小写+下划线格式
          </div>
        </a-form-item>
        <a-form-item label="角色描述">
          <a-textarea 
            v-model:value="newRoleDesc"
            placeholder="请输入角色描述，说明该角色的职责和权限范围"
            :rows="3"
            :maxLength="200"
            show-count
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="角色状态">
          <a-radio-group v-model:value="newRoleStatus">
            <a-radio value="1">启用</a-radio>
            <a-radio value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      title="新增用户"
      v-model:open="showAddUserModal"
      @ok="handleAddUser"
      @cancel="showAddUserModal = false"
    >
      <a-form layout="vertical">
        <a-form-item label="用户名" required>
          <a-input 
            v-model:value="newUserName" 
            placeholder="请输入用户名"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="密码" required>
          <a-input-password 
            v-model:value="newUserPassword" 
            placeholder="请输入密码"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="真实姓名" required>
          <a-input 
            v-model:value="newUserRealName" 
            placeholder="请输入真实姓名"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input 
            v-model:value="newUserEmail" 
            placeholder="请输入邮箱"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="电话">
          <a-input 
            v-model:value="newUserPhone" 
            placeholder="请输入电话"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="所属部门" required>
          <select
            v-model="newUserDeptId"
            class="form-select"
          >
            <option value="">请选择部门</option>
            <option v-for="dept in departments" :key="dept.id" :value="dept.id">
              {{ dept.deptName }}
            </option>
          </select>
        </a-form-item>
        <a-form-item label="用户角色" required>
          <select
            v-model="newUserRoleIds"
            class="form-select"
          >
            <option value="">请选择角色</option>
            <option v-for="role in roles" :key="role.id" :value="role.id">
              {{ role.roleName }}
            </option>
          </select>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      title="用户详情"
      v-model:open="showUserDetailModal"
      :width="600"
      :footer="null"
    >
      <a-spin :spinning="loading.userDetail">
        <template v-if="currentUser">
          <a-descriptions bordered :column="1" size="middle">
            <a-descriptions-item label="用户ID">
              {{ currentUser.id }}
            </a-descriptions-item>
            <a-descriptions-item label="用户名">
              {{ currentUser.username }}
            </a-descriptions-item>
            <a-descriptions-item label="真实姓名">
              {{ currentUser.realName }}
            </a-descriptions-item>
            <a-descriptions-item label="角色">
              <div v-for="role in currentUser.roles" :key="role.id">
                <a-badge 
                  :color="getRoleColor(role.roleCode)"
                  :text="role.roleName"
                />
              </div>
            </a-descriptions-item>
            <a-descriptions-item label="部门">
              {{ currentUser.deptName }}
            </a-descriptions-item>
            <a-descriptions-item label="邮箱">
              {{ currentUser.email }}
            </a-descriptions-item>
            <a-descriptions-item label="电话">
              {{ currentUser.phone }}
            </a-descriptions-item>
            <a-descriptions-item label="状态">
              <a-badge 
                :status="currentUser.status === 1 ? 'success' : 'error'" 
                :text="currentUser.status === 1 ? '活跃' : '禁用'"
              />
            </a-descriptions-item>
          </a-descriptions>

          <div class="user-activities">
            <h4>最近活动</h4>
            <div class="activities-list">
              <div v-if="currentUserRecentActivities.length > 0">
                <div 
                  v-for="(activity, index) in currentUserRecentActivities" 
                  :key="index"
                  class="activity-item"
                >
                  <span>{{ activity.operationDesc }}</span>
                  <span>{{ activity.createTime }}</span>
                </div>
              </div>
              <div v-else class="empty-activities">
                暂无活动记录
              </div>
            </div>
          </div>
        </template>
      </a-spin>
    </a-modal>

    <a-modal
      title="编辑角色"
      v-model:open="showEditRoleModal"
      @ok="handleSaveEditRole"
      @cancel="showEditRoleModal = false"
    >
      <a-form layout="vertical">
        <a-form-item label="角色名称" required>
          <a-input 
            v-model:value="editRoleName"
            placeholder="请输入角色名称"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="角色描述">
          <a-textarea 
            v-model:value="editRoleDesc"
            placeholder="请输入角色描述"
            :rows="3"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="角色状态">
          <select
            v-model="editRoleStatus"
            class="form-select"
          >
            <option value="1">启用</option>
            <option value="0">禁用</option>
          </select>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      title="编辑用户"
      v-model:open="showEditUserModal"
      @ok="handleSaveEditUser"
      @cancel="showEditUserModal = false"
    >
      <a-form layout="vertical">
        <a-form-item label="真实姓名" required>
          <a-input 
            v-model:value="editUserRealName"
            placeholder="请输入真实姓名"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input 
            v-model:value="editUserEmail"
            placeholder="请输入邮箱"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="电话">
          <a-input 
            v-model:value="editUserPhone"
            placeholder="请输入电话"
            class="form-input"
          />
        </a-form-item>
        <a-form-item label="所属部门" required>
          <select
            v-model="editUserDeptId"
            class="form-select"
          >
            <option value="">请选择部门</option>
            <option v-for="dept in departments" :key="dept.id" :value="dept.id">
              {{ dept.deptName }}
            </option>
          </select>
        </a-form-item>
        <a-form-item label="用户状态" required>
          <select
            v-model="editUserStatus"
            class="form-select"
          >
            <option value="1">活跃</option>
            <option value="0">禁用</option>
          </select>
        </a-form-item>
        <a-form-item label="用户角色" required>
          <select
            v-model="editUserRoleIds"
            class="form-select"
          >
            <option value="">请选择角色</option>
            <option v-for="role in roles" :key="role.id" :value="role.id">
              {{ role.roleName }}
            </option>
          </select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 公司管理模态框 -->
    <a-modal
      :title="editingCompany ? '编辑公司' : '新增公司'"
      v-model:open="showAddCompanyModal"
      @ok="handleSaveCompany"
      :confirmLoading="loading.companies"
      @cancel="resetCompanyForm"
      width="600px"
    >
      <a-form
        :model="companyForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        ref="companyFormRef"
      >
        <a-form-item
          label="公司名称"
          name="name"
          :rules="[{ required: true, message: '请输入公司名称' }]"
        >
          <a-input v-model:value="companyForm.name" placeholder="请输入公司名称" />
        </a-form-item>
        <a-form-item
          label="公司代码"
          name="code"
          :rules="[{ required: true, message: '请输入公司代码' }]"
        >
          <a-input v-model:value="companyForm.code" placeholder="请输入公司代码（如：COMP001）" />
        </a-form-item>
        <a-form-item label="公司描述" name="description">
          <a-textarea v-model:value="companyForm.description" placeholder="请输入公司描述" :rows="3" />
        </a-form-item>
        <a-form-item
          label="成立时间"
          name="establishedDate"
        >
          <a-date-picker
            v-model:value="companyForm.establishedDate"
            style="width: 100%"
            placeholder="选择成立时间"
          />
        </a-form-item>
        <a-form-item
          label="联系电话"
          name="phone"
        >
          <a-input v-model:value="companyForm.phone" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item
          label="联系邮箱"
          name="email"
        >
          <a-input v-model:value="companyForm.email" placeholder="请输入联系邮箱" />
        </a-form-item>
        <a-form-item
          label="地址"
          name="address"
        >
          <a-input v-model:value="companyForm.address" placeholder="请输入公司地址" />
        </a-form-item>
        <a-form-item
          label="状态"
          name="status"
        >
          <a-radio-group v-model:value="companyForm.status">
            <a-radio :value="1">运营中</a-radio>
            <a-radio :value="0">已停用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 部门管理模态框 -->
    <a-modal
      :title="editingDepartment ? '编辑部门' : '新增部门'"
      v-model:open="showAddDeptModal"
      @ok="handleSaveDepartment"
      :confirmLoading="loading.departments"
      @cancel="resetDepartmentForm"
      width="600px"
    >
      <a-form
        :model="departmentForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        ref="deptFormRef"
      >
        <a-form-item
          label="部门名称"
          name="deptName"
          :rules="[{ required: true, message: '请输入部门名称' }]"
        >
          <a-input v-model:value="departmentForm.deptName" placeholder="请输入部门名称" />
        </a-form-item>
        <a-form-item
          label="所属公司"
          name="companyId"
          :rules="[{ required: true, message: '请选择所属公司' }]"
        >
          <select
            v-model="departmentForm.companyId"
            class="form-select"
          >
            <option value="">请选择所属公司</option>
            <option v-for="comp in companies" :key="comp.id" :value="comp.id">
              {{ comp.name }}
            </option>
          </select>
        </a-form-item>
        <a-form-item
          label="上级部门"
          name="parentId"
        >
          <a-tree-select
            v-model:value="departmentForm.parentId"
            :tree-data="deptTreeData"
            placeholder="请选择上级部门（可选）"
            allow-clear
            tree-default-expand-all
          />
        </a-form-item>
        <a-form-item
          label="负责人"
          name="managerName"
        >
          <a-input v-model:value="departmentForm.managerName" placeholder="请输入负责人姓名" />
        </a-form-item>
        <a-form-item
          label="联系电话"
          name="phone"
        >
          <a-input v-model:value="departmentForm.phone" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item
          label="排序号"
          name="orderNum"
        >
          <a-input-number v-model:value="departmentForm.orderNum" :min="0" :max="999" style="width: 100%" />
        </a-form-item>
        <a-form-item
          label="描述"
          name="description"
        >
          <a-textarea v-model:value="departmentForm.description" placeholder="请输入部门描述" :rows="2" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
  TeamOutlined,
  UserOutlined,
  LockOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  SaveOutlined,
  BankOutlined,
  ApartmentOutlined,
  SearchOutlined,
  SettingOutlined,
  CheckCircleOutlined,
  InboxOutlined,
  SafetyCertificateOutlined
} from '@ant-design/icons-vue'
import { roleAPI, userAPI, departmentAPI, permissionAPI, companyAPI } from '../api/auth'
import { getDirectPermission, usePermissions } from '../utils/permission.js'
import TabsBar from './common/TabsBar.vue'
import PageHeader from './common/PageHeader.vue'

const emit = defineEmits(['permissions-updated', 'refresh-modules'])

// 细粒度权限检查
const canManageRoles = computed(() => {
  const result = getDirectPermission('role')
  console.log('🔍 权限检查 - 角色管理:', result)
  return result
})
const canManagePermissions = computed(() => {
  const hasPermission = getDirectPermission('permission')
  const hasPermissionManage = getDirectPermission('permission:manage')
  const result = hasPermission || hasPermissionManage
  console.log('🔍 权限检查 - 权限配置:', { hasPermission, hasPermissionManage, result })
  return result
})
const canManageUsers = computed(() => {
  const result = getDirectPermission('user')
  console.log('🔍 权限检查 - 用户管理:', result)
  return result
})
const canManageOrganization = computed(() => {
  const result = getDirectPermission('organization:manage')
  console.log('🔍 权限检查 - 组织管理:', result)
  return result
})
const canViewRules = computed(() => {
  const result = getDirectPermission('role')
  console.log('🔍 权限检查 - 权限规则:', result)
  return result
})

const permissionModuleTabs = computed(() => {
  const tabs = []
  if (canManageRoles.value) {
    tabs.push({ key: 'roles', label: '角色管理', icon: TeamOutlined })
  }
  if (canManagePermissions.value) {
    tabs.push({ key: 'permission', label: '权限配置', icon: LockOutlined })
  }
  if (canManageUsers.value) {
    tabs.push({ key: 'users', label: '用户管理', icon: UserOutlined })
  }
  if (canViewRules.value) {
    tabs.push({ key: 'rules', label: '权限规则', icon: SafetyCertificateOutlined })
  }
  if (canManageOrganization.value) {
    tabs.push({ key: 'organization', label: '组织管理', icon: ApartmentOutlined })
  }
  return tabs
})

const activeTab = ref('roles')
const selectedRole = ref('')
const orgActiveSubTab = ref('companies')

// 获取第一个有权限的标签页
const getFirstAccessibleTab = () => {
  const tabChecks = [
    { key: 'roles', hasPermission: canManageRoles },
    { key: 'permission', hasPermission: canManagePermissions },
    { key: 'users', hasPermission: canManageUsers },
    { key: 'rules', hasPermission: canViewRules },
    { key: 'organization', hasPermission: canManageOrganization }
  ]
  const accessibleTab = tabChecks.find(tab => tab.hasPermission.value)
  return accessibleTab?.key || null
}

// 监听权限变化，确保当前标签页始终有权限
watch([canManageRoles, canManagePermissions, canManageUsers, canViewRules, canManageOrganization], () => {
  // 检查当前标签页是否还有权限
  const currentTabHasPermission = (() => {
    switch (activeTab.value) {
      case 'roles': return canManageRoles.value
      case 'permission': return canManagePermissions.value
      case 'users': return canManageUsers.value
      case 'rules': return canViewRules.value
      case 'organization': return canManageOrganization.value
      default: return false
    }
  })()

  if (!currentTabHasPermission) {
    const firstAccessible = getFirstAccessibleTab()
    if (firstAccessible) {
      activeTab.value = firstAccessible
    }
  }
}, { immediate: true })

watch(activeTab, (newTab) => {
  if (newTab === 'permission') {
    emit('refresh-modules')
  }
})

const checkedKeys = ref([])
const allPermissions = ref([])
const permissionCodeToIdMap = ref({})
const permissionIdToCodeMap = ref({})

const loading = ref({
  roles: false,
  users: false,
  permissions: false,
  departments: false,
  userDetail: false,
  companies: false
})

const rolePagination = ref({
  current: 1,
  pageSize: 10,
  onChange: (page) => {
    rolePagination.value.current = page
    fetchRoles()
  }
})

const userPagination = ref({
  current: 1,
  pageSize: 10,
  onChange: (page) => {
    userPagination.value.current = page
    fetchUsers()
  }
})

const showAddRoleModal = ref(false)
const showAddUserModal = ref(false)
const showEditRoleModal = ref(false)
const showUserDetailModal = ref(false)
const showEditUserModal = ref(false)

const newRoleName = ref('')
const newRoleCode = ref('')
const newRoleDesc = ref('')
const newRoleStatus = ref('1')
const editingRole = ref(null)
const editRoleName = ref('')
const editRoleDesc = ref('')
const editRoleStatus = ref('1')

const newUserName = ref('')
const newUserPassword = ref('')
const newUserRealName = ref('')
const newUserEmail = ref('')
const newUserPhone = ref('')
const newUserDeptId = ref('')
const newUserRoleIds = ref([])
const editingUser = ref(null)
const editUserRealName = ref('')
const editUserEmail = ref('')
const editUserPhone = ref('')
const editUserDeptId = ref('')
const editUserStatus = ref('1')
const editUserRoleIds = ref([])
const currentUser = ref(null)
const currentUserRecentActivities = ref([])

const roles = ref([])
const users = ref([])
const departments = ref([])
const roleIdMap = ref(new Map())

// ========== 公司管理数据 ==========
const companies = ref([])

const companySearchText = ref('')
const showAddCompanyModal = ref(false)
const editingCompany = ref(null)
const companyFormRef = ref(null)
const companyForm = ref({
  name: '',
  code: '',
  description: '',
  establishedDate: null,
  phone: '',
  email: '',
  address: '',
  status: 1
})

// ========== 部门管理数据 ==========
const deptSearchText = ref('')
const deptCompanyFilter = ref(undefined)
const showAddDeptModal = ref(false)
const editingDepartment = ref(null)
const deptFormRef = ref(null)
const departmentForm = ref({
  deptName: '',
  companyId: undefined,
  parentId: undefined,
  managerName: '',
  phone: '',
  orderNum: 1,
  description: ''
})

let isFetchingPermissions = false
let fetchPermissionsTimeout = null
const rolePermissionsCache = new Map()

// 防抖函数
const debounce = (fn, delay) => {
  let timeoutId = null
  return (...args) => {
    if (timeoutId) {
      clearTimeout(timeoutId)
    }
    timeoutId = setTimeout(() => {
      fn(...args)
      timeoutId = null
    }, delay)
  }
}

const handleApiError = (error, defaultMessage) => {
  // 处理限流错误
  if (error.isRateLimitError) {
    message.warning(error.message || '请求过于频繁，请稍后再试')
    console.warn('⚠️ 限流错误:', defaultMessage, error)
    return
  }
  
  if (error.message && error.message.includes('Network Error')) {
    message.error('网络连接失败，请检查后端服务是否正常运行')
  } else if (error.code === 'ERR_CONNECTION_REFUSED' || (error.message && error.message.includes('ECONNREFUSED'))) {
    message.error('无法连接到后端服务，请确保服务已启动')
  } else if (error.response && error.response.status === 404) {
    message.error('请求的接口不存在，请检查后端配置')
  } else {
    message.error(error.message || defaultMessage)
  }
  console.error(defaultMessage + ':', error)
}

// ========== 公司管理计算属性 ==========
const companyColumns = [
  { title: '公司ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '公司名称', dataIndex: 'name', key: 'name', ellipsis: true },
  { title: '公司代码', dataIndex: 'code', key: 'code', width: 120 },
  { title: '联系电话', dataIndex: 'phone', key: 'phone', width: 140 },
  { title: '成立时间', dataIndex: 'establishedDate', key: 'establishedDate', width: 120, sorter: (a, b) => a.establishedDate?.localeCompare(b.establishedDate) },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100, filters: [{ text: '运营中', value: 1 }, { text: '已停用', value: 0 }], onFilter: (value, record) => record.status === value },
  { title: '操作', key: 'action', width: 160, fixed: 'right' }
]

const filteredCompanies = computed(() => {
  if (!companySearchText.value) {
    return companies.value
  }
  const search = companySearchText.value.toLowerCase()
  return companies.value.filter(comp =>
    comp.name.toLowerCase().includes(search) ||
    comp.code.toLowerCase().includes(search) ||
    comp.description?.toLowerCase().includes(search)
  )
})

const paginatedCompanies = computed(() => {
  return filteredCompanies.value
})

const companyPagination = ref({
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// ========== 部门管理计算属性 ==========
const departmentColumns = [
  { title: '部门ID', dataIndex: 'id', key: 'id', width: 80 },
  { title: '部门名称', dataIndex: 'deptName', key: 'deptName', ellipsis: true },
  { title: '所属公司', key: 'company', width: 150 },
  { title: '负责人', key: 'manager', width: 100 },
  { title: '联系电话', dataIndex: 'phone', key: 'phone', width: 130 },
  { title: '排序号', dataIndex: 'orderNum', key: 'orderNum', width: 80 },
  { title: '状态', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 160, fixed: 'right' }
]

const filteredDepartments = computed(() => {
  let result = departments.value

  // 按公司筛选
  if (deptCompanyFilter.value) {
    result = result.filter(dept => dept.companyId === deptCompanyFilter.value)
  }

  // 按搜索文本筛选
  if (deptSearchText.value) {
    const search = deptSearchText.value.toLowerCase()
    result = result.filter(dept =>
      dept.deptName?.toLowerCase().includes(search) ||
      dept.managerName?.toLowerCase().includes(search) ||
      dept.description?.toLowerCase().includes(search)
    )
  }

  return result
})

const deptTreeData = computed(() => {
  const buildTree = (parentId = null) => {
    return departments.value
      .filter(dept => dept.parentId === parentId)
      .map(dept => ({
        value: dept.id,
        title: dept.deptName,
        children: buildTree(dept.id)
      }))
  }
  return buildTree()
})

const deptPagination = ref({
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

const isAdminRole = computed(() => {
  const role = roles.value.find(r => r.id === selectedRole.value)
  return role && role.roleCode === 'admin'
})

const getSelectedRoleCode = () => {
  const role = roles.value.find(r => r.id === selectedRole.value)
  return role ? role.roleCode : ''
}

const systemAllPermissions = ref([])

const buildPermissionTree = (permissions) => {
  console.log('🔧 开始构建权限树，输入权限数量:', permissions ? permissions.length : 0)
  
  if (!permissions || permissions.length === 0) {
    console.warn('⚠️ 权限列表为空，返回空树')
    return []
  }
  
  const isAdmin = isAdminRole.value
  const map = {}
  const roots = []
  
  // 第一步：创建所有节点
  permissions.forEach((perm, index) => {
    console.log(`  [${index}] 权限: id=${perm.id}, name=${perm.permissionName}, parentId=${perm.parentId}`)
    map[perm.id] = {
      title: perm.permissionName,
      key: perm.id,
      disabled: isAdmin && (perm.id === 7 || perm.id === 25 || perm.id === 26 || perm.id === 48 || perm.id === 65),
      children: []
    }
  })
  
  // 第二步：构建树形结构
  permissions.forEach(perm => {
    if (perm.parentId === null || perm.parentId === undefined || perm.parentId === 0) {
      if (map[perm.id]) {
        roots.push(map[perm.id])
        console.log(`  ✅ 添加根节点: ${perm.permissionName} (id=${perm.id})`)
      }
    } else if (map[perm.parentId]) {
      map[perm.parentId].children.push(map[perm.id])
      console.log(`  📎 添加子节点: ${perm.permissionName} (id=${perm.id}) 到父节点 ${perm.parentId}`)
    } else {
      console.warn(`  ⚠️ 找不到父节点 ${perm.parentId}，跳过子节点: ${perm.permissionName}`)
    }
  })
  
  // 第三步：排序
  const sortedRoots = roots.sort((a, b) => {
    const permA = permissions.find(p => p.id === a.key)
    const permB = permissions.find(p => p.id === b.key)
    return (permA?.sortOrder || 0) - (permB?.sortOrder || 0)
  })
  
  console.log('✅ 权限树构建完成，根节点数量:', sortedRoots.length)
  return sortedRoots
}

const fallbackPermissionTree = computed(() => {
  const isAdmin = isAdminRole.value
  return [
    {
      title: '制度文件查看和学习',
      key: 1,
      children: [
        { title: '查看文件列表', key: 8 },
        { title: '阅读文档', key: 9 },
        { title: '上传文件', key: 10 },
        { title: '收藏文件', key: 12 },
        { title: '文件审批', key: 66 },
        { title: '题目管理与审批', key: 68 },
        { title: '管理文件', key: 13 },
      ],
    },
    {
      title: '制度文件管理',
      key: 2,
      children: [
        { title: '知识库同步', key: 14 },
        { title: '题库维护', key: 15 },
      ],
    },
    {
      title: '知识问答',
      key: 3,
      children: [
        { title: '智能对话', key: 16 },
        { title: 'FAQ管理', key: 17 },
      ],
    },
    {
      title: '考察和训练',
      key: 4,
      children: [
        { title: 'AI出题', key: 18 },
        { title: '题库管理', key: 19 },
        { title: '智能组卷', key: 20 },
        { title: '互动训练', key: 21 },
        { title: '试卷考核', key: 67 },
      ],
    },
    {
      title: '纲要学习',
      key: 5,
      children: [
        { title: '纲要生成', key: 22 },
        { title: '互动学习', key: 27 },
      ],
    },
    {
      title: '综合看板',
      key: 6,
      children: [
        { title: '智能预警', key: 23 },
        { title: '决策支持', key: 24 },
      ],
    },
    {
      title: '权限管理（系统管理员默认权限，不可取消）',
      key: 7,
      disabled: isAdmin,
      children: [
        { title: '角色管理', key: 25, disabled: isAdmin },
        { title: '权限配置', key: 48, disabled: isAdmin },
        { title: '用户管理', key: 26, disabled: isAdmin },
        { title: '组织管理', key: 65, disabled: isAdmin },
      ],
    },
  ]
})

const permissionTree = computed(() => {
  const dynamicTree = buildPermissionTree(systemAllPermissions.value)
  if (dynamicTree && dynamicTree.length > 0) {
    console.log('✅ 使用动态权限树')
    return dynamicTree
  }
  console.warn('⚠️ 动态权限树为空，使用fallback权限树')
  return fallbackPermissionTree.value
})

const fetchAllPermissions = async () => {
  try {
    console.log('🔄 开始获取所有权限...')
    const response = await permissionAPI.getAllPermissions()
    console.log('📥 权限API响应:', response.data)
    
    if (response.data.code === 200) {
      systemAllPermissions.value = response.data.data || []
      console.log('✅ 成功获取所有权限:', systemAllPermissions.value.length, '个')
      console.log('📋 权限详情:', systemAllPermissions.value)
      
      systemAllPermissions.value.forEach(p => {
        permissionCodeToIdMap.value[p.permissionCode] = p.id
        permissionIdToCodeMap.value[p.id] = p.permissionCode
      })
    } else {
      console.warn('⚠️ 权限API返回非200状态:', response.data.code)
      throw new Error(response.data.message || '获取权限失败')
    }
  } catch (error) {
    console.error('❌ 获取权限列表失败:', error)
    console.warn('⚠️ 将使用fallback权限树，并初始化默认权限映射')
    
    // 初始化默认权限映射（与fallback权限树对应）
    const defaultPermissions = [
      {id: 1, permissionCode: 'read'},
      {id: 8, permissionCode: 'read:view'},
      {id: 9, permissionCode: 'read:read'},
      {id: 10, permissionCode: 'read:upload'},
      {id: 12, permissionCode: 'read:favorite'},
      {id: 66, permissionCode: 'read:approve'},
      {id: 68, permissionCode: 'read:questionBank'},
      {id: 2, permissionCode: 'manage'},
      {id: 13, permissionCode: 'manage:file'},
      {id: 14, permissionCode: 'manage:sync'},
      {id: 15, permissionCode: 'manage:question'},
      {id: 3, permissionCode: 'qa'},
      {id: 16, permissionCode: 'qa:chat'},
      {id: 17, permissionCode: 'qa:faq'},
      {id: 4, permissionCode: 'exam'},
      {id: 18, permissionCode: 'exam:ai'},
      {id: 19, permissionCode: 'exam:bank'},
      {id: 20, permissionCode: 'exam:paper'},
      {id: 21, permissionCode: 'exam:train'},
      {id: 67, permissionCode: 'exam:exam'},
      {id: 5, permissionCode: 'mind'},
      {id: 22, permissionCode: 'mind:generate'},
      {id: 27, permissionCode: 'mind:learn'},
      {id: 6, permissionCode: 'dashboard'},
      {id: 23, permissionCode: 'dashboard:alert'},
      {id: 24, permissionCode: 'dashboard:decision'},
      {id: 7, permissionCode: 'permission'},
      {id: 25, permissionCode: 'role'},
      {id: 48, permissionCode: 'permission:manage'},
      {id: 26, permissionCode: 'user'},
      {id: 55, permissionCode: 'company:manage'},
      {id: 60, permissionCode: 'dept:manage'},
    ]
    
    defaultPermissions.forEach(p => {
      permissionCodeToIdMap.value[p.permissionCode] = p.id
      permissionIdToCodeMap.value[p.id] = p.permissionCode
    })
    
    console.log('✅ 默认权限映射已初始化')
  }
}

const roleColumns = [
  { title: '角色名称', dataIndex: 'roleName', key: 'roleName' },
  { title: '角色描述', dataIndex: 'description', key: 'description' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
  { title: '操作', key: 'action', width: 200 },
]

const userColumns = [
  { title: '用户ID', dataIndex: 'id', key: 'id' },
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '真实姓名', dataIndex: 'realName', key: 'realName' },
  { title: '角色', dataIndex: 'roles', key: 'roles' },
  { title: '部门', dataIndex: 'deptName', key: 'deptName' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action', width: 250 },
]

const getRoleColor = (roleCode) => {
  const colors = {
    admin: 'var(--color-error)',
    doc_admin: 'var(--text-secondary)',
    exam_admin: 'var(--text-tertiary)',
    hr_user: 'var(--text-secondary)',
    finance_user: 'var(--text-tertiary)',
    general_user: 'var(--border-default)',
  }
  return colors[roleCode] || 'var(--text-secondary)'
}

const getDefaultRoleDesc = (roleCode) => {
  const descriptions = {
    admin: '拥有所有系统权限，包括用户管理、角色管理、系统配置等',
    doc_admin: '管理制度文件和版本，包括上传新版本、对比版本、回滚版本等',
    exam_admin: '管理题库和考试，包括AI出题、题库管理、智能组卷等',
    hr_user: '管理考勤和人事相关制度，查看相关数据报表',
    finance_user: '管理财务相关制度，查看相关数据报表',
    general_user: '查看和学习制度，使用智能对话，参与互动训练',
  }
  return descriptions[roleCode] || '该角色具有特定的系统操作权限，请根据实际需求分配相应权限'
}

const fetchRoles = async () => {
  loading.value.roles = true
  try {
    await fetchAllPermissions()
    
    const response = await roleAPI.getRoles()
    if (response.data.code === 200) {
      roles.value = response.data.data
      
      roleIdMap.value.clear()
      roles.value.forEach(role => {
        roleIdMap.value.set(role.id, role)
      })
      
      const adminRole = roles.value.find(r => r.roleCode === 'admin')
      if (adminRole) {
        await buildPermissionMapping(adminRole.id)
      }
      
      if (roles.value.length > 0 && !selectedRole.value) {
        selectedRole.value = roles.value[0].id
        fetchRolePermissions(selectedRole.value)
      }
    }
  } catch (error) {
    handleApiError(error, '获取角色列表失败')
  } finally {
    loading.value.roles = false
  }
}

const buildPermissionMapping = async (roleId) => {
  try {
    const response = await roleAPI.getRolePermissions(roleId)
    if (response.data.code === 200) {
      const permissions = response.data.data
      allPermissions.value = permissions
      permissions.forEach(p => {
        permissionCodeToIdMap.value[p.permissionCode] = p.id
        permissionIdToCodeMap.value[p.id] = p.permissionCode
      })
    }
  } catch (error) {
    console.error('建立权限映射失败:', error)
  }
}

const fetchUsers = async () => {
  loading.value.users = true
  try {
    const response = await userAPI.getUsers({
      current: userPagination.value.current,
      size: userPagination.value.pageSize
    })
    if (response.data.code === 200) {
      users.value = response.data.data.records
      userPagination.value.total = response.data.data.total
      
      users.value.forEach((user) => {
        // 处理状态字段
        if (typeof user.status === 'string') {
          if (user.status === '启用' || user.status === 'active') {
            user.status = 1
          } else if (user.status === '禁用' || user.status === 'inactive') {
            user.status = 0
          } else {
            const parsedStatus = parseInt(user.status)
            user.status = isNaN(parsedStatus) ? 1 : parsedStatus
          }
        } else if (user.status === null || user.status === undefined) {
          user.status = 1
        } else {
          user.status = parseInt(user.status) || 1
        }
        
        // ✅ 修复：使用真实的角色数据（不再硬编码）
        // 如果用户有roles且是对象格式（从API获取），直接使用
        // 如果用户有roles但是字符串格式，尝试匹配真实角色列表
        if (user.roles && Array.isArray(user.roles) && user.roles.length > 0) {
          // 检查是否已经是对象格式
          if (typeof user.roles[0] === 'object' && user.roles[0].id) {
            console.log(`✅ 用户 ${user.username} 的角色已是对象格式:`, user.roles)
            // 已经是正确的对象格式，无需转换
          } else if (typeof user.roles[0] === 'string') {
            // 字符串格式，需要转换为对象并匹配真实角色
            console.log(`🔄 用户 ${user.username} 的角色是字符串格式:`, user.roles, '正在转换...')
            user.roles = user.roles.map(roleNameOrId => {
              // 尝试在真实角色列表中查找匹配的角色
              const matchedRole = roles.value.find(r => 
                r.roleName === roleNameOrId || 
                r.roleCode === roleNameOrId ||
                String(r.id) === String(roleNameOrId)
              )
              if (matchedRole) {
                console.log(`   匹配成功: "${roleNameOrId}" →`, matchedRole)
                return matchedRole
              } else {
                console.warn(`   ⚠️ 未找到匹配角色: "${roleNameOrId}", 使用默认值`)
                return { 
                  id: roleNameOrId, 
                  roleName: roleNameOrId, 
                  roleCode: 'unknown',
                  _isUnknown: true  // 标记为未知角色
                }
              }
            })
          }
        } else {
          // 用户没有角色信息，标记为无角色（不再硬编码分配）
          console.log(`⚠️ 用户 ${user.username} 没有角色信息`)
          user.roles = []
        }
        
        // ✅ 修复：使用真实的部门数据（不再硬编码）
        // 从已加载的departments列表中匹配部门名称
        if (user.deptId) {
          const matchedDept = departments.value.find(d => 
            d.id === user.deptId || 
            d.deptId === user.deptId
          )
          if (matchedDept) {
            user.deptName = matchedDept.deptName || matchedDept.name || `部门${user.deptId}`
            console.log(`✅ 用户 ${user.username} 部门匹配成功: ID=${user.deptId} → "${user.deptName}"`)
          } else {
            user.deptName = `部门${user.deptId}（未在列表中找到）`
            console.warn(`⚠️ 用户 ${user.username} 部门未找到: ID=${user.deptId}`)
          }
        } else {
          user.deptName = '未分配部门'
        }
      })
    }
  } catch (error) {
    handleApiError(error, '获取用户列表失败')
  } finally {
    loading.value.users = false
  }
}

const fetchRolePermissions = async (roleId) => {
  // 如果正在获取中，不重复请求
  if (isFetchingPermissions) {
    console.log('正在获取权限中，跳过重复请求')
    return
  }
  
  // 优先使用缓存
  if (rolePermissionsCache.has(roleId)) {
    console.log('使用缓存的权限数据')
    const cachedPermissions = rolePermissionsCache.get(roleId)
    applyPermissionsToUI(cachedPermissions, roleId)
    return
  }
  
  isFetchingPermissions = true
  loading.value.permissions = true
  
  try {
    const response = await roleAPI.getRolePermissions(roleId)
    if (response.data.code === 200) {
      const permissions = response.data.data
      
      rolePermissionsCache.set(roleId, permissions)
      console.log('✅ 成功获取角色权限:', permissions.length, '个')
      
      applyPermissionsToUI(permissions, roleId)
    }
  } catch (error) {
    console.error('获取角色权限失败:', error)
    if (!error.isRateLimitError && (!error.message || !error.message.includes('Network Error'))) {
      handleApiError(error, '获取角色权限失败')
    }
  } finally {
    loading.value.permissions = false
    isFetchingPermissions = false
  }
}

const getTreeNodeParentIds = (treeData) => {
  const parentIds = new Set()
  const traverse = (nodes) => {
    if (!nodes) return
    nodes.forEach(node => {
      if (node.children && node.children.length > 0) {
        parentIds.add(node.key)
        traverse(node.children)
      }
    })
  }
  traverse(treeData)
  return parentIds
}

const getParentIdsForLeafIds = (treeData, leafIds) => {
  const result = new Set()
  const traverse = (nodes, ancestors) => {
    if (!nodes) return
    nodes.forEach(node => {
      const currentAncestors = [...ancestors, node.key]
      if (node.children && node.children.length > 0) {
        traverse(node.children, currentAncestors)
      } else {
        if (leafIds.includes(node.key)) {
          ancestors.forEach(id => result.add(id))
        }
      }
    })
  }
  traverse(treeData, [])
  return result
}

const applyPermissionsToUI = (permissions, roleId) => {
  permissions.forEach(p => {
    permissionCodeToIdMap.value[p.permissionCode] = p.id
    permissionIdToCodeMap.value[p.id] = p.permissionCode
  })
  
  let permissionIds = permissions.map(p => p.id)
  
  const role = roles.value.find(r => r.id === roleId)
  if (role && role.roleCode === 'admin') {
    const adminRequiredPermissions = [7, 25, 48, 26, 55, 60]
    adminRequiredPermissions.forEach(permId => {
      if (!permissionIds.includes(permId)) {
        permissionIds.push(permId)
      }
    })
    console.log('✅ 管理员必需权限已自动添加:', adminRequiredPermissions)
  }
  
  console.log('📋 应用到UI的权限ID列表:', permissionIds)

  const parentIds = getTreeNodeParentIds(permissionTree.value)
  const leafPermissionIds = permissionIds.filter(id => !parentIds.has(id))

  console.log('📋 过滤后的叶子节点权限ID:', leafPermissionIds)
  checkedKeys.value = leafPermissionIds
}

const handleRoleSelect = (event) => {
  // 原生 select 的 @change 事件传递的是 event，event.target.value 才是值
  // 同时也支持直接传值，保持兼容性
  const roleId = event && event.target ? event.target.value : event
  selectedRole.value = roleId
  fetchRolePermissions(roleId)
}

const handleSelectRoleByCode = (roleCode) => {
  const role = roles.value.find(r => r.roleCode === roleCode)
  if (role) {
    selectedRole.value = role.id
    fetchRolePermissions(role.id)
    message.info(`已切换到${role.roleName}角色`)
  }
}

const handleSavePermissions = async () => {
  if (!selectedRole.value) {
    message.error('请先选择角色')
    return
  }
  
  loading.value.permissions = true
  try {
    let permissionIds = checkedKeys.value.map(key => {
      const id = typeof key === 'number' ? key : parseInt(key)
      if (isNaN(id)) {
        throw new Error(`无效的权限ID: ${key}`)
      }
      return id
    }).filter(id => id !== null && id !== undefined && !isNaN(id))

    const parentIds = getParentIdsForLeafIds(permissionTree.value, permissionIds)
    parentIds.forEach(pid => {
      if (!permissionIds.includes(pid)) {
        permissionIds.push(pid)
      }
    })

    console.log('📋 准备保存的权限ID（含父节点）:', permissionIds)
    
    const roleCode = getSelectedRoleCode()
    if (roleCode === 'admin') {
      const adminRequiredPermissions = [7, 25, 26, 55, 60]
      adminRequiredPermissions.forEach(permId => {
        if (!permissionIds.includes(permId)) {
          permissionIds.push(permId)
        }
      })
      message.info('系统管理员的权限管理权限已自动保留')
    }
    
    const assignResponse = await roleAPI.assignPermissions(selectedRole.value, permissionIds)
    console.log('✅ 保存权限响应:', assignResponse.data)
    
    if (assignResponse.data.code === 200) {
      message.success('权限配置已保存')
      
      rolePermissionsCache.delete(selectedRole.value)
      
      await fetchRolePermissions(selectedRole.value)
      
      // 验证保存结果，但不要重复请求太多次
      try {
        const verifyResponse = await roleAPI.getRolePermissions(selectedRole.value)
        if (verifyResponse.data.code === 200) {
          const savedPermissionIds = verifyResponse.data.data.map(p => p.id)
          console.log('🔍 验证保存结果 - 保存后的权限ID:', savedPermissionIds)
          console.log('🔍 验证保存结果 - 预期权限ID:', permissionIds)
        }
      } catch (verifyError) {
        console.warn('验证保存结果时出错，跳过验证:', verifyError)
      }
      
      emit('permissions-updated')
    } else {
      throw new Error(assignResponse.data.message || '保存权限配置失败')
    }
  } catch (error) {
    if (error.isRateLimitError) {
      message.warning('保存操作触发限流，请稍后再试')
    } else {
      message.error(error.message || '保存权限配置失败')
    }
    console.error('保存权限配置失败:', error)
  } finally {
    loading.value.permissions = false
  }
}

const handleAddRole = async () => {
  if (!newRoleName.value || !newRoleCode.value) {
    message.error('角色名称和代码不能为空')
    return
  }
  
  const roleCodePattern = /^[a-z0-9_]+$/
  if (!roleCodePattern.test(newRoleCode.value)) {
    message.error('角色代码只能包含英文小写、数字和下划线')
    return
  }
  
  try {
    await roleAPI.createRole({
      roleName: newRoleName.value,
      roleCode: newRoleCode.value,
      description: newRoleDesc.value,
      status: parseInt(newRoleStatus.value)
    })
    message.success(`角色 ${newRoleName.value} 已创建`)
    showAddRoleModal.value = false
    newRoleName.value = ''
    newRoleCode.value = ''
    newRoleDesc.value = ''
    newRoleStatus.value = '1'
    fetchRoles()
  } catch (error) {
    message.error(error.message || '创建角色失败')
    console.error('创建角色失败:', error)
  }
}

const handleEditRole = (record) => {
  editingRole.value = record
  editRoleName.value = record.roleName
  editRoleDesc.value = record.description || ''
  editRoleStatus.value = record.status?.toString() || '1'
  showEditRoleModal.value = true
}

const handleSaveEditRole = async () => {
  if (!editRoleName.value) {
    message.error('角色名称不能为空')
    return
  }
  
  try {
    await roleAPI.updateRole(editingRole.value.id, {
      roleName: editRoleName.value,
      description: editRoleDesc.value,
      status: parseInt(editRoleStatus.value)
    })
    message.success('角色信息已更新')
    showEditRoleModal.value = false
    fetchRoles()
  } catch (error) {
    message.error(error.message || '更新角色失败')
    console.error('更新角色失败:', error)
  }
}

const handleDeleteRole = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除角色 ${record.roleName} 吗？`,
    onOk: async () => {
      try {
        await roleAPI.deleteRole(record.id)
        message.success('角色已删除')
        fetchRoles()
      } catch (error) {
        message.error(error.message || '删除角色失败')
        console.error('删除角色失败:', error)
      }
    }
  })
}

const handleAddUser = async () => {
  if (!newUserName.value || !newUserPassword.value || !newUserRealName.value) {
    message.error('用户名、密码和真实姓名不能为空')
    return
  }
  
  try {
    const userData = {
      username: newUserName.value,
      password: newUserPassword.value,
      realName: newUserRealName.value,
      email: newUserEmail.value,
      phone: newUserPhone.value,
      deptId: newUserDeptId.value ? parseInt(newUserDeptId.value) : null
    }
    await userAPI.createUser(userData)
    
    if (newUserRoleIds.value) {
      await fetchUsers()
      const newUser = users.value.find(u => u.username === newUserName.value)
      if (newUser) {
        const roleIds = [parseInt(newUserRoleIds.value)]
        await userAPI.assignRoles(newUser.id, roleIds)
      }
    }
    
    message.success(`用户 ${newUserRealName.value} 已创建`)
    showAddUserModal.value = false
    newUserName.value = ''
    newUserPassword.value = ''
    newUserRealName.value = ''
    newUserEmail.value = ''
    newUserPhone.value = ''
    newUserDeptId.value = ''
    newUserRoleIds.value = []
    fetchUsers()
  } catch (error) {
    message.error(error.message || '创建用户失败')
    console.error('创建用户失败:', error)
  }
}

const handleViewUser = async (record) => {
  loading.value.userDetail = true
  try {
    currentUser.value = record
    currentUserRecentActivities.value = [
      { operationDesc: '登录系统', createTime: '2026-04-10 09:30:15' },
      { operationDesc: '查看制度文件', createTime: '2026-04-10 10:15:42' },
      { operationDesc: '参与考试训练', createTime: '2026-04-09 14:20:30' }
    ]
    showUserDetailModal.value = true
  } catch (error) {
    message.error(error.message || '获取用户详情失败')
    console.error('获取用户详情失败:', error)
  } finally {
    loading.value.userDetail = false
  }
}

const handleEditUser = async (record) => {
  console.log('📝 开始编辑用户:', record.username || record.realName, '(ID:', record.id, ')')
  editingUser.value = record
  loading.value.userDetail = true
  
  try {
    console.log('📡 正在从API获取用户详情...')
    const response = await userAPI.getUserById(record.id)
    
    if (response.data.code === 200) {
      const userData = response.data.data
      console.log('✅ 用户详情获取成功:', userData)
      console.log('   - 用户名:', userData.username)
      console.log('   - 真实姓名:', userData.realName)
      console.log('   - 部门ID:', userData.deptId)
      console.log('   - 角色数据:', JSON.stringify(userData.roles, null, 2))
      
      editingUser.value = userData
      editUserRealName.value = userData.realName
      editUserEmail.value = userData.email || ''
      editUserPhone.value = userData.phone || ''
      editUserDeptId.value = userData.deptId || ''
      
      // 处理状态字段
      if (userData.status === 1 || userData.status === '1' || userData.status === '启用') {
        editUserStatus.value = '1'
      } else if (userData.status === 0 || userData.status === '0' || userData.status === '禁用') {
        editUserStatus.value = '0'
      } else {
        editUserStatus.value = '1'
      }
      
      // ✅ 增强：更健壮的角色ID提取逻辑
      if (userData.roles && Array.isArray(userData.roles) && userData.roles.length > 0) {
        const firstRole = userData.roles[0]
        
        // 情况1：角色已经是对象格式，直接取id
        if (typeof firstRole === 'object' && firstRole.id) {
          editUserRoleIds.value = String(firstRole.id)
          console.log('✅ 角色ID提取成功（对象格式）:', editUserRoleIds.value, '- 角色:', firstRole.roleName || firstRole.roleCode)
        
        // 情况2：角色是字符串格式，尝试在角色列表中匹配
        } else if (typeof firstRole === 'string') {
          console.log(`🔄 角色是字符串格式:`, firstRole, `正在尝试匹配...`)
          const matchedRole = roles.value.find(r => 
            r.roleName === firstRole || 
            r.roleCode === firstRole ||
            String(r.id) === String(firstRole)
          )
          
          if (matchedRole) {
            editUserRoleIds.value = String(matchedRole.id)
            console.log('✅ 角色匹配成功:', firstRole, '→ ID:', matchedRole.id, '-', matchedRole.roleName)
          } else {
            editUserRoleIds.value = ''
            console.warn('⚠️ 未找到匹配的角色:', firstRole)
          }
          
        // 情况3：其他格式
        } else {
          editUserRoleIds.value = ''
          console.warn('⚠️ 无法识别的角色格式:', typeof firstRole, firstRole)
        }
      } else {
        editUserRoleIds.value = ''
        console.log('⚠️ 该用户没有角色信息')
      }
      
      showEditUserModal.value = true
      console.log('🎉 编辑弹窗已打开')
      console.log('   - 编辑用户部门ID:', editUserDeptId.value)
      console.log('   - 编辑用户角色ID:', editUserRoleIds.value)
    }
  } catch (error) {
    console.error('❌ 获取用户详情失败:', error)
    handleApiError(error, '获取用户详情失败')
    
    // 回退：使用表格中的数据
    console.log('🔄 使用表格中的回退数据...')
    editUserRealName.value = record.realName
    editUserEmail.value = record.email || ''
    editUserPhone.value = record.phone || ''
    editUserDeptId.value = record.deptId || ''
    
    if (record.status === 1 || record.status === '1' || record.status === '启用') {
      editUserStatus.value = '1'
    } else if (record.status === 0 || record.status === '0' || record.status === '禁用') {
      editUserStatus.value = '0'
    } else {
      editUserStatus.value = '1'
    }
    
    // 从表格记录中提取角色ID（使用处理后的数据）
    if (record.roles && Array.isArray(record.roles) && record.roles.length > 0) {
      const tableRole = record.roles[0]
      if (tableRole && tableRole.id) {
        editUserRoleIds.value = String(tableRole.id)
        console.log('✅ 从表格数据中提取到角色ID:', editUserRoleIds.value, '- 角色:', tableRole.roleName || tableRole.roleCode)
      } else {
        editUserRoleIds.value = ''
        console.warn('⚠️ 表格中的角色也没有ID:', tableRole)
      }
    } else {
      editUserRoleIds.value = ''
      console.log('⚠️ 表格记录中没有角色信息')
    }
    
    showEditUserModal.value = true
  } finally {
    loading.value.userDetail = false
  }
}

const handleSaveEditUser = async () => {
  if (!editUserRealName.value) {
    message.error('真实姓名不能为空')
    return
  }
  
  console.log('📝 开始保存用户信息...')
  console.log('   - 用户ID:', editingUser.value.id)
  console.log('   - 真实姓名:', editUserRealName.value)
  console.log('   - 部门ID:', editUserDeptId.value)
  console.log('   - 角色IDs:', editUserRoleIds.value)
  
  try {
    await userAPI.updateUser(editingUser.value.id, {
      realName: editUserRealName.value,
      email: editUserEmail.value,
      phone: editUserPhone.value,
      deptId: parseInt(editUserDeptId.value),
      status: parseInt(editUserStatus.value)
    })
    console.log('✅ 用户基本信息更新成功')
    
    // 安全处理角色分配：只有当用户明确选择了角色（非空）时才更新
    // 防止意外清空用户的角色导致权限丢失
    if (editUserRoleIds.value && editUserRoleIds.value !== '') {
      const roleIds = [parseInt(editUserRoleIds.value)]
      console.log('📋 更新用户角色:', editingUser.value.id, '→', roleIds)
      await userAPI.assignRoles(editingUser.value.id, roleIds)
      console.log('✅ 角色分配成功')
    } else {
      console.log('⚠️ 角色未变更（值为空），保留原有角色不变')
    }
    
    message.success('用户信息已更新')
    showEditUserModal.value = false
    fetchUsers()
    
    // 检查是否修改的是当前登录用户
    const currentUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    console.log('🔍 检查是否为当前用户:')
    console.log('   - 编辑的用户ID:', editingUser.value.id)
    console.log('   - 当前登录用户ID:', currentUserInfo.id)
    console.log('   - 是否匹配:', editingUser.value.id === currentUserInfo.id)
    
    if (editingUser.value.id === currentUserInfo.id) {
      console.log('🔄 检测到修改了当前登录用户的信息，准备刷新权限...')
      
      // 同步更新 localStorage 中的用户信息（保持数据一致性）
      const updatedUserInfo = {
        ...currentUserInfo,
        realName: editUserRealName.value,
        deptId: parseInt(editUserDeptId.value),
        email: editUserEmail.value,
        phone: editUserPhone.value
      }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
      console.log('✅ 已同步更新 localStorage 中的 userInfo')
      
      message.info('您修改了自己的信息，正在刷新功能栏...')
      emit('permissions-updated')
    }
  } catch (error) {
    message.error(error.message || '更新用户失败')
    console.error('❌ 更新用户失败:', error)
    console.error('   错误详情:', error.response?.data || error.message)
  }
}

const handleDeleteUser = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 ${record.realName} 吗？`,
    onOk: async () => {
      try {
        await userAPI.deleteUser(record.id)
        message.success('用户已删除')
        fetchUsers()
      } catch (error) {
        message.error(error.message || '删除用户失败')
        console.error('删除用户失败:', error)
      }
    }
  })
}

// ========== 公司管理方法 ==========

const searchCompanies = () => {
  if (companySearchText.value) {
    message.info(`正在搜索包含"${companySearchText.value}"的公司`)
  } else {
    message.info('请输入搜索关键词')
  }
}

const resetCompanySearch = () => {
  companySearchText.value = ''
  message.info('已重置搜索条件')
}

const handleEditCompany = (company) => {
  editingCompany.value = company
  companyForm.value = { ...company }
  showAddCompanyModal.value = true
}

const handleDeleteCompany = async (company) => {
  const hasDepartments = departments.value.some(d => d.companyId === company.id)
  if (hasDepartments) {
    message.warning(`公司"${company.name}"下存在部门，请先删除部门`)
    return
  }

  try {
    loading.value.companies = true
    const response = await companyAPI.deleteCompany(company.id)

    if (response.data.code === 200) {
      message.success(`公司"${company.name}"删除成功`)
      await fetchCompanies()
    } else {
      message.error(response.data.message || '删除公司失败')
    }
  } catch (error) {
    handleApiError(error, '删除公司失败')
  } finally {
    loading.value.companies = false
  }
}

const handleSaveCompany = async () => {
  try {
    if (!companyFormRef.value) return

    await companyFormRef.value.validate()

    if (!companyForm.value.name || !companyForm.value.name.trim()) {
      message.warning('请输入公司名称')
      return
    }

    loading.value.companies = true

    if (editingCompany.value) {
      // 编辑模式
      const updateData = {
        name: companyForm.value.name.trim(),
        code: companyForm.value.code?.trim() || null,
        description: companyForm.value.description?.trim() || null,
        establishedDate: companyForm.value.establishedDate || null,
        phone: companyForm.value.phone?.trim() || null,
        email: companyForm.value.email?.trim() || null,
        address: companyForm.value.address?.trim() || null,
        status: companyForm.value.status || 1
      }
      console.log('📝 编辑公司参数:', updateData)

      const response = await companyAPI.updateCompany(editingCompany.value.id, updateData)

      if (response.data.code === 200) {
        message.success(`公司"${companyForm.value.name}"更新成功`)
        await fetchCompanies()
        showAddCompanyModal.value = false
        resetCompanyForm()
      } else {
        message.error(response.data.message || '更新公司失败')
      }
    } else {
      // 新增模式
      const createData = {
        name: companyForm.value.name.trim(),
        code: companyForm.value.code?.trim() || null,
        description: companyForm.value.description?.trim() || null,
        establishedDate: companyForm.value.establishedDate || null,
        phone: companyForm.value.phone?.trim() || null,
        email: companyForm.value.email?.trim() || null,
        address: companyForm.value.address?.trim() || null,
        status: companyForm.value.status || 1
      }
      console.log('➕ 创建公司参数:', createData)

      const response = await companyAPI.createCompany(createData)

      if (response.data.code === 200) {
        message.success(`公司"${companyForm.value.name}"创建成功`)
        await fetchCompanies()
        showAddCompanyModal.value = false
        resetCompanyForm()
      } else {
        message.error(response.data.message || '创建公司失败')
      }
    }
  } catch (error) {
    if (error.message !== '验证失败') {
      handleApiError(error, '保存公司失败')
    }
  } finally {
    loading.value.companies = false
  }
}

const resetCompanyForm = () => {
  companyForm.value = {
    name: '',
    code: '',
    description: '',
    establishedDate: null,
    phone: '',
    email: '',
    address: '',
    status: 1
  }
  editingCompany.value = null
  companyFormRef.value?.resetFields()
}

// ========== 公司管理方法 ==========

const fetchCompanies = async () => {
  try {
    const response = await companyAPI.getCompanies()
    if (response.data.code === 200) {
      const rawCompanies = response.data.data || []
      companies.value = rawCompanies.map(c => ({
        id: c.id || c.companyId || c.company_id,
        name: c.name || c.companyName || c.company_name,
        code: c.code || c.companyCode || c.company_code,
        ...c
      }))
      console.log('公司列表加载成功:', companies.value.length, '个公司', companies.value)
    } else {
      console.warn('获取公司列表失败:', response.data.message)
      companies.value = []
    }
  } catch (error) {
    console.warn('获取公司列表异常（使用空列表）:', error.message)
    companies.value = []
  }
}

// ========== 部门管理方法 ==========

const fetchDepartments = async () => {
  loading.value.departments = true
  try {
    const response = await departmentAPI.getDepartments()
    if (response.data.code === 200) {
      const rawDepts = response.data.data || []
      departments.value = rawDepts.map(d => ({
        id: d.id || d.deptId || d.dept_id,
        deptName: d.deptName || d.name || d.dept_name,
        companyId: d.companyId || d.company_id,
        parentId: d.parentId || d.parent_id,
        managerName: d.managerName || d.manager_name,
        phone: d.phone,
        orderNum: d.orderNum || d.sort_order || 1,
        description: d.description,
        status: d.status,
        ...d
      }))
      console.log('部门列表加载成功:', departments.value.length, '个部门', departments.value)
    } else {
      console.warn('获取部门列表失败:', response.data.message)
      message.warning(response.data.message || '获取部门列表失败')
    }
  } catch (error) {
    handleApiError(error, '获取部门列表失败')
  } finally {
    loading.value.departments = false
  }
}

const searchDepartments = () => {
  if (deptSearchText.value) {
    message.info(`正在搜索包含"${deptSearchText.value}"的部门`)
  } else {
    message.info('请输入搜索关键词')
  }
}

const resetDeptSearch = () => {
  deptSearchText.value = ''
  deptCompanyFilter.value = undefined
  fetchDepartments()
  message.info('已重置搜索条件')
}

const getCompanyName = (companyId) => {
  const company = companies.value.find(c => c.id === companyId)
  return company ? company.name : null
}

const handleEditDepartment = (department) => {
  console.log('📝 编辑部门，原始数据:', department)
  editingDepartment.value = department
  departmentForm.value = {
    deptName: department.deptName || department.name || '',
    companyId: department.companyId || department.company_id || '',
    parentId: department.parentId || department.parent_id || null,
    managerName: department.managerName || department.manager_name || '',
    phone: department.phone || '',
    orderNum: department.orderNum || department.sort_order || 1,
    description: department.description || ''
  }
  console.log('📝 编辑部门，表单数据:', departmentForm.value)
  showAddDeptModal.value = true
}

const handleDeleteDepartment = async (department) => {
  const hasChildren = departments.value.some(d => d.parentId === department.id)
  if (hasChildren) {
    message.warning(`部门"${department.deptName}"下存在子部门，请先删除子部门`)
    return
  }

  try {
    loading.value.departments = true
    const response = await departmentAPI.deleteDepartment(department.id)

    if (response.data.code === 200) {
      message.success(`部门"${department.deptName}"删除成功`)
      await fetchDepartments()
    } else {
      message.error(response.data.message || '删除部门失败')
    }
  } catch (error) {
    handleApiError(error, '删除部门失败')
  } finally {
    loading.value.departments = false
  }
}

const handleSaveDepartment = async () => {
  try {
    if (!deptFormRef.value) return

    await deptFormRef.value.validate()

    if (!departmentForm.value.deptName || !departmentForm.value.deptName.trim()) {
      message.warning('请输入部门名称')
      return
    }

    loading.value.departments = true

    if (editingDepartment.value) {
      const updateData = {
        deptName: departmentForm.value.deptName.trim(),
        companyId: departmentForm.value.companyId,
        parentId: departmentForm.value.parentId || null,
        managerName: departmentForm.value.managerName?.trim() || null,
        phone: departmentForm.value.phone?.trim() || null,
        orderNum: departmentForm.value.orderNum || 1,
        description: departmentForm.value.description?.trim() || null
      }
      console.log('📝 编辑部门参数:', updateData)

      const response = await departmentAPI.updateDepartment(editingDepartment.value.id, updateData)

      if (response.data.code === 200) {
        message.success(`部门"${departmentForm.value.deptName}"更新成功`)
        await fetchDepartments()
        showAddDeptModal.value = false
        resetDepartmentForm()
      } else {
        message.error(response.data.message || '更新部门失败')
      }
    } else {
      if (!departmentForm.value.companyId) {
        message.warning('请选择所属公司')
        loading.value.departments = false
        return
      }

      const createData = {
        deptName: departmentForm.value.deptName.trim(),
        companyId: departmentForm.value.companyId,
        parentId: departmentForm.value.parentId || null,
        managerName: departmentForm.value.managerName?.trim() || null,
        phone: departmentForm.value.phone?.trim() || null,
        orderNum: departmentForm.value.orderNum || 1,
        description: departmentForm.value.description?.trim() || null
      }
      console.log('➕ 创建部门参数:', createData)

      const response = await departmentAPI.createDepartment(createData)

      if (response.data.code === 200) {
        message.success(`部门"${departmentForm.value.deptName}"创建成功`)
        await fetchDepartments()
        showAddDeptModal.value = false
        resetDepartmentForm()
      } else {
        message.error(response.data.message || '创建部门失败')
      }
    }
  } catch (error) {
    if (error.message !== '验证失败') {
      handleApiError(error, '保存部门失败')
    }
  } finally {
    loading.value.departments = false
  }
}

const resetDepartmentForm = () => {
  departmentForm.value = {
    deptName: '',
    companyId: undefined,
    parentId: undefined,
    managerName: '',
    phone: '',
    orderNum: 1,
    description: ''
  }
  editingDepartment.value = null
  deptFormRef.value?.resetFields()
}

onMounted(async () => {
  const { userPermissions, accessibleModules } = usePermissions()
  console.log('🔍 PermissionModule 挂载 - 用户权限缓存:', userPermissions.value)
  console.log('🔍 PermissionModule 挂载 - 可访问模块:', accessibleModules.value)
  
  await Promise.all([fetchRoles(), fetchDepartments(), fetchCompanies()])
  await fetchUsers()
})
</script>

<style scoped>
.permission-page {
  height: 100%;
  min-height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 1600px;
  margin: 0 auto;
}

.permission-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: var(--space-lg);
  overflow-y: auto;
  overflow-x: hidden;
  min-width: 0;
}

.main-tabs-bar {
  display: flex;
  gap: var(--space-xs);
  padding: var(--space-sm) var(--space-xl);
  background: var(--bg-base);
  box-shadow: var(--shadow-sm);
  flex-shrink: 0;
}

.main-tab-btn {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  padding: var(--space-xs) var(--space-lg);
  border: none;
  background: transparent;
  border-radius: var(--radius-lg);
  font-size: var(--font-md);
  font-weight: var(--weight-medium);
  cursor: pointer;
  transition: all var(--transition-normal);
  color: var(--text-secondary);
}

.main-tab-btn:hover {
  background: var(--bg-active);
  color: var(--text-primary);
}

.main-tab-btn.active {
  background: var(--color-primary);
  color: white;
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.tab-icon {
  font-size: 18px;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-md);
  padding: var(--space-lg) var(--space-xl);
  background: var(--bg-base);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-light);
}

.header-left {
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
  gap: var(--space-lg);
}

.page-title {
  font-size: var(--font-xl);
  font-weight: var(--weight-semibold);
  color: var(--text-primary);
  margin: 0;
}

.page-desc {
  font-size: var(--font-sm);
  color: var(--text-tertiary);
  margin: 0;
  display: none;
}

.exam-card {
  background: var(--bg-base);
  border-radius: var(--radius-lg);
  padding: var(--space-xl);
  margin-bottom: var(--space-lg);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-light);
  flex: 1;
  min-height: 0;
  overflow: auto;
}

.card-title {
  font-size: var(--font-lg);
  font-weight: var(--weight-semibold);
  color: var(--text-primary);
  margin-bottom: var(--space-lg);
  padding-bottom: var(--space-sm);
  border-bottom: 1px solid var(--border-light);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-sm);
}

.card-row {
  display: flex;
  gap: var(--space-xl);
}

.filter-bar {
  display: flex;
  gap: var(--space-md);
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: var(--space-lg);
  flex-shrink: 0;
}

.btn {
  border-radius: var(--radius-lg);
  padding: 0 var(--space-lg);
  height: 36px;
  font-size: var(--font-md);
  font-weight: var(--weight-medium);
  transition: all var(--transition-normal);
  border: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: var(--space-xs);
}

.btn-primary {
  background: var(--color-primary);
  color: var(--text-inverse);
  box-shadow: var(--shadow-sm);
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.btn-danger {
  background: var(--color-error);
  color: var(--text-inverse);
  box-shadow: var(--shadow-sm);
}

.btn-danger:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.btn-small {
  padding: var(--space-xs) var(--space-md);
  font-size: var(--font-sm);
}

.form-input {
  width: 280px;
  height: var(--input-height);
  border-radius: var(--radius-md);
  border: 1px solid var(--border-default);
  padding: 0 var(--space-md);
  font-size: var(--font-md);
  transition: all var(--transition-normal);
  box-sizing: border-box;
}

.form-input:focus {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 2px var(--color-primary-alpha-20);
}

.form-select {
  width: 130px;
  height: var(--input-height);
  box-sizing: border-box;
}

.form-select :deep(.ant-select-selector) {
  height: var(--input-height) !important;
  min-height: var(--input-height) !important;
  max-height: var(--input-height) !important;
  padding: 0 28px 0 var(--space-md) !important;
  border-radius: var(--radius-md) !important;
  border: 1px solid var(--border-light) !important;
  background: var(--bg-container) !important;
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  overflow: hidden !important;
  box-sizing: border-box !important;
  line-height: 1 !important;
}

.form-select :deep(.ant-select-selection-search) {
  flex: 1;
  height: 100% !important;
  display: flex !important;
  align-items: center !important;
  box-sizing: border-box !important;
}

.form-select :deep(.ant-select-selection-item) {
  height: 100% !important;
  line-height: 1 !important;
  display: flex !important;
  align-items: center !important;
  font-size: var(--font-lg);
  color: var(--text-primary);
  font-weight: var(--weight-medium);
  box-sizing: border-box !important;
  margin: 0 !important;
  padding: 0 !important;
}

.form-select :deep(.ant-select-selection-placeholder) {
  height: 100% !important;
  line-height: 1 !important;
  display: flex !important;
  align-items: center !important;
  font-size: var(--font-lg);
  color: var(--text-tertiary);
  box-sizing: border-box !important;
  margin: 0 !important;
  padding: 0 !important;
}

.form-select :deep(.ant-select-arrow) {
  right: var(--space-md) !important;
  top: 50% !important;
  transform: translateY(-50%) !important;
  margin-top: 0 !important;
  color: var(--text-tertiary);
  font-size: var(--font-sm);
  transition: all var(--transition-normal);
  position: absolute !important;
  height: 16px !important;
  width: 16px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  overflow: hidden !important;
  box-sizing: border-box !important;
}

.form-select :deep(.ant-select-arrow svg) {
  width: 12px !important;
  height: 12px !important;
  box-sizing: border-box !important;
  overflow: visible !important;
  position: relative !important;
  z-index: 1 !important;
}

.form-tip {
  color: var(--text-tertiary);
  font-size: var(--font-sm);
  margin-top: var(--space-xs);
}

.role-cell {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
}

.action-buttons {
  display: flex;
  gap: var(--space-sm);
}

.permission-tree-container {
  border: 1px solid var(--border-light);
  border-radius: var(--radius-lg);
  padding: var(--space-md);
  background-color: var(--bg-container);
  overflow: auto;
}

.role-cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: var(--space-md);
}

.role-card {
  background: var(--bg-base);
  border-radius: var(--radius-lg);
  padding: var(--space-lg);
  border: 1px solid var(--border-light);
  cursor: pointer;
  transition: all var(--transition-normal);
}

.role-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
  border-color: var(--color-primary);
}

.role-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--space-xs);
}

.role-card-header h5 {
  margin: 0;
  font-size: var(--font-md);
  font-weight: var(--weight-semibold);
}

.role-card p {
  color: var(--text-secondary);
  margin: 0;
  font-size: var(--font-lg);
  line-height: 1.5;
}

.role-card-footer {
  margin-top: var(--space-lg);
  padding-top: var(--space-lg);
  border-top: 1px solid var(--border-light);
}

.role-card-footer span {
  color: var(--text-tertiary);
  font-size: var(--font-sm);
}

.rules-list {
  margin: 0;
  padding-left: var(--space-xl);
}

.rules-list li {
  margin-bottom: var(--space-lg);
  font-size: var(--font-lg);
  color: var(--text-primary);
  line-height: 1.6;
}

.rules-list li strong {
  color: var(--color-primary);
}

.user-activities {
  margin-top: var(--space-2xl);
}

.user-activities h4 {
  margin: 0 0 var(--space-lg) 0;
  font-size: var(--font-lg);
  font-weight: var(--weight-semibold);
  color: var(--text-primary);
}

.activities-list {
  padding: var(--space-lg);
  background-color: var(--bg-container);
  border-radius: var(--radius-lg);
}

.activity-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: var(--space-sm);
  padding-bottom: var(--space-sm);
  border-bottom: 1px solid var(--border-light);
}

.activity-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.activity-item span:last-child {
  color: var(--text-tertiary);
  font-size: var(--font-md);
}

.empty-activities {
  text-align: center;
  color: var(--text-tertiary);
}

/* 覆盖 Ant Design 按钮默认蓝色样式 */
:deep(.ant-btn-primary) {
  background: var(--color-primary) !important;
  border-color: var(--color-primary) !important;
  box-shadow: none !important;
}

:deep(.ant-btn-primary:hover) {
  background: var(--color-primary-hover) !important;
  border-color: var(--color-primary-hover) !important;
  transform: translateY(-2px);
  box-shadow: var(--shadow-md) !important;
}

:deep(.ant-btn-dangerous) {
  background: var(--color-error) !important;
  border-color: var(--color-error) !important;
}

:deep(.ant-btn-dangerous:hover) {
  background: var(--color-error-hover) !important;
  border-color: var(--color-error-hover) !important;
}

/* 覆盖 Ant Design Tabs 标签页样式 */
:deep(.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab) {
  background: var(--bg-container);
  border-color: var(--border-light);
  color: var(--text-secondary);
  transition: all var(--transition-normal);
}

:deep(.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab:hover) {
  color: var(--text-primary);
  background: var(--bg-active);
  border-color: var(--border-default);
}

:deep(.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab-active) {
  background: var(--color-primary);
  border-color: var(--color-primary);
  color: white !important;
}

:deep(.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab-active .ant-tabs-tab-btn) {
  color: white !important;
}

/* 覆盖链接按钮样式 */
:deep(.ant-btn-link) {
  color: var(--text-secondary);
}

:deep(.ant-btn-link:hover) {
  color: var(--color-primary);
}
</style>
