Files
syops/frontend/src/views/AdminView.vue
T
2026-03-29 00:55:01 +08:00

3657 lines
163 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
/**
* AdminView.vue
* 文件用途:管理员控制台,用于配置 Dify Agent 与用户权限
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/admin 接口
* 逻辑关系:
* - 通过 /api/admin/agents 管理 Agent 配置
* - 通过 /api/admin/users 与 /permissions 管理用户可访问的 Agent
*/
import { ref, onMounted, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { config } from '../config';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage';
import {
ArrowLeft,
Save,
Plus,
Trash2,
UserPlus,
Edit,
ShieldCheck,
LayoutDashboard,
Bot,
Users,
FileText,
BarChart2,
MessageSquare,
Globe,
Download,
UserCog,
Building,
MessageCircleQuestion,
Settings2,
Megaphone,
Link2,
Unlink2,
RefreshCw
} from 'lucide-vue-next';
import * as XLSX from 'xlsx';
const { t, locale } = useI18n();
const sidebarItems = computed(() => {
const items = [
{ id: 'dashboard', icon: LayoutDashboard, label: t('admin.nav.dashboard') },
{ id: 'approvals', icon: UserPlus, label: t('admin.nav.approvals'), badge: pendingUsers.value.length },
{ id: 'users', icon: UserCog, label: t('admin.nav.users') },
{ id: 'departments', icon: Building, label: t('admin.nav.departments') },
{ id: 'agents', icon: Bot, label: t('admin.nav.agents') },
{ id: 'announcements', icon: Megaphone, label: t('admin.nav.announcements') },
{ id: 'questions', icon: MessageCircleQuestion, label: t('admin.nav.questions') },
{ id: 'wecom', icon: Link2, label: t('admin.nav.wecom') },
{ id: 'permissions', icon: Users, label: t('admin.nav.permissions') },
{ id: 'requests', icon: ShieldCheck, label: t('admin.nav.requests'), badge: permissionRequests.value.filter(r => r.status === 'pending').length },
{ id: 'reports', icon: BarChart2, label: t('admin.nav.reports') },
];
return items.filter(item => {
if (config.admin.modules[item.id as keyof typeof config.admin.modules] === false) {
return false;
}
return true;
});
});
onMounted(() => {
const allowed = sidebarItems.value.map(i => i.id);
if (!allowed.includes(activeModule.value)) {
activeModule.value = (allowed[0] ?? 'agents') as any;
}
});
// 获取路由实例,用于页面跳转
interface AgentRow {
id: number;
name: string;
dify_app_id: string;
dify_api_key: string;
is_active: boolean;
description?: string;
type: 'api' | 'iframe';
api_base_url?: string;
extra_config?: Record<string, any>;
iframe_url?: string; // Frontend helper property
}
interface AgentTestResult {
success: boolean;
request_url: string;
output_info: string;
analysis: string;
http_status?: number;
tested_at?: string;
}
// 定义 User 行的数据结构
interface UserRow {
id: number;
username: string;
email: string;
department?: string;
role: string;
status: string;
real_name?: string;
employee_id?: string;
phone_number?: string;
agent_ids: number[];
}
interface PermissionRequestRow {
id: number;
user_id: number;
agent_id: number;
reason: string;
status: string;
created_at: string;
reviewed_at?: string | null;
}
interface UsageReport {
total: number;
by_user: { username: string; count: number }[];
by_agent: { agent: string; count: number }[];
by_day: { date: string; count: number }[];
}
interface FeedbackReport {
total: number;
avg_score: number;
distribution: { score: number; count: number }[];
}
interface WecomBindingRow {
id: number;
username: string;
real_name?: string;
email: string;
role: string;
status: string;
wecom_userid?: string | null;
wecom_unionid?: string | null;
bound: boolean;
}
interface LoginAuditRow {
id: number;
user_id?: number | null;
username?: string | null;
source: string;
status: string;
reason?: string | null;
wecom_userid?: string | null;
ip?: string | null;
user_agent?: string | null;
created_at?: string | null;
}
// 获取路由实例,用于页面跳转
const router = useRouter();
// 当前左侧菜单激活的模块:dashboard / agents / permissions
const activeModule = ref<'dashboard' | 'agents' | 'announcements' | 'permissions' | 'requests' | 'reports' | 'approvals' | 'users' | 'departments' | 'questions' | 'wecom'>('dashboard');
const expandedReports = ref(true);
// agents:管理员视角下的所有 Agent 列表
const agents = ref<AgentRow[]>([]);
// users:系统中的用户列表及其权限
const users = ref<UserRow[]>([]);
// isSaving:标记保存操作是否进行中
const isSaving = ref(false);
const isLoading = ref(true);
const showUserModal = ref(false);
const newAgent = ref<Partial<AgentRow>>({
name: '',
dify_app_id: '',
dify_api_key: '',
description: '',
type: 'api',
api_base_url: '',
iframe_url: '',
is_active: true
});
const editingUser = ref<{
id: number | null;
username: string;
email: string;
department?: string;
role: string;
password?: string;
real_name?: string;
employee_id?: string;
phone_number?: string;
agent_ids: number[];
}>({
id: null,
username: '',
email: '',
department: '',
role: 'user',
password: '',
real_name: '',
employee_id: '',
phone_number: '',
agent_ids: []
});
const openCreateUserModal = () => {
editingUser.value = {
id: null,
username: '',
email: '',
department: '',
role: 'user',
password: '',
real_name: '',
employee_id: '',
phone_number: '',
agent_ids: []
};
showUserModal.value = true;
};
const openEditUserModal = (user: UserRow) => {
editingUser.value = {
id: user.id,
username: user.username,
email: user.email,
department: user.department || '',
role: user.role,
password: '', // 留空表示不修改
real_name: user.real_name || '',
employee_id: user.employee_id || '',
phone_number: user.phone_number || '',
agent_ids: user.agent_ids || []
};
showUserModal.value = true;
};
const saveUser = async () => {
if (!editingUser.value.username) {
alert(t('admin.user.msgs.usernameRequired'));
return;
}
if (!editingUser.value.id && !editingUser.value.password) {
alert(t('admin.user.msgs.passwordRequired'));
return;
}
isSaving.value = true;
try {
if (editingUser.value.id) {
// Update
await fetch(`/api/admin/users/${editingUser.value.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
email: editingUser.value.email,
department: editingUser.value.department,
role: editingUser.value.role,
password: editingUser.value.password || undefined,
real_name: editingUser.value.real_name,
employee_id: editingUser.value.employee_id,
phone_number: editingUser.value.phone_number,
agent_ids: editingUser.value.agent_ids
})
});
} else {
// Create
const res = await fetch('/api/admin/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
username: editingUser.value.username,
email: editingUser.value.email,
department: editingUser.value.department,
role: editingUser.value.role,
password: editingUser.value.password,
real_name: editingUser.value.real_name,
employee_id: editingUser.value.employee_id,
phone_number: editingUser.value.phone_number,
agent_ids: editingUser.value.agent_ids
})
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || t('admin.msg.failed'));
}
}
await loadUsers();
showUserModal.value = false;
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
}
};
const permissionRequests = ref<PermissionRequestRow[]>([]);
const usageReport = ref<UsageReport | null>(null);
const feedbackReport = ref<FeedbackReport | null>(null);
const wecomBindings = ref<WecomBindingRow[]>([]);
const wecomLoginAudits = ref<LoginAuditRow[]>([]);
const wecomBindForm = ref({
user_id: '' as string | number,
wecom_userid: '',
wecom_unionid: '',
});
const wecomBoundOnly = ref(false);
const wecomAuditSourceFilter = ref<'all' | 'wecom' | 'password'>('all');
const wecomAuditStatusFilter = ref<'all' | 'success' | 'failed'>('all');
const filteredWecomLoginAudits = computed(() => wecomLoginAudits.value);
// Batch Operation Refs
const selectedUserIds = ref<number[]>([]);
const showBatchEditModal = ref(false);
const showBatchPermissionModal = ref(false);
const batchEditForm = ref({
department: '',
role: '',
status: '',
});
const batchPermissionForm = ref({
agent_ids: [] as number[],
action: 'add' as 'add' | 'remove' | 'set'
});
// Department Management
interface Department {
id: number;
name: string;
code?: string;
company?: string;
description?: string;
}
const departments = ref<Department[]>([]);
const editingDept = ref<Partial<Department>>({});
const isManagingDepts = ref(false);
const loadDepartments = async () => {
try {
const res = await fetch('/api/admin/departments', { headers: getAuthHeaders() });
if (res.ok) departments.value = await res.json();
} catch (e) {
console.error('Failed to load departments', e);
}
};
const saveDepartment = async () => {
if (!editingDept.value.name) return alert(t('admin.dept.msg.nameRequired'));
try {
if (editingDept.value.id) {
const res = await fetch(`/api/admin/departments/${editingDept.value.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(editingDept.value)
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || t('admin.msg.failed'));
}
} else {
const res = await fetch('/api/admin/departments', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(editingDept.value)
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || t('admin.msg.failed'));
}
}
await loadDepartments();
editingDept.value = {};
} catch (e: any) {
alert(e.message);
}
};
const editDepartment = (dept: Department) => {
editingDept.value = { ...dept };
};
// Sidebar Toggle
const isSidebarCollapsed = ref(false);
const toggleSidebar = () => {
isSidebarCollapsed.value = !isSidebarCollapsed.value;
};
// Report Tabs
interface ReportTab {
id: string;
label: string;
type: string; // 'table' or 'chart'
table?: string;
filter?: Record<string, string>;
}
const reportTabs = ref<ReportTab[]>([]);
const activeReportTabId = ref<string | null>(null);
const openReportTab = (table: string) => {
const existingTab = reportTabs.value.find(t => t.table === table);
if (existingTab) {
activeReportTabId.value = existingTab.id;
} else {
const newTab: ReportTab = {
id: Date.now().toString(),
label: table.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
type: 'table',
table: table,
filter: {}
};
reportTabs.value.push(newTab);
activeReportTabId.value = newTab.id;
}
activeModule.value = 'reports';
currentTable.value = table;
};
watch(activeReportTabId, (newId) => {
if (newId) {
const tab = reportTabs.value.find(t => t.id === newId);
if (tab && tab.table) {
currentTable.value = tab.table;
columnFilters.value = tab.filter || {};
}
}
});
const deleteDepartment = async (id: number) => {
if (!confirm(t('admin.dept.confirmDelete'))) return;
try {
await fetch(`/api/admin/departments/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
await loadDepartments();
} catch (e) {
console.error(e);
}
};
// User Filters & Actions
const userFilters = ref({
username: '',
email: '',
department: '',
role: '',
status: '',
real_name: '',
employee_id: '',
phone_number: ''
});
const hideRejected = ref(true);
const filteredUsers = computed(() => {
return users.value.filter(u => {
if (hideRejected.value && u.status === 'rejected') return false;
for (const key of Object.keys(userFilters.value)) {
const k = key as keyof typeof userFilters.value;
const filterVal = userFilters.value[k].toLowerCase();
if (!filterVal) continue;
const userVal = u[k]?.toString().toLowerCase() || '';
if (!userVal.includes(filterVal)) return false;
}
return true;
});
});
const cleanRejectedUsers = async () => {
if (!confirm(t('admin.user.confirmClean'))) return;
try {
const res = await fetch('/api/admin/users/cleanup-rejected', {
method: 'POST',
headers: getAuthHeaders()
});
const data = await res.json();
if (res.ok) {
alert(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
loadUsers();
} else {
alert(data.error);
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
}
};
const batchDeleteUsers = async () => {
if (selectedUserIds.value.length === 0) return;
if (!confirm(t('admin.user.confirmBatchDelete', { count: selectedUserIds.value.length }))) return;
try {
const res = await fetch('/api/admin/users/batch-delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ user_ids: selectedUserIds.value })
});
const data = await res.json();
if (res.ok) {
alert(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
selectedUserIds.value = [];
loadUsers();
} else {
alert(data.error);
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
}
};
const toggleUserSelection = (userId: number) => {
const index = selectedUserIds.value.indexOf(userId);
if (index === -1) {
selectedUserIds.value.push(userId);
} else {
selectedUserIds.value.splice(index, 1);
}
};
const toggleAllUsers = (filteredUsers: UserRow[]) => {
if (selectedUserIds.value.length === filteredUsers.length) {
selectedUserIds.value = [];
} else {
selectedUserIds.value = filteredUsers.map(u => u.id);
}
};
const openBatchEditModal = () => {
if (selectedUserIds.value.length === 0) return;
batchEditForm.value = { department: '', role: '', status: '' };
showBatchEditModal.value = true;
};
const openBatchPermissionModal = () => {
if (selectedUserIds.value.length === 0) return;
batchPermissionForm.value = { agent_ids: [], action: 'add' };
showBatchPermissionModal.value = true;
};
const submitBatchEdit = async () => {
isSaving.value = true;
try {
const data: any = {};
if (batchEditForm.value.department) data.department = batchEditForm.value.department;
if (batchEditForm.value.role) data.role = batchEditForm.value.role;
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
if (Object.keys(data).length === 0) {
alert(t('admin.msg.enterOneField'));
return;
}
const res = await fetch('/api/admin/users/batch', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
user_ids: selectedUserIds.value,
data: data
})
});
if (!res.ok) throw new Error(t('admin.msg.batchUpdateFailed'));
await loadUsers();
showBatchEditModal.value = false;
selectedUserIds.value = [];
} catch (e: any) {
console.error(e);
alert(t('admin.msg.batchUpdateFailed'));
} finally {
isSaving.value = false;
}
};
const submitBatchPermission = async () => {
if (batchPermissionForm.value.agent_ids.length === 0) {
alert(t('admin.perm.msg.selectAgent'));
return;
}
isSaving.value = true;
try {
const res = await fetch('/api/admin/permissions/batch', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
user_ids: selectedUserIds.value,
agent_ids: batchPermissionForm.value.agent_ids,
action: batchPermissionForm.value.action
})
});
if (!res.ok) throw new Error(t('admin.msg.batchPermissionUpdateFailed'));
await loadUsers();
showBatchPermissionModal.value = false;
selectedUserIds.value = [];
} catch (e: any) {
console.error(e);
alert(t('admin.msg.batchPermissionUpdateFailed'));
} finally {
isSaving.value = false;
}
};
const getAuthHeaders = () => {
let stored = localStorage.getItem('hxops_user');
if (!stored) stored = sessionStorage.getItem('hxops_user');
if (!stored) return {};
try {
const data = JSON.parse(stored);
const user = data.user || data; // Handle both wrapped and unwrapped format
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
} catch (e) {
return {};
}
};
/**
* 加载 Agent 列表
* 核心逻辑:调用 GET /api/admin/agents
*/
const loadAgents = async () => {
try {
const res = await fetch('/api/admin/agents', { headers: getAuthHeaders() });
if (res.ok) {
agents.value = await res.json();
} else {
console.error('Failed to load agents:', res.statusText);
agents.value = [];
}
} catch (e) {
console.error('Error loading agents:', e);
agents.value = [];
}
};
/**
* 加载用户与权限列表
* 核心逻辑:调用 GET /api/admin/users
*/
const loadUsers = async () => {
try {
const res = await fetch('/api/admin/users', { headers: getAuthHeaders() });
if (res.ok) {
users.value = await res.json();
} else {
console.error('Failed to load users:', res.statusText);
}
} catch (e) {
console.error('Error loading users:', e);
}
};
const loadPermissionRequests = async () => {
try {
const res = await fetch('/api/admin/permission-requests', { headers: getAuthHeaders() });
if (res.ok) {
permissionRequests.value = await res.json();
}
} catch (e) {
console.error('Error loading permission requests:', e);
}
};
const approvePermissionRequest = async (id: number) => {
await fetch(`/api/admin/permission-requests/${id}/approve`, {
method: 'POST',
headers: getAuthHeaders(),
});
await loadPermissionRequests();
await loadUsers();
};
const rejectPermissionRequest = async (id: number) => {
await fetch(`/api/admin/permission-requests/${id}/reject`, {
method: 'POST',
headers: getAuthHeaders(),
});
await loadPermissionRequests();
};
const loadReports = async () => {
try {
const usageRes = await fetch('/api/admin/reports/usage', { headers: getAuthHeaders() });
if (usageRes.ok) {
usageReport.value = await usageRes.json();
}
const feedbackRes = await fetch('/api/admin/reports/feedback', { headers: getAuthHeaders() });
if (feedbackRes.ok) {
feedbackReport.value = await feedbackRes.json();
}
} catch (e) {
console.error('Error loading reports:', e);
}
};
const loadWecomBindings = async () => {
try {
const boundOnly = wecomBoundOnly.value ? 'true' : 'false';
const res = await fetch(`/api/admin/wecom/bindings?bound_only=${boundOnly}`, { headers: getAuthHeaders() });
if (res.ok) {
wecomBindings.value = await res.json();
}
} catch (e) {
console.error('Error loading WeCom bindings:', e);
}
};
const loadWecomAudits = async () => {
try {
const params = new URLSearchParams({ limit: '200' });
if (wecomAuditSourceFilter.value !== 'all') {
params.set('source', wecomAuditSourceFilter.value);
}
if (wecomAuditStatusFilter.value !== 'all') {
params.set('status', wecomAuditStatusFilter.value);
}
const res = await fetch(`/api/admin/wecom/login-audits?${params.toString()}`, { headers: getAuthHeaders() });
if (res.ok) {
wecomLoginAudits.value = await res.json();
}
} catch (e) {
console.error('Error loading WeCom login audits:', e);
}
};
const refreshWecomData = async () => {
await Promise.all([loadWecomBindings(), loadWecomAudits()]);
};
const bindWecomUser = async () => {
if (!wecomBindForm.value.user_id || !wecomBindForm.value.wecom_userid.trim()) {
alert(t('admin.wecom.msg.bindInputRequired'));
return;
}
isSaving.value = true;
try {
const res = await fetch('/api/admin/wecom/bind', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
user_id: Number(wecomBindForm.value.user_id),
wecom_userid: wecomBindForm.value.wecom_userid.trim(),
wecom_unionid: wecomBindForm.value.wecom_unionid.trim() || undefined,
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || t('admin.wecom.msg.bindFailed'));
wecomBindForm.value.wecom_userid = '';
wecomBindForm.value.wecom_unionid = '';
await refreshWecomData();
alert(t('admin.wecom.msg.bindSuccess'));
} catch (e: any) {
console.error(e);
const errorMessage = e?.message || t('admin.wecom.msg.bindFailed');
if (String(errorMessage).includes('already bound to user')) {
alert(t('admin.wecom.msg.boundConflict', { detail: errorMessage }));
} else {
alert(errorMessage);
}
} finally {
isSaving.value = false;
}
};
const unbindWecomUserByAdmin = async (userId: number) => {
if (!confirm(t('admin.wecom.confirmUnbind'))) return;
isSaving.value = true;
try {
const res = await fetch('/api/admin/wecom/unbind', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ user_id: userId }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || t('admin.wecom.msg.unbindFailed'));
await refreshWecomData();
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.wecom.msg.unbindFailed'));
} finally {
isSaving.value = false;
}
};
const exportWecomAudits = () => {
if (filteredWecomLoginAudits.value.length === 0) {
alert(t('admin.wecom.noAuditData'));
return;
}
const rows = filteredWecomLoginAudits.value.map((row) => ({
Time: row.created_at || '',
Source: row.source || '',
Username: row.username || '',
Status: row.status || '',
Reason: row.reason || '',
IP: row.ip || '',
WecomUserId: row.wecom_userid || '',
UserAgent: row.user_agent || '',
}));
const ws = XLSX.utils.json_to_sheet(rows);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'wecom_login_audits');
XLSX.writeFile(wb, `wecom_login_audits_${new Date().toISOString().split('T')[0]}.xlsx`);
};
// Quick Questions Logic
interface QuickQuestion {
id: number;
title: string;
question: string;
agent_id: number;
agent_name?: string;
sort_order: number;
}
const quickQuestions = ref<QuickQuestion[]>([]);
const newQuestion = ref<Partial<QuickQuestion>>({
title: '',
question: '',
agent_id: undefined,
sort_order: 0
});
const isEditingQuestion = ref(false);
interface AnnouncementItem {
id: number;
title: string;
content: string;
created_at: string;
}
const adminAnnouncements = ref<AnnouncementItem[]>([]);
const newAnnouncement = ref({ title: '', content: '' });
const loadAnnouncementsAdmin = async () => {
try {
const res = await fetch('/api/user/announcements', { headers: getAuthHeaders() });
if (res.ok) {
adminAnnouncements.value = await res.json();
} else {
adminAnnouncements.value = [];
}
} catch (e) {
console.error('Failed to load announcements', e);
adminAnnouncements.value = [];
}
};
const createAnnouncementAdmin = async () => {
if (!newAnnouncement.value.title.trim() || !newAnnouncement.value.content.trim()) {
alert(t('admin.announcement.msg.fillAll'));
return;
}
isSaving.value = true;
try {
const res = await fetch('/api/user/announcements', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
title: newAnnouncement.value.title.trim(),
content: newAnnouncement.value.content.trim()
})
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || t('admin.msg.failed'));
}
newAnnouncement.value = { title: '', content: '' };
await loadAnnouncementsAdmin();
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const deleteAnnouncementAdmin = async (id: number) => {
if (!confirm(t('admin.announcement.confirmDelete'))) return;
try {
const res = await fetch(`/api/user/announcements/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || t('admin.msg.failed'));
}
await loadAnnouncementsAdmin();
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.requestFailed'));
}
};
const loadQuickQuestions = async () => {
try {
const res = await fetch('/api/admin/quick-questions', { headers: getAuthHeaders() });
if (res.ok) quickQuestions.value = await res.json();
} catch (e) {
console.error('Failed to load quick questions', e);
}
};
const saveQuestion = async () => {
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
alert(t('admin.question.msg.fillAll'));
return;
}
isSaving.value = true;
try {
const url = isEditingQuestion.value
? `/api/admin/quick-questions/${newQuestion.value.id}`
: '/api/admin/quick-questions';
const method = isEditingQuestion.value ? 'PUT' : 'POST';
const res = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(newQuestion.value)
});
if (res.ok) {
await loadQuickQuestions();
resetQuestionForm();
} else {
alert(t('admin.msg.failed'));
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const editQuestion = (q: QuickQuestion) => {
newQuestion.value = { ...q };
isEditingQuestion.value = true;
};
const deleteQuestion = async (id: number) => {
if (!confirm(t('admin.question.confirmDelete'))) return;
try {
await fetch(`/api/admin/quick-questions/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
await loadQuickQuestions();
} catch (e) {
console.error(e);
}
};
const resetQuestionForm = () => {
newQuestion.value = { title: '', question: '', agent_id: undefined, sort_order: 0 };
isEditingQuestion.value = false;
};
// 组件挂载时加载初始数据
onMounted(async () => {
const headers = getAuthHeaders();
if (!headers['X-User-Id'] && !headers['X-Username']) {
console.warn('No auth headers found, redirecting to login');
router.push('/');
return;
}
isLoading.value = true;
await Promise.all([
loadAgents(),
loadUsers(),
loadReports(),
loadPermissionRequests(),
loadDepartments(),
loadAnnouncementsAdmin(),
loadQuickQuestions(),
loadWecomBindings(),
loadWecomAudits()
]);
isLoading.value = false;
});
watch(activeModule, async (value) => {
if (value === 'requests') {
await loadPermissionRequests();
}
if (value === 'questions') {
await loadQuickQuestions();
}
if (value === 'announcements') {
await loadAnnouncementsAdmin();
}
if (value === 'reports' || value === 'dashboard') {
await loadReports();
}
if (value === 'departments') {
await loadDepartments();
}
if (value === 'wecom') {
await refreshWecomData();
}
});
/**
* saveConfig
* 用途:目前仅作为“保存成功”提示,核心配置变更在具体操作时已写入后台
*/
const saveConfig = () => {
alert(t('admin.msg.allSaved'));
};
const pendingUsers = computed(() => users.value.filter(u => u.status === 'pending'));
const activeUsers = computed(() => users.value.filter(u => u.status !== 'pending'));
const permissionFilters = ref({
username: '',
department: '',
role: ''
});
const filteredPermissionUsers = computed(() => {
return activeUsers.value.filter(u => {
const matchName = !permissionFilters.value.username ||
u.username.toLowerCase().includes(permissionFilters.value.username.toLowerCase()) ||
(u.real_name && u.real_name.toLowerCase().includes(permissionFilters.value.username.toLowerCase()));
const matchDept = !permissionFilters.value.department ||
(u.department && u.department.toLowerCase().includes(permissionFilters.value.department.toLowerCase()));
const matchRole = !permissionFilters.value.role || u.role === permissionFilters.value.role;
return matchName && matchDept && matchRole;
});
});
const isEditingAgent = ref(false);
const selectedAgentId = ref<number | null>(null);
const showAgentTestModal = ref(false);
const isTestingAgent = ref(false);
const testingAgent = ref<AgentRow | null>(null);
const agentTestResult = ref<AgentTestResult | null>(null);
const selectAgent = (agent: AgentRow) => {
selectedAgentId.value = agent.id;
// Deep clone and ensure all fields are present
newAgent.value = {
...agent,
// Show existing API key while editing selected row.
dify_api_key: agent.dify_api_key || '',
iframe_url: agent.extra_config?.iframe_url || ''
};
isEditingAgent.value = true;
};
const resetAgentForm = () => {
selectedAgentId.value = null;
newAgent.value = {
name: '',
dify_app_id: '',
dify_api_key: '',
description: '',
type: 'api',
api_base_url: '',
iframe_url: '',
is_active: true
} as any;
isEditingAgent.value = false;
};
const openAgentTestModal = (agent: AgentRow) => {
testingAgent.value = agent;
agentTestResult.value = null;
showAgentTestModal.value = true;
runAgentTest(agent);
};
const runAgentTest = async (agent?: AgentRow) => {
const target = agent || testingAgent.value;
if (!target) return;
isTestingAgent.value = true;
try {
const res = await fetch(`/api/admin/agents/${target.id}/test`, {
method: 'POST',
headers: getAuthHeaders()
});
const data = await res.json().catch(() => ({}));
agentTestResult.value = {
success: !!data.success,
request_url: data.request_url || '',
output_info: data.output_info || '',
analysis: data.analysis || (res.ok ? '测试已完成。' : '测试失败。'),
http_status: data.http_status,
tested_at: data.tested_at
};
if (data.success) {
const idx = agents.value.findIndex(a => a.id === target.id);
if (idx >= 0) {
const updatedAgent = agents.value[idx];
if (updatedAgent) {
updatedAgent.is_active = true;
}
}
if (selectedAgentId.value === target.id) {
newAgent.value.is_active = true;
}
}
} catch (e: any) {
agentTestResult.value = {
success: false,
request_url: '',
output_info: e?.message || 'Network error',
analysis: '测试失败:请求过程出现异常。',
http_status: 0
};
} finally {
isTestingAgent.value = false;
}
};
/**
* createAgent
* 用途:使用表单一次性填写所有字段并创建 Agent
* 实现方式:调 POST /api/admin/agents
*/
const createAgent = async () => {
if (!newAgent.value.name) {
alert(t('admin.dept.msg.nameRequired'));
return;
}
isSaving.value = true;
const extra_config = newAgent.value.iframe_url ? { iframe_url: newAgent.value.iframe_url } : {};
let res;
try {
const editingId = isEditingAgent.value ? Number(newAgent.value.id) : null;
if (isEditingAgent.value) {
// Update
const payload: any = {
name: newAgent.value.name,
dify_app_id: newAgent.value.dify_app_id,
description: newAgent.value.description,
type: newAgent.value.type,
api_base_url: newAgent.value.api_base_url,
extra_config: extra_config,
is_active: newAgent.value.is_active
};
// Only include API key if it's not empty (user updated it)
if (newAgent.value.dify_api_key) {
payload.dify_api_key = newAgent.value.dify_api_key;
}
res = await fetch(`/api/admin/agents/${newAgent.value.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(payload),
});
} else {
// Create
res = await fetch('/api/admin/agents', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
name: newAgent.value.name,
dify_app_id: newAgent.value.dify_app_id,
dify_api_key: newAgent.value.dify_api_key,
description: newAgent.value.description,
type: newAgent.value.type,
api_base_url: newAgent.value.api_base_url,
extra_config: extra_config
}),
});
}
if (res.ok) {
await loadAgents();
// Keep current row selected after update; only reset after create.
if (editingId) {
const updated = agents.value.find(a => a.id === editingId);
if (updated) {
selectAgent(updated);
}
} else {
resetAgentForm();
}
} else {
const text = await res.text();
try {
const err = JSON.parse(text);
alert(err.error || t('admin.msg.failed'));
} catch {
alert(`${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
}
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const approveUser = async (userId: number) => {
if (!confirm(t('admin.approval.confirmApprove'))) return;
const res = await fetch(`/api/admin/users/${userId}/approve`, {
method: 'POST',
headers: getAuthHeaders()
});
if (res.ok) {
await loadUsers();
} else {
alert(t('admin.msg.failed'));
}
};
const rejectUser = async (userId: number) => {
if (!confirm(t('admin.approval.confirmReject'))) return;
try {
const res = await fetch(`/api/admin/users/${userId}/reject`, {
method: 'POST',
headers: getAuthHeaders()
});
if (res.ok) {
await loadUsers();
} else {
const text = await res.text();
try {
const err = JSON.parse(text);
alert(err.error || t('admin.msg.failed'));
} catch {
alert(`${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
}
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
}
};
// 报表相关状态
const currentTable = ref('users');
const tableData = ref<any[]>([]);
const isFullScreen = ref(false);
const columnFilters = ref<Record<string, string>>({});
const selectedReportRowIds = ref<number[]>([]);
const isDeletingChatLogs = ref(false);
const chatLogsTotal = ref(0);
const showChatLogsColumnPanel = ref(false);
const chatLogsWrapEnabled = ref(false);
const chatLogsWrapMaxHeight = ref(120);
const showChatLogsSelection = ref(false);
const reportCurrentPage = ref(1);
const reportPageSize = ref(20);
const reportPageSizeOptions = [10, 20, 50, 100];
interface ReportColumnConfig {
key: string;
visible: boolean;
width: number;
}
interface ChatLogsLayoutPref {
columns: ReportColumnConfig[];
wrapEnabled: boolean;
wrapMaxHeight: number;
sortRules?: SortRule[];
}
type SortDirection = 'asc' | 'desc';
interface SortRule {
key: string;
direction: SortDirection;
}
const chatLogsColumns = ref<ReportColumnConfig[]>([]);
const chatLogsSortRules = ref<SortRule[]>([]);
const reportHeaderSort = ref<SortRule | null>(null);
const draggingColumnKey = ref<string | null>(null);
const resizingColumnKey = ref<string | null>(null);
let resizeStartX = 0;
let resizeStartWidth = 0;
const loadTableData = async () => {
// Construct query params from columnFilters
const params = new URLSearchParams();
for (const [key, value] of Object.entries(columnFilters.value)) {
if (value) params.append(key, value);
}
const res = await fetch(`/api/admin/database/${currentTable.value}?${params.toString()}`, {
headers: getAuthHeaders()
});
if (res.ok) {
tableData.value = await res.json();
if (tableData.value.length > 0) {
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
}
// Keep selection valid after reload/filter.
if (currentTable.value === 'chat_logs') {
const validIds = new Set(
tableData.value
.map((row: any) => Number(row?.id))
.filter((id: number) => Number.isFinite(id))
);
selectedReportRowIds.value = selectedReportRowIds.value.filter(id => validIds.has(id));
} else {
selectedReportRowIds.value = [];
}
} else {
tableData.value = [];
selectedReportRowIds.value = [];
}
};
const saveChatLogsColumns = () => {
if (chatLogsColumns.value.length === 0) return;
const payload: ChatLogsLayoutPref = {
columns: chatLogsColumns.value,
wrapEnabled: chatLogsWrapEnabled.value,
wrapMaxHeight: chatLogsWrapMaxHeight.value,
sortRules: chatLogsSortRules.value,
};
saveReportLayoutPref(currentTable.value, payload);
};
const initChatLogsColumns = (keys: string[]) => {
chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120;
const defaults: ReportColumnConfig[] = keys.map((k) => ({
key: k,
visible: true,
width: k === 'id' ? 90 : 180
}));
let merged = defaults;
try {
const parsed = loadReportLayoutPref<ReportColumnConfig[] | ChatLogsLayoutPref>(currentTable.value);
if (parsed) {
const saved = Array.isArray(parsed) ? parsed : (parsed.columns || []);
const savedMap = new Map(saved.map((c) => [c.key, c]));
const order = saved.map((c) => c.key).filter((k) => keys.includes(k));
const missing = keys.filter((k) => !order.includes(k));
merged = [...order, ...missing].map((k) => ({
key: k,
visible: savedMap.get(k)?.visible ?? true,
width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : 180),
}));
if (!Array.isArray(parsed)) {
chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
chatLogsWrapMaxHeight.value = Number(parsed.wrapMaxHeight || 120);
chatLogsSortRules.value = Array.isArray(parsed.sortRules)
? parsed.sortRules
.filter((r: any) => r && typeof r.key === 'string' && (r.direction === 'asc' || r.direction === 'desc'))
: [];
}
}
} catch {
merged = defaults;
}
if (!Number.isFinite(chatLogsWrapMaxHeight.value)) chatLogsWrapMaxHeight.value = 120;
chatLogsColumns.value = merged;
};
const resetChatLogsColumns = () => {
if (tableData.value.length === 0) return;
chatLogsWrapEnabled.value = false;
chatLogsWrapMaxHeight.value = 120;
chatLogsSortRules.value = [];
reportHeaderSort.value = null;
initChatLogsColumns(Object.keys(tableData.value[0] || {}));
saveChatLogsColumns();
};
const moveChatLogsColumn = (key: string, direction: -1 | 1) => {
const idx = chatLogsColumns.value.findIndex((c) => c.key === key);
if (idx < 0) return;
const target = idx + direction;
if (target < 0 || target >= chatLogsColumns.value.length) return;
const copy = [...chatLogsColumns.value];
const [item] = copy.splice(idx, 1);
if (!item) return;
copy.splice(target, 0, item);
chatLogsColumns.value = copy;
saveChatLogsColumns();
};
const onColumnDragStart = (key: string) => {
draggingColumnKey.value = key;
};
const onColumnDrop = (targetKey: string) => {
const sourceKey = draggingColumnKey.value;
draggingColumnKey.value = null;
if (!sourceKey || sourceKey === targetKey) return;
const sourceIdx = chatLogsColumns.value.findIndex((c) => c.key === sourceKey);
const targetIdx = chatLogsColumns.value.findIndex((c) => c.key === targetKey);
if (sourceIdx < 0 || targetIdx < 0) return;
const copy = [...chatLogsColumns.value];
const [item] = copy.splice(sourceIdx, 1);
if (!item) return;
copy.splice(targetIdx, 0, item);
chatLogsColumns.value = copy;
saveChatLogsColumns();
};
const onResizeMouseMove = (e: MouseEvent) => {
if (!resizingColumnKey.value) return;
const diff = e.clientX - resizeStartX;
const col = chatLogsColumns.value.find((c) => c.key === resizingColumnKey.value);
if (!col) return;
col.width = Math.max(80, resizeStartWidth + diff);
};
const onResizeMouseUp = () => {
if (!resizingColumnKey.value) return;
resizingColumnKey.value = null;
document.removeEventListener('mousemove', onResizeMouseMove);
document.removeEventListener('mouseup', onResizeMouseUp);
saveChatLogsColumns();
};
const startResizeColumn = (key: string, e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
const col = chatLogsColumns.value.find((c) => c.key === key);
if (!col) return;
resizingColumnKey.value = key;
resizeStartX = e.clientX;
resizeStartWidth = col.width;
document.addEventListener('mousemove', onResizeMouseMove);
document.addEventListener('mouseup', onResizeMouseUp);
};
const loadTableCount = async (table: string) => {
try {
const res = await fetch(`/api/admin/database/${table}/count`, {
headers: getAuthHeaders()
});
if (!res.ok) return 0;
const data = await res.json();
return Number(data.total || 0);
} catch {
return 0;
}
};
const exportToExcel = () => {
if (tableData.value.length === 0) return;
const ws = XLSX.utils.json_to_sheet(tableData.value);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, currentTable.value);
XLSX.writeFile(wb, `${currentTable.value}_report_${new Date().toISOString().split('T')[0]}.xlsx`);
};
// Debounce filter input
let debounceTimer: any = null;
const handleFilterChange = () => {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
loadTableData();
}, 500);
};
const isChatLogsTable = computed(() => currentTable.value === 'chat_logs');
const visibleReportKeys = computed(() => {
if (chatLogsColumns.value.length === 0) return Object.keys(tableData.value[0] || {});
return chatLogsColumns.value.filter((c) => c.visible).map((c) => c.key);
});
const getReportRowId = (row: any) => Number(row?.id);
const allReportRowsSelected = computed(() => {
if (!isChatLogsTable.value || paginatedSortedTableData.value.length === 0) return false;
return paginatedSortedTableData.value.every((row: any) => selectedReportRowIds.value.includes(getReportRowId(row)));
});
const getColumnWidthStyle = (key: string) => {
const col = chatLogsColumns.value.find((c) => c.key === key);
if (!col) return {};
return {
width: `${col.width}px`,
minWidth: `${col.width}px`,
maxWidth: `${col.width}px`,
};
};
const getReportCellValue = (row: any, key: string) => row?.[key];
const normalizeSortValue = (v: any) => {
if (v === null || v === undefined) return null;
if (typeof v === 'number') return v;
if (typeof v === 'boolean') return v ? 1 : 0;
if (typeof v === 'string') {
const n = Number(v);
if (!Number.isNaN(n) && v.trim() !== '') return n;
const d = Date.parse(v);
if (!Number.isNaN(d)) return d;
return v.toLowerCase();
}
return String(v).toLowerCase();
};
const compareByRule = (a: any, b: any, rule: SortRule) => {
const av = normalizeSortValue(getReportCellValue(a, rule.key));
const bv = normalizeSortValue(getReportCellValue(b, rule.key));
if (av === bv) return 0;
if (av === null) return 1;
if (bv === null) return -1;
const dir = rule.direction === 'asc' ? 1 : -1;
return av > bv ? dir : -dir;
};
const sortedTableData = computed(() => {
const list = [...tableData.value];
const advanced = chatLogsSortRules.value.length > 0 ? chatLogsSortRules.value : [];
const rules = advanced.length > 0 ? advanced : (reportHeaderSort.value ? [reportHeaderSort.value] : []);
if (rules.length === 0) return list;
return list.sort((a, b) => {
for (const r of rules) {
const c = compareByRule(a, b, r);
if (c !== 0) return c;
}
return 0;
});
});
// Front-end pagination over the already filtered/sorted dataset.
const reportTotalRows = computed(() => sortedTableData.value.length);
const reportTotalPages = computed(() => {
const size = Math.max(1, Number(reportPageSize.value) || 20);
return Math.max(1, Math.ceil(reportTotalRows.value / size));
});
const paginatedSortedTableData = computed(() => {
const size = Math.max(1, Number(reportPageSize.value) || 20);
// Clamp page number to avoid empty pages after filtering/deletion.
const safePage = Math.min(Math.max(1, reportCurrentPage.value), reportTotalPages.value);
const start = (safePage - 1) * size;
return sortedTableData.value.slice(start, start + size);
});
const reportRangeStart = computed(() => {
if (reportTotalRows.value === 0) return 0;
const safePage = Math.min(Math.max(1, reportCurrentPage.value), reportTotalPages.value);
const size = Math.max(1, Number(reportPageSize.value) || 20);
return (safePage - 1) * size + 1;
});
const reportRangeEnd = computed(() => {
if (reportTotalRows.value === 0) return 0;
const size = Math.max(1, Number(reportPageSize.value) || 20);
return Math.min(reportRangeStart.value + size - 1, reportTotalRows.value);
});
const goToReportPage = (page: number) => {
reportCurrentPage.value = Math.min(Math.max(1, page), reportTotalPages.value);
};
const prevReportPage = () => goToReportPage(reportCurrentPage.value - 1);
const nextReportPage = () => goToReportPage(reportCurrentPage.value + 1);
const reportPageButtons = computed(() => {
const total = reportTotalPages.value;
const current = Math.min(Math.max(1, reportCurrentPage.value), total);
if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
if (current <= 4) return [1, 2, 3, 4, 5, -1, total];
if (current >= total - 3) return [1, -1, total - 4, total - 3, total - 2, total - 1, total];
return [1, -1, current - 1, current, current + 1, -1, total];
});
const onReportHeaderClick = (key: string) => {
// Column-header sorting is the quick mode; clear advanced rules to avoid precedence conflict.
if (chatLogsSortRules.value.length > 0) {
chatLogsSortRules.value = [];
}
if (reportHeaderSort.value?.key === key) {
reportHeaderSort.value = { key, direction: reportHeaderSort.value.direction === 'asc' ? 'desc' : 'asc' };
} else {
reportHeaderSort.value = { key, direction: 'asc' };
}
reportCurrentPage.value = 1;
};
const getHeaderSortMark = (key: string) => {
if (reportHeaderSort.value?.key !== key) return '';
return reportHeaderSort.value.direction === 'asc' ? '▲' : '▼';
};
const addChatLogsSortRule = () => {
const keys = visibleReportKeys.value;
const fallback = Object.keys(tableData.value[0] || {});
const key = keys[0] || fallback[0];
if (!key) return;
chatLogsSortRules.value.push({ key, direction: 'asc' });
};
const removeChatLogsSortRule = (idx: number) => {
chatLogsSortRules.value.splice(idx, 1);
};
const moveChatLogsSortRule = (idx: number, direction: -1 | 1) => {
const target = idx + direction;
if (target < 0 || target >= chatLogsSortRules.value.length) return;
const copy = [...chatLogsSortRules.value];
const [item] = copy.splice(idx, 1);
if (!item) return;
copy.splice(target, 0, item);
chatLogsSortRules.value = copy;
};
const getReportCellDisplayStyle = (key: string) => {
// Width is applied on <td>; height clamp is applied to inner block container.
return { ...getColumnWidthStyle(key) } as any;
};
const getReportCellInnerStyle = () => {
const style: Record<string, string> = { display: 'block' };
if (!chatLogsWrapEnabled.value) {
style.whiteSpace = 'nowrap';
style.overflow = 'hidden';
style.textOverflow = 'ellipsis';
return style;
}
const maxH = Number.isFinite(chatLogsWrapMaxHeight.value) ? chatLogsWrapMaxHeight.value : 120;
style.whiteSpace = 'normal';
style.wordBreak = 'break-word';
style.maxHeight = `${maxH}px`;
style.overflow = 'hidden';
return style;
};
const toggleReportRowSelection = (rowId: number) => {
const idx = selectedReportRowIds.value.indexOf(rowId);
if (idx === -1) selectedReportRowIds.value.push(rowId);
else selectedReportRowIds.value.splice(idx, 1);
};
const toggleAllReportRows = () => {
if (!isChatLogsTable.value) return;
const ids = paginatedSortedTableData.value
.map((row: any) => getReportRowId(row))
.filter((id: number) => Number.isFinite(id));
const allSelected = ids.length > 0 && ids.every((id: number) => selectedReportRowIds.value.includes(id));
if (allSelected) {
selectedReportRowIds.value = selectedReportRowIds.value.filter((id) => !ids.includes(id));
return;
}
const merged = new Set([...selectedReportRowIds.value, ...ids]);
selectedReportRowIds.value = Array.from(merged);
};
const batchDeleteChatLogs = async () => {
if (!isChatLogsTable.value) return;
if (selectedReportRowIds.value.length === 0) return;
if (!confirm(`Delete ${selectedReportRowIds.value.length} selected chat logs?`)) return;
isDeletingChatLogs.value = true;
try {
const res = await fetch('/api/admin/database/chat_logs/batch-delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ ids: selectedReportRowIds.value })
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data.error || t('admin.msg.failed'));
}
alert(`Deleted ${data.deleted_count ?? 0} chat logs.`);
selectedReportRowIds.value = [];
await loadTableData();
chatLogsTotal.value = await loadTableCount('chat_logs');
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.failed'));
} finally {
isDeletingChatLogs.value = false;
}
};
watch(currentTable, async () => {
if (activeModule.value === 'reports') {
columnFilters.value = {}; // Reset filters on table change
selectedReportRowIds.value = [];
showChatLogsColumnPanel.value = false;
showChatLogsSelection.value = false;
reportCurrentPage.value = 1;
await loadTableData();
reportHeaderSort.value = null;
if (currentTable.value === 'chat_logs') {
chatLogsTotal.value = await loadTableCount('chat_logs');
}
}
});
watch(activeModule, async (value) => {
if (value === 'requests') {
await loadPermissionRequests();
}
if (value === 'reports') {
reportCurrentPage.value = 1;
await loadTableData();
if (currentTable.value === 'chat_logs') {
chatLogsTotal.value = await loadTableCount('chat_logs');
} else {
showChatLogsSelection.value = false;
}
}
});
watch(chatLogsColumns, () => {
saveChatLogsColumns();
}, { deep: true });
watch([chatLogsWrapEnabled, chatLogsWrapMaxHeight], () => {
saveChatLogsColumns();
});
watch(chatLogsSortRules, () => {
// Force row re-evaluation immediately when rule fields/order change.
tableData.value = [...tableData.value];
reportCurrentPage.value = 1;
saveChatLogsColumns();
}, { deep: true });
watch(showChatLogsSelection, (v) => {
if (!v) selectedReportRowIds.value = [];
});
watch(columnFilters, () => {
reportCurrentPage.value = 1;
}, { deep: true });
watch(wecomBoundOnly, async () => {
if (activeModule.value === 'wecom') {
await loadWecomBindings();
}
});
watch([wecomAuditSourceFilter, wecomAuditStatusFilter], async () => {
if (activeModule.value === 'wecom') {
await loadWecomAudits();
}
});
watch([reportPageSize, sortedTableData], () => {
if (reportCurrentPage.value > reportTotalPages.value) {
reportCurrentPage.value = reportTotalPages.value;
}
if (reportCurrentPage.value < 1) {
reportCurrentPage.value = 1;
}
});
/**
* deleteAgent
* 用途:删除指定 Agent
* 实现方式:调 DELETE /api/admin/agents/:id
*/
const deleteAgent = async (id: number) => {
if (!confirm(t('admin.agent.confirmDelete'))) return;
try {
const res = await fetch(`/api/admin/agents/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (res.ok) {
await loadAgents();
if (selectedAgentId.value === id) {
resetAgentForm();
}
} else {
const text = await res.text();
try {
const err = JSON.parse(text);
alert(err.error || t('admin.msg.failed'));
} catch {
alert(`${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
}
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
}
};
const showAgentPermissionModal = ref(false);
const selectedAgentForPermissions = ref<AgentRow | null>(null);
const agentPermissionUserIds = ref<number[]>([]);
const openAgentPermissionModal = (agent: AgentRow) => {
selectedAgentForPermissions.value = agent;
// Find users who have this agent in their agent_ids
agentPermissionUserIds.value = users.value
.filter(u => u.agent_ids.includes(agent.id))
.map(u => u.id);
showAgentPermissionModal.value = true;
};
const saveAgentPermissions = async () => {
if (!selectedAgentForPermissions.value) return;
isSaving.value = true;
try {
const res = await fetch(`/api/admin/agents/${selectedAgentForPermissions.value.id}/permissions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
user_ids: agentPermissionUserIds.value
})
});
if (!res.ok) {
throw new Error('Failed to update permissions');
}
await loadUsers(); // Reload to update local state
showAgentPermissionModal.value = false;
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
}
};
const toggleAgentPermission = (userId: number) => {
const index = agentPermissionUserIds.value.indexOf(userId);
if (index === -1) {
agentPermissionUserIds.value.push(userId);
} else {
agentPermissionUserIds.value.splice(index, 1);
}
};
// Toggle permission from Matrix View
const toggleUserAgentPermission = async (user: UserRow, agentId: number) => {
const hasPermission = user.agent_ids.includes(agentId);
const newAgentIds = hasPermission
? user.agent_ids.filter(id => id !== agentId)
: [...user.agent_ids, agentId];
// Optimistic update
const originalIds = [...user.agent_ids];
user.agent_ids = newAgentIds;
try {
await fetch(`/api/admin/users/${user.id}/permissions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
agent_ids: newAgentIds
})
});
} catch (e) {
console.error(e);
user.agent_ids = originalIds; // Revert on error
alert(t('admin.msg.failed'));
}
};
/**
* editUserPermissions
* 用途:通过输入框编辑用户可访问的 Agent ID 列表
* 实现方式:调 POST /api/admin/users/:id/permissions
*/
/* const editUserPermissions = (user: UserRow) => {
openEditUserModal(user);
}; */
const exportPermissions = () => {
const data = users.value.map(u => ({
Username: u.username,
Email: u.email,
Role: u.role,
Allowed_Agents: u.agent_ids.join('|')
}));
const ws = XLSX.utils.json_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Permissions');
XLSX.writeFile(wb, 'user_permissions.csv');
};
/**
* handlePermissionImport
* 用途:从 Excel 导出的 CSV 文件中批量导入用户权限
* 实现方式:将文件作为 multipart/form-data 上传到 /api/admin/permissions/import
*/
const handlePermissionImport = async (event: Event) => {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
const formData = new FormData();
formData.append('file', file);
isSaving.value = true;
try {
await fetch('/api/admin/permissions/import', {
method: 'POST',
headers: getAuthHeaders(),
body: formData,
});
await loadUsers();
} finally {
isSaving.value = false;
// 清空文件选择,以便可以重复上传同一个文件名
input.value = '';
}
};
</script>
<template>
<div class="min-h-screen bg-gray-50 dark:bg-slate-950 font-sans text-slate-800 dark:text-slate-200 flex flex-col">
<!-- Header -->
<header class="bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-slate-200 dark:border-slate-700 px-6 py-4 flex items-center justify-between sticky top-0 z-30 shadow-sm">
<div class="flex items-center gap-4">
<button
@click="toggleSidebar"
class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-xl transition-colors text-slate-500 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 md:block hidden"
title="Toggle Sidebar"
>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><path d="M9 3v18"/></svg>
</button>
<button
@click="router.push('/workspace')"
class="p-2 hover:bg-slate-100 dark:hover:bg-slate-800 rounded-xl transition-colors text-slate-500 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100"
title="Back to Workspace"
>
<ArrowLeft class="w-6 h-6" />
</button>
<div class="flex flex-col">
<h1 class="text-xl md:text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-brand-600 to-indigo-600 tracking-tight">
{{ t('admin.title') }}
</h1>
<span class="text-xs text-slate-400 dark:text-slate-500 font-medium tracking-wide">{{ t('admin.subtitle') }}</span>
</div>
</div>
<div class="flex items-center gap-4">
<ThemeToggleButton />
<!-- Language Selector -->
<div class="flex items-center gap-2">
<Globe class="w-4 h-4 text-slate-400 dark:text-slate-500" />
<select
v-model="locale"
class="bg-transparent border-none text-sm font-medium text-slate-600 dark:text-slate-300 focus:ring-0 cursor-pointer hover:text-brand-600 transition-colors"
>
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
</div>
<button
@click="saveConfig"
class="hidden md:flex items-center gap-2 px-5 py-2.5 bg-slate-900 dark:bg-slate-700 text-white rounded-xl hover:bg-slate-800 dark:hover:bg-slate-600 transition-all shadow-lg shadow-slate-200 active:scale-95"
>
<Save class="w-4 h-4" />
<span class="font-medium text-sm">{{ t('admin.save') }}</span>
</button>
</div>
</header>
<main class="flex-1 w-full mx-auto px-4 md:px-8 py-6 md:py-8 flex flex-col md:flex-row gap-8 items-start">
<!-- Sidebar Navigation -->
<aside
class="bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-2xl shadow-sm h-fit md:sticky md:top-24 overflow-hidden shrink-0 z-10 transition-all duration-300"
:class="isSidebarCollapsed ? 'w-0 md:w-20' : 'w-full md:w-64'"
>
<nav class="flex md:flex-col p-3 gap-1 overflow-x-auto md:overflow-visible no-scrollbar">
<button
v-for="item in sidebarItems"
:key="item.id"
class="group px-4 py-3 text-left text-sm font-medium rounded-xl transition-all flex items-center gap-3 relative overflow-hidden whitespace-nowrap flex-shrink-0"
:class="activeModule === item.id ? 'bg-brand-50 text-brand-700' : 'text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 hover:text-slate-900 dark:hover:text-slate-100'"
@click="activeModule = item.id as any; activeReportTabId = null"
:title="isSidebarCollapsed ? item.label : ''"
>
<component :is="item.icon" class="w-5 h-5 transition-transform group-hover:scale-110 flex-shrink-0" :class="activeModule === item.id ? 'text-brand-600' : 'text-slate-400 dark:text-slate-500 group-hover:text-slate-600 dark:group-hover:text-slate-300'" />
<span :class="isSidebarCollapsed ? 'md:hidden' : ''">{{ item.label }}</span>
<span v-if="item.badge && !isSidebarCollapsed" class="ml-auto bg-red-500 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-sm">
{{ item.badge }}
</span>
<span v-if="item.badge && isSidebarCollapsed" class="absolute top-2 right-2 w-2 h-2 bg-red-500 rounded-full"></span>
<div v-if="activeModule === item.id" class="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-brand-600 rounded-r-full"></div>
</button>
<!-- Reports Submenu -->
<div v-if="config.admin.modules.reports !== false" class="flex flex-col flex-shrink-0">
<button
@click="expandedReports = !expandedReports"
class="group px-4 py-3 text-left text-sm font-medium rounded-xl transition-all flex items-center justify-between gap-3 relative overflow-hidden whitespace-nowrap text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 hover:text-slate-900 dark:hover:text-slate-100"
:title="isSidebarCollapsed ? t('admin.nav.reports') : ''"
>
<div class="flex items-center gap-3">
<BarChart2 class="w-5 h-5 text-slate-400 dark:text-slate-500 group-hover:text-slate-600 dark:group-hover:text-slate-300 flex-shrink-0" />
<span :class="isSidebarCollapsed ? 'md:hidden' : ''">{{ t('admin.nav.reports') }}</span>
</div>
<svg v-if="!isSidebarCollapsed" :class="expandedReports ? 'rotate-180' : ''" class="w-4 h-4 transition-transform text-slate-400 dark:text-slate-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
<div v-if="expandedReports && !isSidebarCollapsed" class="pl-4 space-y-1 mt-1 border-l-2 border-slate-100 dark:border-slate-700 ml-6">
<button
v-for="table in ['users', 'agents', 'chat_logs', 'permission_requests', 'feedbacks']"
:key="table"
@click="openReportTab(table)"
class="w-full text-left px-4 py-2 text-xs font-medium rounded-lg transition-colors flex items-center gap-2"
:class="(activeModule === 'reports' && currentTable === table) ? 'bg-brand-50 text-brand-700' : 'text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-slate-800 hover:text-slate-900 dark:hover:text-slate-100'"
>
<div class="w-1.5 h-1.5 rounded-full" :class="(activeModule === 'reports' && currentTable === table) ? 'bg-brand-600' : 'bg-slate-300'"></div>
{{ table.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()) }}
</button>
</div>
</div>
</nav>
</aside>
<!-- Main Content Area -->
<section class="flex-1 min-w-0 space-y-8 w-full">
<!-- Loading State -->
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600"></div>
</div>
<!-- Dashboard Overview -->
<section v-else-if="activeModule === 'dashboard'" class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-6 animate-fade-in-up">
<div
class="bg-white dark:bg-slate-900 p-6 rounded-2xl border border-slate-100 dark:border-slate-700 shadow-soft hover:shadow-lg transition-all group cursor-pointer"
@click="activeModule = 'agents'"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-brand-50 rounded-xl group-hover:bg-brand-100 transition-colors">
<Bot class="w-6 h-6 text-brand-600" />
</div>
<span class="text-xs font-medium text-green-600 bg-green-50 px-2 py-1 rounded-full">+2 new</span>
</div>
<div class="text-3xl font-bold text-slate-900 dark:text-slate-100 mb-1">{{ agents.length }}</div>
<div class="text-sm text-slate-500 dark:text-slate-400 font-medium">{{ t('admin.dash.activeAgents') }}</div>
</div>
<div
class="bg-white dark:bg-slate-900 p-6 rounded-2xl border border-slate-100 dark:border-slate-700 shadow-soft hover:shadow-lg transition-all group cursor-pointer"
@click="activeModule = 'permissions'"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-purple-50 rounded-xl group-hover:bg-purple-100 transition-colors">
<Users class="w-6 h-6 text-purple-600" />
</div>
</div>
<div class="text-3xl font-bold text-slate-900 mb-1">{{ users.length }}</div>
<div class="text-sm text-slate-500 font-medium">{{ t('admin.dash.totalUsers') }}</div>
</div>
<div
class="bg-white p-6 rounded-2xl border border-slate-100 shadow-soft hover:shadow-lg transition-all group cursor-pointer"
@click="activeModule = 'reports'; currentTable = 'chat_logs'"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-indigo-50 rounded-xl group-hover:bg-indigo-100 transition-colors">
<MessageSquare class="w-6 h-6 text-indigo-600" />
</div>
</div>
<div class="text-3xl font-bold text-slate-900 mb-1">{{ usageReport?.total ?? 0 }}</div>
<div class="text-sm text-slate-500 font-medium">{{ t('admin.dash.totalConversations') }}</div>
</div>
<div
class="bg-white p-6 rounded-2xl border border-slate-100 shadow-soft hover:shadow-lg transition-all group cursor-pointer"
@click="activeModule = 'reports'; currentTable = 'feedbacks'"
>
<div class="flex justify-between items-start mb-4">
<div class="p-3 bg-orange-50 rounded-xl group-hover:bg-orange-100 transition-colors">
<BarChart2 class="w-6 h-6 text-orange-600" />
</div>
</div>
<div class="text-3xl font-bold text-slate-900 mb-1">{{ feedbackReport?.avg_score?.toFixed(1) ?? '0.0' }}</div>
<div class="text-sm text-slate-500 font-medium">{{ t('admin.dash.avgRating') }}</div>
</div>
</section>
<!-- User Approvals -->
<section v-else-if="activeModule === 'approvals'" class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden animate-fade-in-up">
<div class="px-8 py-6 border-b border-slate-100 flex justify-between items-center bg-white">
<div>
<h2 class="text-lg font-bold text-slate-900">{{ t('admin.approval.title') }}</h2>
<p class="text-sm text-slate-500 mt-1">{{ t('admin.approval.subtitle') }}</p>
</div>
<button
@click="openCreateUserModal"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
>
<Plus class="w-4 h-4" />
<span class="font-medium">{{ t('admin.approval.addUser') }}</span>
</button>
</div>
<div class="overflow-x-auto">
<table class="w-full">
<thead class="bg-slate-50 border-b border-slate-100">
<tr>
<th class="px-8 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.approval.headers.username') }}</th>
<th class="px-8 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.approval.headers.nameId') }}</th>
<th class="px-8 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.approval.headers.contact') }}</th>
<th class="px-8 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.approval.headers.role') }}</th>
<th class="px-8 py-4 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.approval.headers.actions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-50">
<tr v-if="pendingUsers.length === 0">
<td colspan="5" class="px-8 py-12 text-center text-slate-400 text-sm">{{ t('admin.approval.noPending') }}</td>
</tr>
<tr v-for="user in pendingUsers" :key="user.id" class="hover:bg-slate-50 transition-colors">
<td class="px-8 py-5 text-sm font-medium text-slate-900">
<div>{{ user.username }}</div>
<div class="text-xs text-slate-500 font-normal">{{ user.email }}</div>
</td>
<td class="px-8 py-5 text-sm text-slate-500">
<div>{{ user.real_name || '-' }}</div>
<div class="text-xs text-slate-400 font-mono">{{ user.employee_id || '-' }}</div>
</td>
<td class="px-8 py-5 text-sm text-slate-500">{{ user.phone_number || '-' }}</td>
<td class="px-8 py-5">
<span class="px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200">
{{ t('admin.role.' + user.role) }}
</span>
</td>
<td class="px-8 py-5 text-right flex items-center justify-end gap-2">
<button
@click="approveUser(user.id)"
class="p-2 text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors"
title="Approve"
>
<ShieldCheck class="w-4 h-4" />
</button>
<button
@click="rejectUser(user.id)"
class="p-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
title="Reject"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- User Maintenance -->
<section v-else-if="activeModule === 'users'" class="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden animate-fade-in-up">
<div class="px-8 py-6 border-b border-slate-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white">
<div>
<h2 class="text-lg font-bold text-slate-900">{{ t('admin.user.title') }}</h2>
<p class="text-sm text-slate-500 mt-1">{{ t('admin.user.subtitle') }}</p>
</div>
<div class="flex flex-wrap gap-3">
<button
@click="isManagingDepts = true"
class="flex items-center gap-2 px-4 py-2 bg-white text-slate-700 rounded-xl hover:bg-slate-50 transition-all border border-slate-200 text-sm font-medium"
>
<span>{{ t('admin.user.manageDepts') }}</span>
</button>
<button
@click="cleanRejectedUsers"
class="flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 rounded-xl hover:bg-red-100 transition-all border border-red-200 text-sm font-medium"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.cleanRejected') }}</span>
</button>
<button
v-if="selectedUserIds.length > 0"
@click="batchDeleteUsers"
class="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-xl hover:bg-red-700 transition-all shadow-lg shadow-red-200 active:scale-95 text-sm font-medium"
>
<Trash2 class="w-4 h-4" />
<span>{{ t('admin.user.batchDelete') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="selectedUserIds.length > 0"
@click="openBatchEditModal"
class="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200 active:scale-95 text-sm font-medium"
>
<Edit class="w-4 h-4" />
<span>{{ t('admin.user.batchEdit') }} ({{ selectedUserIds.length }})</span>
</button>
<button
v-if="selectedUserIds.length > 0"
@click="openBatchPermissionModal"
class="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition-all shadow-lg shadow-purple-200 active:scale-95 text-sm font-medium"
>
<Users class="w-4 h-4" />
<span>{{ t('admin.user.batchPermission') }} ({{ selectedUserIds.length }})</span>
</button>
<button
@click="openCreateUserModal"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
>
<Plus class="w-4 h-4" />
<span class="font-medium">{{ t('admin.user.addUser') }}</span>
</button>
</div>
</div>
<!-- Filters -->
<div class="px-8 py-4 bg-slate-50 border-b border-slate-100 grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
<input v-model="userFilters.username" :placeholder="t('admin.user.filterUsername')" class="px-3 py-2 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500 bg-white" />
<input v-model="userFilters.email" :placeholder="t('admin.user.filterEmail')" class="px-3 py-2 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500 bg-white" />
<select v-model="userFilters.department" class="px-3 py-2 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500 bg-white">
<option value="">{{ t('admin.user.allDepts') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
<input v-model="userFilters.role" :placeholder="t('admin.user.filterRole')" class="px-3 py-2 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500 bg-white" />
<div class="flex items-center gap-2">
<input type="checkbox" id="hideRejected" v-model="hideRejected" class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 border-slate-300" />
<label for="hideRejected" class="text-sm text-slate-600 select-none">{{ t('admin.user.hideRejected') }}</label>
</div>
</div>
<div class="overflow-x-auto">
<table class="w-full">
<thead class="bg-slate-50 border-b border-slate-100">
<tr>
<th class="px-6 py-4 w-12 text-center">
<input type="checkbox"
:checked="selectedUserIds.length === filteredUsers.length && filteredUsers.length > 0"
@change="toggleAllUsers(filteredUsers)"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-slate-300"
/>
</th>
<th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.user.headers.user') }}</th>
<th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.user.headers.role') }}</th>
<th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.user.headers.dept') }}</th>
<th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.user.headers.status') }}</th>
<th class="px-6 py-4 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">{{ t('admin.user.headers.actions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-50">
<tr v-if="filteredUsers.length === 0">
<td colspan="6" class="px-6 py-12 text-center text-slate-400 text-sm">{{ t('admin.user.noUsers') }}</td>
</tr>
<tr v-for="user in filteredUsers" :key="user.id" class="hover:bg-slate-50 transition-colors group">
<td class="px-6 py-4 text-center">
<input type="checkbox"
:checked="selectedUserIds.includes(user.id)"
@change="toggleUserSelection(user.id)"
class="w-4 h-4 rounded text-brand-600 focus:ring-brand-500 cursor-pointer border-slate-300"
/>
</td>
<td class="px-6 py-4">
<div class="flex items-center">
<div class="h-9 w-9 rounded-full bg-gradient-to-br from-brand-500 to-indigo-600 text-white flex items-center justify-center text-xs font-bold shadow-sm">
{{ user.username.charAt(0).toUpperCase() }}
</div>
<div class="ml-3">
<div class="text-sm font-medium text-slate-900">{{ user.username }}</div>
<div class="text-xs text-slate-500">{{ user.email }}</div>
</div>
</div>
</td>
<td class="px-6 py-4">
<span class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
:class="user.role === 'admin' ? 'bg-purple-50 text-purple-700 border-purple-100' : 'bg-blue-50 text-blue-700 border-blue-100'">
{{ t('admin.role.' + user.role) }}
</span>
</td>
<td class="px-6 py-4 text-sm text-slate-500">
{{ user.department || '-' }}
</td>
<td class="px-6 py-4">
<span class="px-2.5 py-0.5 rounded-full text-xs font-medium border"
:class="{
'bg-green-50 text-green-700 border-green-100': user.status === 'active',
'bg-yellow-50 text-yellow-700 border-yellow-100': user.status === 'pending',
'bg-red-50 text-red-700 border-red-100': user.status === 'disabled' || user.status === 'rejected'
}">
{{ t('admin.status.' + user.status) }}
</span>
</td>
<td class="px-6 py-4 text-right">
<button
@click="openEditUserModal(user)"
class="text-brand-600 hover:text-brand-900 font-medium text-xs px-3 py-1.5 rounded-lg hover:bg-brand-50 transition-colors"
>
{{ t('admin.edit') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- Department Management -->
<section v-else-if="activeModule === 'departments'" class="space-y-6 animate-fade-in-up">
<div class="flex items-center justify-between">
<div>
<h2 class="text-xl font-bold text-gray-900">{{ t('admin.dept.title') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ t('admin.dept.subtitle') }}</p>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Form Section -->
<div class="lg:col-span-1 bg-white rounded-2xl border border-gray-100 p-6 shadow-sm h-fit">
<h3 class="font-bold text-gray-900 mb-4">{{ editingDept.id ? t('admin.dept.edit') : t('admin.dept.add') }}</h3>
<div class="space-y-4">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.dept.fields.name') }}</label>
<input v-model="editingDept.name" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" placeholder="e.g. IT Department" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.dept.fields.code') }}</label>
<input v-model="editingDept.code" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" placeholder="e.g. DEPT-001" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.dept.fields.company') }}</label>
<input v-model="editingDept.company" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" placeholder="e.g. HQ" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.dept.fields.description') }}</label>
<textarea v-model="editingDept.description" rows="3" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" placeholder="Department description..."></textarea>
</div>
<div class="flex justify-end gap-2 pt-2">
<button v-if="editingDept.id" @click="editingDept = {}" class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg text-sm font-medium transition-colors">{{ t('admin.cancel') }}</button>
<button @click="saveDepartment" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors shadow-sm">
{{ editingDept.id ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div>
<!-- List Section -->
<div class="lg:col-span-2 bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div v-if="departments.length === 0" class="p-8 text-center text-gray-400">
{{ t('admin.dept.noDepts') }}
</div>
<table v-else class="w-full text-left">
<thead class="bg-gray-50 border-b border-gray-100">
<tr>
<th class="px-6 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.dept.headers.name') }}</th>
<th class="px-6 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.dept.headers.code') }}</th>
<th class="px-6 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.dept.headers.company') }}</th>
<th class="px-6 py-3 text-xs font-semibold text-gray-500 uppercase text-right">{{ t('admin.dept.headers.actions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr v-for="d in departments" :key="d.id" class="hover:bg-gray-50 transition-colors">
<td class="px-6 py-4">
<div class="font-medium text-gray-900 text-sm">{{ d.name }}</div>
<div class="text-xs text-gray-500 truncate max-w-xs mt-0.5">{{ d.description }}</div>
</td>
<td class="px-6 py-4 text-sm text-gray-500 font-mono">{{ d.code || '-' }}</td>
<td class="px-6 py-4 text-sm text-gray-500">{{ d.company || '-' }}</td>
<td class="px-6 py-4 text-right flex justify-end gap-2">
<button @click="editDepartment(d)" class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
<Edit class="w-4 h-4" />
</button>
<button @click="deleteDepartment(d.id)" class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- Agent Management -->
<section v-else-if="activeModule === 'agents'" class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden animate-fade-in-up">
<div class="px-8 py-6 border-b border-gray-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-4 bg-white">
<div>
<h2 class="text-xl font-bold text-gray-900">{{ t('admin.agent.title') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ t('admin.agent.subtitle') }}</p>
</div>
<button
@click="resetAgentForm"
class="flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition-colors shadow-lg shadow-blue-200"
>
<Plus class="w-5 h-5" />
<span class="font-medium">{{ t('admin.agent.new') }}</span>
</button>
</div>
<!-- Add Agent Form -->
<div class="px-8 py-8 border-b border-gray-100 dark:border-slate-700 bg-white dark:bg-slate-900">
<h3 class="text-base font-bold text-gray-800 dark:text-slate-100 mb-6">{{ isEditingAgent ? t('admin.agent.edit') : t('admin.agent.create') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
<div class="space-y-2">
<label class="text-xs font-bold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.fields.name') }}</label>
<input
v-model="newAgent.name"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-base focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm"
placeholder="e.g. HR Assistant"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.fields.type') }}</label>
<select v-model="newAgent.type" class="w-full border-gray-200 rounded-xl px-4 py-3 text-base focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-white">
<option value="api">{{ t('admin.agent.fields.types.api') }}</option>
<option value="iframe">{{ t('admin.agent.fields.types.iframe') }}</option>
</select>
</div>
<template v-if="newAgent.type === 'api'">
<div class="space-y-2">
<label class="text-xs font-bold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.fields.appId') }}</label>
<input
v-model="newAgent.dify_app_id"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm font-mono bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
/>
</div>
<div class="space-y-2">
<label class="text-xs font-bold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.fields.apiKey') }}</label>
<input
v-model="newAgent.dify_api_key"
type="password"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm font-mono bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
/>
</div>
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.fields.baseUrl') }}</label>
<input
v-model="newAgent.api_base_url"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm font-mono bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
placeholder="Default: Dify Config"
/>
</div>
</template>
<template v-if="newAgent.type === 'iframe'">
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.fields.iframeUrl') }}</label>
<input
v-model="newAgent.iframe_url"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm font-mono bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
placeholder="https://..."
/>
</div>
</template>
<div class="col-span-1 md:col-span-2 space-y-2">
<label class="text-xs font-bold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.fields.description') }}</label>
<input
v-model="newAgent.description"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-base bg-white focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none shadow-sm"
:placeholder="t('admin.agent.fields.descPlaceholder')"
/>
</div>
</div>
<div class="flex justify-end">
<button
class="flex items-center gap-2 px-8 py-3 bg-blue-600 text-white text-base font-medium rounded-xl hover:bg-blue-700 transition-all shadow-md shadow-blue-200 active:scale-95"
@click="createAgent"
>
<Plus v-if="!isEditingAgent" class="w-5 h-5" />
{{ isEditingAgent ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
<!-- Agent List -->
<div class="overflow-x-auto">
<div v-if="agents.length === 0" class="text-center py-12 text-gray-500">
<Bot class="w-12 h-12 mx-auto text-gray-300 mb-3" />
<p class="text-lg">{{ t('admin.agent.noAgents') }}</p>
</div>
<table v-else class="w-full text-left">
<thead class="bg-gray-50/50 border-b border-gray-100">
<tr>
<th class="px-8 py-4 text-sm font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.headers.name') }}</th>
<th class="px-8 py-4 text-sm font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.headers.type') }}</th>
<th class="px-8 py-4 text-sm font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.headers.config') }}</th>
<th class="px-8 py-4 text-sm font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.agent.headers.status') }}</th>
<th class="px-8 py-4 text-sm font-semibold text-gray-500 uppercase tracking-wider text-right">{{ t('admin.agent.headers.actions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<tr
v-for="agent in agents"
:key="agent.id"
class="hover:bg-gray-50/50 transition-colors group cursor-pointer"
:class="{ 'bg-blue-50/50': selectedAgentId === agent.id }"
@click="selectAgent(agent)"
>
<td class="px-8 py-5">
<div class="font-bold text-gray-900 text-base">{{ agent.name }}</div>
<div class="text-sm text-gray-500 mt-1">{{ agent.description }}</div>
</td>
<td class="px-8 py-5">
<span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800 uppercase tracking-wide">
{{ agent.type }}
</span>
</td>
<td class="px-8 py-5 font-mono text-xs text-gray-500 max-w-xs truncate">
<span v-if="agent.type === 'api'" class="flex items-center gap-1">
<span class="text-gray-400">ID:</span> {{ agent.dify_app_id }}
</span>
<span v-else class="flex items-center gap-1" :title="agent.extra_config?.iframe_url">
<span class="text-gray-400">URL:</span> {{ agent.extra_config?.iframe_url }}
</span>
</td>
<td class="px-8 py-5">
<span
class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border"
:class="agent.is_active ? 'bg-green-50 text-green-700 border-green-100' : 'bg-gray-100 text-gray-600 border-gray-200'"
>
<span class="w-2 h-2 rounded-full" :class="agent.is_active ? 'bg-green-500' : 'bg-gray-400'"></span>
{{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }}
</span>
</td>
<td class="px-8 py-5 text-right flex justify-end gap-2">
<button
@click.stop="openAgentTestModal(agent)"
class="p-2 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-all"
title="测试应用"
>
测试
</button>
<button
@click.stop="openAgentPermissionModal(agent)"
class="p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
title="Manage Access"
>
<Users class="w-5 h-5" />
</button>
<button
@click.stop="deleteAgent(agent.id)"
class="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
title="Delete Agent"
>
<Trash2 class="w-5 h-5" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- Announcement Management -->
<section v-else-if="activeModule === 'announcements'" class="space-y-6 animate-fade-in-up">
<div>
<h2 class="text-xl font-bold text-gray-900">{{ t('admin.announcement.title') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ t('admin.announcement.subtitle') }}</p>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-1 bg-white rounded-2xl border border-gray-100 p-6 shadow-sm h-fit">
<h3 class="font-bold text-gray-900 mb-4">{{ t('admin.announcement.add') }}</h3>
<div class="space-y-4">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.announcement.fields.title') }}</label>
<input v-model="newAnnouncement.title" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.announcement.fields.content') }}</label>
<textarea v-model="newAnnouncement.content" rows="6" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"></textarea>
</div>
<div class="flex justify-end pt-2">
<button @click="createAnnouncementAdmin" :disabled="isSaving" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors shadow-sm disabled:opacity-50">
{{ isSaving ? t('admin.save') + '...' : t('admin.announcement.publish') }}
</button>
</div>
</div>
</div>
<div class="lg:col-span-2 bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div v-if="adminAnnouncements.length === 0" class="p-8 text-center text-gray-400">
{{ t('admin.announcement.noData') }}
</div>
<div v-else class="divide-y divide-gray-100">
<div v-for="ann in adminAnnouncements" :key="ann.id" class="p-5 hover:bg-gray-50 transition-colors">
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<h4 class="font-semibold text-gray-900 truncate">{{ ann.title }}</h4>
<p class="text-xs text-gray-500 mt-1">{{ new Date(ann.created_at).toLocaleString() }}</p>
</div>
<button @click="deleteAnnouncementAdmin(ann.id)" class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</div>
<p class="text-sm text-gray-600 mt-2 whitespace-pre-wrap">{{ ann.content }}</p>
</div>
</div>
</div>
</div>
</section>
<!-- Common Questions Management -->
<section v-else-if="activeModule === 'questions'" class="space-y-6 animate-fade-in-up">
<div class="flex items-center justify-between">
<div>
<h2 class="text-xl font-bold text-gray-900">{{ t('admin.question.title') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ t('admin.question.subtitle') }}</p>
</div>
</div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Form Section -->
<div class="lg:col-span-1 bg-white rounded-2xl border border-gray-100 p-6 shadow-sm h-fit">
<h3 class="font-bold text-gray-900 mb-4">{{ isEditingQuestion ? t('admin.question.edit') : t('admin.question.add') }}</h3>
<div class="space-y-4">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.question.fields.title') }}</label>
<input v-model="newQuestion.title" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" placeholder="e.g. Write Report" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.question.fields.targetAgent') }}</label>
<select v-model="newQuestion.agent_id" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none bg-white">
<option :value="undefined" disabled>{{ t('admin.perm.batchModal.selectAgents') }}</option>
<option v-for="agent in agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.question.fields.sortOrder') }}</label>
<input type="number" v-model="newQuestion.sort_order" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-gray-500 uppercase">{{ t('admin.question.fields.content') }}</label>
<textarea v-model="newQuestion.question" rows="4" class="w-full px-3 py-2 border rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" :placeholder="t('admin.question.fields.contentPlaceholder')"></textarea>
</div>
<div class="flex justify-end gap-2 pt-2">
<button v-if="isEditingQuestion" @click="resetQuestionForm" class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg text-sm font-medium transition-colors">{{ t('admin.cancel') }}</button>
<button @click="saveQuestion" :disabled="isSaving" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors shadow-sm disabled:opacity-50">
{{ isSaving ? t('admin.save') + '...' : (isEditingQuestion ? t('admin.update') : t('admin.add')) }}
</button>
</div>
</div>
</div>
<!-- List Section -->
<div class="lg:col-span-2 bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div v-if="quickQuestions.length === 0" class="p-8 text-center text-gray-400">
{{ t('admin.question.noData') }}
</div>
<table v-else class="w-full text-left">
<thead class="bg-gray-50 border-b border-gray-100">
<tr>
<th class="px-6 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.question.headers.title') }}</th>
<th class="px-6 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.question.headers.agent') }}</th>
<th class="px-6 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.question.headers.order') }}</th>
<th class="px-6 py-3 text-xs font-semibold text-gray-500 uppercase text-right">{{ t('admin.question.headers.actions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr v-for="q in quickQuestions" :key="q.id" class="hover:bg-gray-50 transition-colors">
<td class="px-6 py-4">
<div class="font-medium text-gray-900 text-sm">{{ q.title }}</div>
<div class="text-xs text-gray-500 truncate max-w-xs mt-0.5">{{ q.question }}</div>
</td>
<td class="px-6 py-4">
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 border border-blue-100">
{{ q.agent_name || 'Unknown' }}
</span>
</td>
<td class="px-6 py-4 text-sm text-gray-500">{{ q.sort_order }}</td>
<td class="px-6 py-4 text-right flex justify-end gap-2">
<button @click="editQuestion(q)" class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
<Edit class="w-4 h-4" />
</button>
<button @click="deleteQuestion(q.id)" class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- User Permission Management (Matrix View) -->
<section v-else-if="activeModule === 'permissions'" class="space-y-6 animate-fade-in-up">
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div>
<h2 class="text-xl font-bold text-gray-900">{{ t('admin.perm.title') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ t('admin.perm.subtitle') }}</p>
</div>
<div class="flex gap-3">
<button
v-if="selectedUserIds.length > 0"
@click="openBatchPermissionModal"
class="flex items-center gap-2 px-4 py-2 bg-indigo-600 text-white rounded-xl hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-200 active:scale-95"
>
<Users class="w-4 h-4" />
<span class="font-medium">{{ t('admin.perm.batchAssign') }}</span>
</button>
<label class="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 text-gray-700 rounded-xl hover:bg-gray-50 cursor-pointer text-sm font-medium transition-all shadow-sm">
<input type="file" accept=".csv" class="hidden" @change="handlePermissionImport" />
<FileText class="w-4 h-4" />
{{ t('admin.perm.importCsv') }}
</label>
<button
class="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 text-gray-700 rounded-xl hover:bg-gray-50 text-sm font-medium transition-all shadow-sm"
@click="exportPermissions"
>
<Download class="w-4 h-4" />
{{ t('admin.perm.exportCsv') }}
</button>
</div>
</div>
<!-- Filters -->
<div class="flex flex-wrap gap-4 bg-white p-4 rounded-xl border border-gray-100 shadow-sm">
<input v-model="permissionFilters.username" :placeholder="t('admin.perm.filterName')" class="px-3 py-2 border rounded-lg text-sm w-48 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" />
<input v-model="permissionFilters.department" :placeholder="t('admin.perm.filterDept')" class="px-3 py-2 border rounded-lg text-sm w-48 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none" />
<select v-model="permissionFilters.role" class="px-3 py-2 border rounded-lg text-sm w-32 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none bg-white">
<option value="">{{ t('admin.perm.allRoles') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="overflow-x-auto bg-white border border-gray-100 rounded-2xl shadow-sm">
<table class="w-full">
<thead class="bg-gray-50 border-b border-gray-100">
<tr>
<th class="px-4 py-4 w-12 text-center sticky left-0 bg-gray-50 z-20">
<input type="checkbox" :checked="selectedUserIds.length > 0 && selectedUserIds.length === filteredPermissionUsers.length" @change="toggleAllUsers(filteredPermissionUsers)" class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500" />
</th>
<th class="px-6 py-4 text-left text-sm font-semibold text-gray-500 uppercase tracking-wider sticky left-12 bg-gray-50 z-20 w-64 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]">{{ t('admin.perm.headers.user') }}</th>
<th class="px-6 py-4 text-left text-sm font-semibold text-gray-500 uppercase tracking-wider sticky left-[19rem] bg-gray-50 z-20 w-40 border-r border-gray-100 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]">{{ t('admin.perm.headers.dept') }}</th>
<th
v-for="agent in agents"
:key="agent.id"
class="px-4 py-4 text-center text-sm font-semibold text-gray-500 uppercase tracking-wider min-w-[100px]"
>
<div class="flex flex-col items-center gap-1">
<span>{{ agent.name }}</span>
<span class="text-[10px] text-gray-400 font-normal border border-gray-200 px-1 rounded">{{ agent.type }}</span>
</div>
</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr v-for="user in filteredPermissionUsers" :key="user.id" class="hover:bg-gray-50 transition-colors">
<td class="px-4 py-4 text-center sticky left-0 bg-white z-20">
<input type="checkbox" :checked="selectedUserIds.includes(user.id)" @change="toggleUserSelection(user.id)" class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500" />
</td>
<td class="px-6 py-4 sticky left-12 bg-white z-20 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]">
<div class="flex items-center gap-3">
<div class="w-8 h-8 rounded-full bg-gradient-to-br from-blue-100 to-indigo-100 text-blue-600 flex items-center justify-center font-bold text-sm">
{{ user.username.charAt(0).toUpperCase() }}
</div>
<div class="truncate max-w-[150px]">
<div class="font-medium text-gray-900 truncate" :title="user.username">{{ user.username }}</div>
<div class="text-xs text-gray-500 truncate" :title="user.email">{{ user.email }}</div>
</div>
</div>
</td>
<td class="px-6 py-4 sticky left-[19rem] bg-white z-20 border-r border-gray-100 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]">
<div class="text-sm text-gray-500 truncate" :title="user.department">{{ user.department || '-' }}</div>
</td>
<td
v-for="agent in agents"
:key="agent.id"
class="px-4 py-4 text-center border-l border-dashed border-gray-100"
>
<input
type="checkbox"
:checked="user.agent_ids.includes(agent.id)"
@change="toggleUserAgentPermission(user, agent.id)"
class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500 border-gray-300 cursor-pointer transition-all"
/>
</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- WeCom Management -->
<section v-else-if="activeModule === 'wecom'" class="space-y-6 animate-fade-in-up">
<div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
<div>
<h2 class="text-xl font-bold text-gray-900">{{ t('admin.wecom.title') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ t('admin.wecom.subtitle') }}</p>
</div>
<button
@click="refreshWecomData"
class="inline-flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 text-gray-700 rounded-xl hover:bg-gray-50 transition-all shadow-sm"
>
<RefreshCw class="w-4 h-4" />
{{ t('admin.wecom.refresh') }}
</button>
</div>
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 space-y-4">
<h3 class="font-semibold text-gray-900">{{ t('admin.wecom.quickBind') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-4 gap-3">
<input v-model="wecomBindForm.user_id" type="number" :placeholder="t('admin.wecom.fields.userId')" class="input-field" />
<input v-model="wecomBindForm.wecom_userid" :placeholder="t('admin.wecom.fields.wecomUserId')" class="input-field md:col-span-2" />
<input v-model="wecomBindForm.wecom_unionid" :placeholder="t('admin.wecom.fields.wecomUnionId')" class="input-field" />
</div>
<div class="flex justify-end">
<button @click="bindWecomUser" :disabled="isSaving" class="btn-primary px-5 py-2 disabled:opacity-60">
<Link2 class="w-4 h-4" /> {{ t('admin.wecom.bind') }}
</button>
</div>
</div>
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div class="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
<h3 class="font-semibold text-gray-900">{{ t('admin.wecom.bindingList') }}</h3>
<label class="inline-flex items-center gap-2 text-sm text-gray-600">
<input type="checkbox" v-model="wecomBoundOnly" class="w-4 h-4 rounded text-blue-600 border-gray-300" />
{{ t('admin.wecom.boundOnly') }}
</label>
</div>
<div class="overflow-x-auto">
<table class="w-full text-left">
<thead class="bg-gray-50 border-b border-gray-100">
<tr>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.headers.user') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.headers.roleStatus') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.headers.wecomUserId') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.headers.unionId') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase text-right">{{ t('admin.wecom.headers.actions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<tr v-if="wecomBindings.length === 0">
<td colspan="5" class="px-4 py-8 text-center text-sm text-gray-400">{{ t('admin.wecom.noData') }}</td>
</tr>
<tr v-for="u in wecomBindings" :key="u.id" class="hover:bg-gray-50">
<td class="px-4 py-3">
<div class="text-sm font-medium text-gray-900">{{ u.username }} <span class="text-gray-500">(#{{ u.id }})</span></div>
<div class="text-xs text-gray-500">{{ u.real_name || '-' }} · {{ u.email }}</div>
</td>
<td class="px-4 py-3 text-sm text-gray-600">{{ t('admin.role.' + u.role) }} / {{ t('admin.status.' + u.status) }}</td>
<td class="px-4 py-3 text-sm text-gray-700 font-mono">{{ u.wecom_userid || '-' }}</td>
<td class="px-4 py-3 text-sm text-gray-700 font-mono">{{ u.wecom_unionid || '-' }}</td>
<td class="px-4 py-3 text-right">
<button
v-if="u.wecom_userid"
@click="unbindWecomUserByAdmin(u.id)"
class="inline-flex items-center gap-1 px-3 py-1.5 text-xs text-red-600 bg-red-50 rounded-lg hover:bg-red-100"
>
<Unlink2 class="w-3.5 h-3.5" />
{{ t('admin.wecom.unbind') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
<div class="px-5 py-4 border-b border-gray-100 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
<h3 class="font-semibold text-gray-900">{{ t('admin.wecom.auditTitle') }}</h3>
<div class="flex flex-wrap items-center gap-2">
<select v-model="wecomAuditSourceFilter" class="px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white">
<option value="all">{{ t('admin.wecom.filters.allSources') }}</option>
<option value="wecom">{{ t('admin.wecom.sources.wecom') }}</option>
<option value="password">{{ t('admin.wecom.sources.password') }}</option>
</select>
<select v-model="wecomAuditStatusFilter" class="px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white">
<option value="all">{{ t('admin.wecom.filters.allStatus') }}</option>
<option value="success">{{ t('admin.wecom.auditStatus.success') }}</option>
<option value="failed">{{ t('admin.wecom.auditStatus.failed') }}</option>
</select>
<button
@click="exportWecomAudits"
class="inline-flex items-center gap-2 px-3 py-2 border border-gray-200 rounded-lg text-sm text-gray-700 bg-white hover:bg-gray-50"
>
<Download class="w-4 h-4" />
{{ t('admin.wecom.exportAudit') }}
</button>
</div>
</div>
<div class="overflow-x-auto max-h-[420px]">
<table class="w-full text-left">
<thead class="bg-gray-50 border-b border-gray-100 sticky top-0 z-10">
<tr>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.auditHeaders.time') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.auditHeaders.source') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.auditHeaders.user') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.auditHeaders.status') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.auditHeaders.reason') }}</th>
<th class="px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{{ t('admin.wecom.auditHeaders.ip') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<tr v-if="filteredWecomLoginAudits.length === 0">
<td colspan="6" class="px-4 py-8 text-center text-sm text-gray-400">{{ t('admin.wecom.noAuditData') }}</td>
</tr>
<tr v-for="row in filteredWecomLoginAudits" :key="row.id" class="hover:bg-gray-50">
<td class="px-4 py-3 text-xs text-gray-600 whitespace-nowrap">{{ row.created_at || '-' }}</td>
<td class="px-4 py-3 text-xs text-gray-700">{{ t('admin.wecom.sources.' + row.source) }}</td>
<td class="px-4 py-3 text-xs text-gray-700">{{ row.username || '-' }}</td>
<td class="px-4 py-3">
<span class="inline-flex px-2 py-0.5 rounded-full text-[11px] font-medium" :class="row.status === 'success' ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'">
{{ t('admin.wecom.auditStatus.' + row.status) }}
</span>
</td>
<td class="px-4 py-3 text-xs text-gray-600 max-w-[360px] truncate" :title="row.reason || ''">{{ row.reason || '-' }}</td>
<td class="px-4 py-3 text-xs text-gray-600 font-mono">{{ row.ip || '-' }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<!-- Requests -->
<section
v-if="activeModule === 'requests'"
class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden animate-fade-in-up"
>
<div class="px-8 py-6 border-b border-gray-100 bg-white">
<h2 class="font-bold text-gray-900 text-lg">{{ t('admin.request.title') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ t('admin.request.subtitle') }}</p>
</div>
<div v-if="permissionRequests.length === 0" class="flex flex-col items-center justify-center py-16 text-gray-400">
<div class="w-16 h-16 bg-gray-50 rounded-full flex items-center justify-center mb-4">
<ShieldCheck class="w-8 h-8 text-gray-300" />
</div>
<p>{{ t('admin.request.noPending') }}</p>
</div>
<table v-else class="w-full text-left">
<thead class="bg-gray-50/50 border-b border-gray-100">
<tr>
<th class="px-8 py-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.request.headers.userId') }}</th>
<th class="px-8 py-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.request.headers.targetAgent') }}</th>
<th class="px-8 py-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.request.headers.reason') }}</th>
<th class="px-8 py-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.request.headers.status') }}</th>
<th class="px-8 py-4 text-xs font-semibold text-gray-500 uppercase tracking-wider text-right">{{ t('admin.request.headers.actions') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100">
<tr v-for="req in permissionRequests" :key="req.id" class="hover:bg-gray-50/50 transition-colors">
<td class="px-8 py-4 text-sm font-medium text-gray-900">{{ req.user_id }}</td>
<td class="px-8 py-4 text-sm text-gray-700">{{ req.agent_id }}</td>
<td class="px-8 py-4 text-sm text-gray-500 max-w-xs truncate" :title="req.reason">{{ req.reason || '-' }}</td>
<td class="px-8 py-4">
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-50 text-yellow-700 border border-yellow-100">
{{ t('admin.status.' + req.status) }}
</span>
</td>
<td class="px-8 py-4 text-right">
<div class="flex justify-end gap-3">
<button
class="text-green-600 hover:text-green-800 text-sm font-medium hover:underline"
@click="approvePermissionRequest(req.id)"
>
{{ t('admin.request.approve') }}
</button>
<button
class="text-red-500 hover:text-red-700 text-sm font-medium hover:underline"
@click="rejectPermissionRequest(req.id)"
>
{{ t('admin.request.reject') }}
</button>
</div>
</td>
</tr>
</tbody>
</table>
</section>
<!-- Reports -->
<section
v-if="activeModule === 'reports'"
class="relative rounded-3xl border border-slate-200/80 bg-gradient-to-br from-white via-slate-50 to-cyan-50/40 shadow-[0_20px_60px_-35px_rgba(15,23,42,0.45)] transition-all duration-300 animate-fade-in-up"
:class="isFullScreen ? 'fixed inset-0 z-50 m-0 rounded-none h-screen w-screen overflow-auto p-8' : 'overflow-hidden'"
>
<div class="px-6 md:px-8 py-5 border-b border-slate-200/70 bg-white/85 backdrop-blur-md flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between sticky top-0 z-10 shadow-sm">
<div class="space-y-2">
<h2 class="font-bold text-slate-900 text-lg flex items-center gap-3">
<span class="inline-flex h-8 w-8 items-center justify-center rounded-xl bg-gradient-to-br from-sky-600 to-cyan-500 shadow-md shadow-cyan-200/70">
<BarChart2 class="w-4 h-4 text-white" />
</span>
{{ t('admin.report.title', { table: currentTable.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()) }) }}
</h2>
<div class="flex flex-wrap items-center gap-2 text-xs">
<span class="inline-flex items-center rounded-full border border-slate-200 bg-slate-50 px-3 py-1 font-medium text-slate-600">
{{ t('admin.report.subtitle') }}
</span>
<span v-if="isChatLogsTable" class="inline-flex items-center rounded-full border border-cyan-200 bg-cyan-50 px-3 py-1 font-semibold text-cyan-700">
Total: {{ chatLogsTotal }}
</span>
<span class="inline-flex items-center rounded-full border border-indigo-200 bg-indigo-50 px-3 py-1 font-semibold text-indigo-700">
Showing: {{ reportRangeStart }}-{{ reportRangeEnd }} / {{ reportTotalRows }}
</span>
</div>
</div>
<div class="flex flex-wrap items-center gap-2 md:gap-3">
<button
@click="showChatLogsColumnPanel = !showChatLogsColumnPanel"
class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold text-slate-700 border border-slate-300 bg-white hover:bg-slate-50 hover:border-slate-400 transition-colors"
title="Column Settings"
>
<Settings2 class="w-4 h-4" />
<span>Column Settings</span>
</button>
<button
v-if="isChatLogsTable"
@click="showChatLogsSelection = !showChatLogsSelection"
class="px-3 py-2 border border-slate-300 rounded-xl text-xs font-medium text-slate-600 hover:bg-slate-50"
>
{{ showChatLogsSelection ? 'Hide Selection' : 'Show Selection' }}
</button>
<button
v-if="isChatLogsTable && showChatLogsSelection"
@click="batchDeleteChatLogs"
:disabled="selectedReportRowIds.length === 0 || isDeletingChatLogs"
class="flex items-center gap-2 px-4 py-2 bg-rose-600 text-white text-sm font-medium rounded-xl hover:bg-rose-700 transition-all shadow-md shadow-rose-200 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ isDeletingChatLogs ? 'Deleting...' : `Delete Selected (${selectedReportRowIds.length})` }}
</button>
<button
@click="exportToExcel"
class="flex items-center gap-2 px-4 py-2 bg-emerald-600 text-white text-sm font-medium rounded-xl hover:bg-emerald-700 transition-all shadow-md shadow-emerald-200 active:scale-95"
>
<Download class="w-4 h-4" />
{{ t('admin.report.export') }}
</button>
<button
@click="isFullScreen = !isFullScreen"
class="p-2.5 hover:bg-slate-100 rounded-xl transition-colors text-slate-500 hover:text-slate-900 border border-slate-200/60 bg-white"
:title="isFullScreen ? t('admin.report.exitFullscreen') : t('admin.report.enterFullscreen')"
>
<svg v-if="!isFullScreen" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M16 3h3a2 2 0 0 1 2 2v3"/><path d="M8 21H5a2 2 0 0 1-2-2v-3"/><path d="M16 21h3a2 2 0 0 1 2 2v-3"/></svg>
<svg v-else xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v3a2 2 0 0 1-2 2H3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M16 21v-3a2 2 0 0 1 2-2h3"/></svg>
</button>
</div>
</div>
<div class="p-5 md:p-8 space-y-5">
<div
v-if="showChatLogsColumnPanel"
class="p-4 md:p-5 rounded-2xl border border-slate-200 bg-white/90 shadow-sm"
>
<div class="flex items-center justify-between mb-3">
<div class="text-sm font-semibold text-slate-800">Table Settings</div>
<button
@click="resetChatLogsColumns"
class="text-xs px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-200 hover:bg-slate-100 text-slate-700"
>
Reset Layout
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
<label class="flex items-center gap-2 px-3 py-2 bg-slate-50 rounded-lg border border-slate-200 text-xs text-slate-700">
<input type="checkbox" v-model="chatLogsWrapEnabled" class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500" />
<span>换行</span>
</label>
<label class="flex items-center gap-2 px-3 py-2 bg-slate-50 rounded-lg border border-slate-200 text-xs text-slate-700">
<span>换行最大高度(px)</span>
<input
v-model.number="chatLogsWrapMaxHeight"
type="number"
step="1"
class="w-24 px-2 py-1 border border-slate-300 rounded text-xs outline-none focus:ring-1 focus:ring-sky-500"
/>
</label>
</div>
<div class="mb-3 p-3 bg-slate-50 rounded-xl border border-slate-200">
<div class="flex items-center justify-between mb-2">
<span class="text-xs font-semibold text-slate-700">高级排序规则(按顺序优先)</span>
<button
@click="addChatLogsSortRule"
class="text-xs px-2 py-1 rounded border border-slate-300 hover:bg-white text-slate-700"
>
+ 添加规则
</button>
</div>
<div v-if="chatLogsSortRules.length === 0" class="text-xs text-slate-500">未设置高级排序,将使用列头点击排序。</div>
<div v-else class="space-y-2">
<div
v-for="(rule, ridx) in chatLogsSortRules"
:key="`sort-rule-${ridx}`"
class="grid grid-cols-12 items-center gap-2 text-xs p-2 border border-slate-200 rounded-lg bg-white"
>
<span class="col-span-1 text-slate-500">{{ ridx + 1 }}.</span>
<select v-model="rule.key" class="col-span-4 px-2 py-1 border border-slate-300 rounded">
<option v-for="k in Object.keys(tableData[0] || {})" :key="`rule-key-${k}`" :value="k">{{ k }}</option>
</select>
<select v-model="rule.direction" class="col-span-3 px-2 py-1 border border-slate-300 rounded">
<option value="asc">正序</option>
<option value="desc">倒序</option>
</select>
<div class="col-span-4 flex items-center justify-end gap-1">
<button @click="moveChatLogsSortRule(ridx, -1)" class="px-2 py-1 rounded border border-slate-300 hover:bg-slate-50">上移</button>
<button @click="moveChatLogsSortRule(ridx, 1)" class="px-2 py-1 rounded border border-slate-300 hover:bg-slate-50">下移</button>
<button @click="removeChatLogsSortRule(ridx)" class="px-2 py-1 rounded border border-red-200 text-red-600 hover:bg-red-50">删除</button>
</div>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
<div
v-for="col in chatLogsColumns"
:key="`cfg-${col.key}`"
class="flex items-center justify-between gap-2 px-2 py-1.5 bg-slate-50 rounded-lg border border-slate-200"
>
<label class="flex items-center gap-2 min-w-0">
<input type="checkbox" v-model="col.visible" class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500" />
<span class="text-xs text-slate-700 truncate">{{ col.key }}</span>
</label>
<div class="flex items-center gap-1">
<button @click="moveChatLogsColumn(col.key, -1)" class="text-xs px-1.5 py-0.5 rounded border border-slate-300 hover:bg-white">◀</button>
<button @click="moveChatLogsColumn(col.key, 1)" class="text-xs px-1.5 py-0.5 rounded border border-slate-300 hover:bg-white">▶</button>
</div>
</div>
</div>
</div>
<div v-if="tableData.length === 0" class="text-center text-slate-400 py-20 bg-slate-50 rounded-2xl border border-dashed border-slate-300">
<p>{{ t('admin.report.noData', { table: currentTable }) }}</p>
</div>
<div v-else class="overflow-x-auto rounded-2xl border border-slate-200 bg-white shadow-[0_12px_40px_-28px_rgba(15,23,42,0.5)]">
<table class="w-full text-left border-collapse">
<thead class="bg-gradient-to-r from-slate-100 to-cyan-50/80 backdrop-blur text-slate-600 text-xs uppercase tracking-wider sticky top-0">
<tr>
<th v-if="isChatLogsTable && showChatLogsSelection" class="px-4 py-4 font-semibold border-b border-slate-200 w-10">
<input
type="checkbox"
:checked="allReportRowsSelected"
@change="toggleAllReportRows"
class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500"
/>
</th>
<th
v-for="key in visibleReportKeys"
:key="key"
class="px-6 py-4 font-semibold border-b border-slate-200 whitespace-nowrap align-top relative"
:style="getColumnWidthStyle(key)"
:draggable="true"
@dragstart="onColumnDragStart(String(key))"
@dragover.prevent
@drop="onColumnDrop(String(key))"
>
<div class="flex flex-col gap-2 min-w-[120px]">
<button
@click="onReportHeaderClick(String(key))"
class="text-left hover:text-blue-700 transition-colors"
>
{{ key }} <span class="text-[10px] text-blue-600">{{ getHeaderSortMark(String(key)) }}</span>
</button>
<input
v-model="columnFilters[key]"
@input="handleFilterChange"
type="text"
class="w-full px-2 py-1 text-xs border border-slate-300 rounded focus:ring-1 focus:ring-sky-500 outline-none font-normal normal-case bg-white/95"
placeholder="Filter..."
/>
</div>
<span
class="absolute right-0 top-0 h-full w-1.5 cursor-col-resize select-none"
@mousedown="startResizeColumn(String(key), $event)"
></span>
</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 bg-white">
<tr v-for="(row, idx) in paginatedSortedTableData" :key="idx" class="odd:bg-white even:bg-slate-50/40 hover:bg-cyan-50/50 transition-colors">
<td v-if="isChatLogsTable && showChatLogsSelection" class="px-4 py-3 border-b border-slate-100">
<input
type="checkbox"
:checked="selectedReportRowIds.includes(getReportRowId(row))"
@change="toggleReportRowSelection(getReportRowId(row))"
class="w-4 h-4 rounded text-blue-600 focus:ring-blue-500"
/>
</td>
<td
v-for="key in visibleReportKeys"
:key="`cell-${idx}-${key}`"
class="px-6 py-3 text-sm text-slate-700 border-b border-slate-100 font-mono align-top"
:title="String(getReportCellValue(row, String(key)))"
:style="getReportCellDisplayStyle(String(key))"
>
<div :style="getReportCellInnerStyle()">
{{ getReportCellValue(row, String(key)) }}
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="tableData.length > 0" class="flex flex-col gap-3 rounded-2xl border border-slate-200 bg-white/80 px-4 py-3 md:flex-row md:items-center md:justify-between">
<div class="text-sm text-slate-600">
共 {{ reportTotalRows }} 条,当前第 {{ reportCurrentPage }} / {{ reportTotalPages }} 页
</div>
<div class="flex flex-wrap items-center gap-2">
<label class="flex items-center gap-2 text-xs text-slate-600">
<span>每页</span>
<span class="relative inline-flex items-center">
<select
v-model.number="reportPageSize"
class="appearance-none rounded-lg border border-slate-300 bg-white pl-2 pr-7 py-1 text-xs leading-5 outline-none focus:ring-1 focus:ring-sky-500"
>
<option v-for="size in reportPageSizeOptions" :key="`page-size-${size}`" :value="size">{{ size }}</option>
</select>
<svg class="pointer-events-none absolute right-2 h-3.5 w-3.5 text-slate-500" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd" />
</svg>
</span>
<span>条</span>
</label>
<button
@click="prevReportPage"
:disabled="reportCurrentPage <= 1"
class="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs text-slate-700 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed"
>
上一页
</button>
<button
v-for="btn in reportPageButtons"
:key="`report-page-btn-${btn}`"
:disabled="btn === -1"
@click="btn !== -1 && goToReportPage(btn)"
class="rounded-lg border px-2.5 py-1.5 text-xs"
:class="btn === -1
? 'border-transparent text-slate-400 cursor-default'
: btn === reportCurrentPage
? 'border-sky-600 bg-sky-600 text-white'
: 'border-slate-300 text-slate-700 hover:bg-slate-50'"
>
{{ btn === -1 ? '...' : btn }}
</button>
<button
@click="nextReportPage"
:disabled="reportCurrentPage >= reportTotalPages"
class="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs text-slate-700 hover:bg-slate-50 disabled:opacity-40 disabled:cursor-not-allowed"
>
下一页
</button>
</div>
</div>
<!-- Statistics Charts -->
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-slate-200 pt-10">
<h3 class="font-bold text-lg mb-6 text-slate-900">Usage Analytics</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-8">
<div class="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm">
<h4 class="text-sm font-bold text-slate-500 uppercase tracking-wider mb-4">Requests by User</h4>
<div class="space-y-3">
<div v-for="u in usageReport.by_user" :key="u.username" class="flex items-center justify-between p-3 bg-slate-50 rounded-xl">
<span class="font-medium text-slate-700">{{ u.username }}</span>
<span class="bg-blue-100 text-blue-700 text-xs font-bold px-2.5 py-1 rounded-full">{{ u.count }}</span>
</div>
</div>
</div>
<div class="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm">
<h4 class="text-sm font-bold text-slate-500 uppercase tracking-wider mb-4">Requests by Agent</h4>
<div class="space-y-3">
<div v-for="a in usageReport.by_agent" :key="a.agent" class="flex items-center justify-between p-3 bg-slate-50 rounded-xl">
<span class="font-medium text-slate-700">{{ a.agent }}</span>
<span class="bg-cyan-100 text-cyan-700 text-xs font-bold px-2.5 py-1 rounded-full">{{ a.count }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</section>
</main>
<!-- User Modal -->
<div v-if="showUserModal" class="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50 transition-opacity animate-fade-in">
<div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-8 transform transition-all scale-100">
<h3 class="text-xl font-bold text-gray-900 mb-6">{{ editingUser.id ? t('admin.user.editUser') : t('admin.user.createUser') }}</h3>
<div class="space-y-5">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.user.fields.realName') }}</label>
<input
v-model="editingUser.real_name"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-gray-50 focus:bg-white"
/>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.user.fields.employeeId') }}</label>
<input
v-model="editingUser.employee_id"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-gray-50 focus:bg-white"
/>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.user.fields.phone') }}</label>
<input
v-model="editingUser.phone_number"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-gray-50 focus:bg-white"
/>
</div>
<div class="space-y-1.5 col-span-1 md:col-span-2">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.user.fields.allowedAgents') }}</label>
<div class="grid grid-cols-2 gap-3 mt-2">
<label
v-for="agent in agents"
:key="agent.id"
class="flex items-center gap-2 p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
:class="editingUser.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input
type="checkbox"
:value="agent.id"
v-model="editingUser.agent_ids"
class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
>
<span class="text-sm font-medium text-gray-700">{{ agent.name }}</span>
</label>
</div>
<p v-if="agents.length === 0" class="text-sm text-gray-400 italic">{{ t('admin.user.fields.noAgents') }}</p>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.user.fields.username') }}</label>
<input
v-model="editingUser.username"
type="text"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-gray-50 focus:bg-white"
:disabled="!!editingUser.id"
/>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.user.fields.email') }}</label>
<input
v-model="editingUser.email"
type="email"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-gray-50 focus:bg-white"
/>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.user.fields.department') }}</label>
<select
v-model="editingUser.department"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-gray-50 focus:bg-white"
>
<option value="">{{ t('admin.user.allDepts') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.user.fields.role') }}</label>
<select
v-model="editingUser.role"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-gray-50 focus:bg-white"
>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">
{{ t('admin.user.fields.password') }} <span v-if="editingUser.id" class="text-gray-400 font-normal lowercase">{{ t('admin.user.fields.passwordHint') }}</span>
</label>
<input
v-model="editingUser.password"
type="password"
class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all shadow-sm bg-gray-50 focus:bg-white"
/>
</div>
</div>
<div class="flex justify-end gap-3 mt-8">
<button
class="px-5 py-2.5 text-gray-600 hover:bg-gray-100 rounded-xl text-sm font-medium transition-colors"
@click="showUserModal = false"
>
{{ t('admin.cancel') }}
</button>
<button
class="px-5 py-2.5 bg-blue-600 text-white rounded-xl hover:bg-blue-700 text-sm font-medium shadow-md shadow-blue-200 transition-all active:scale-95 disabled:opacity-70 disabled:cursor-not-allowed"
@click="saveUser"
:disabled="isSaving"
>
{{ isSaving ? t('admin.save') + '...' : t('admin.save') }}
</button>
</div>
</div>
</div>
<!-- Agent Test Modal -->
<div v-if="showAgentTestModal && testingAgent" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div class="bg-white rounded-2xl shadow-xl w-full max-w-3xl max-h-[90vh] flex flex-col animate-fade-in-up">
<div class="px-8 py-6 border-b border-gray-100 flex justify-between items-start">
<div>
<h3 class="text-lg font-bold text-gray-900">应用测试</h3>
<p class="text-sm text-gray-500 mt-1">应用:<span class="font-medium text-blue-600">{{ testingAgent.name }}</span></p>
</div>
<button @click="showAgentTestModal = false" class="p-2 hover:bg-gray-100 rounded-full text-gray-400 hover:text-gray-600 transition-colors">✕</button>
</div>
<div class="flex-1 overflow-y-auto p-8 space-y-5">
<div class="flex items-center justify-between">
<div class="text-sm text-gray-600">
<span v-if="agentTestResult?.tested_at">测试时间:{{ agentTestResult.tested_at }}</span>
</div>
<button
@click="runAgentTest()"
:disabled="isTestingAgent"
class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
>
{{ isTestingAgent ? '测试中...' : '重新测试' }}
</button>
</div>
<div v-if="isTestingAgent" class="text-sm text-gray-500">正在执行测试,请稍候...</div>
<template v-if="agentTestResult">
<div>
<div class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">请求地址</div>
<div class="p-3 rounded-lg bg-gray-50 border border-gray-200 text-sm font-mono break-all">{{ agentTestResult.request_url || '-' }}</div>
</div>
<div>
<div class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">输出信息</div>
<pre class="p-3 rounded-lg bg-gray-50 border border-gray-200 text-sm whitespace-pre-wrap break-all max-h-64 overflow-y-auto">{{ agentTestResult.output_info || '-' }}</pre>
</div>
<div>
<div class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">最终结果分析</div>
<div
class="p-3 rounded-lg border text-sm"
:class="agentTestResult.success ? 'bg-green-50 border-green-200 text-green-800' : 'bg-red-50 border-red-200 text-red-800'"
>
{{ agentTestResult.analysis }}
<span v-if="agentTestResult.http_status">(HTTP {{ agentTestResult.http_status }})</span>
</div>
</div>
</template>
</div>
</div>
</div>
<!-- Agent Permission Modal -->
<div v-if="showAgentPermissionModal && selectedAgentForPermissions" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div class="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col animate-fade-in-up">
<div class="px-8 py-6 border-b border-gray-100 flex justify-between items-center">
<div>
<h3 class="text-lg font-bold text-gray-900">{{ t('admin.perm.agentModal.title') }}</h3>
<p class="text-sm text-gray-500">{{ t('admin.perm.agentModal.agent') }} <span class="font-medium text-blue-600">{{ selectedAgentForPermissions.name }}</span></p>
</div>
<button @click="showAgentPermissionModal = false" class="p-2 hover:bg-gray-100 rounded-full text-gray-400 hover:text-gray-600 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div class="flex-1 overflow-y-auto p-8">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div
v-for="user in activeUsers"
:key="user.id"
class="flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer"
:class="agentPermissionUserIds.includes(user.id) ? 'border-blue-200 bg-blue-50/50' : 'border-gray-200 hover:bg-gray-50'"
@click="toggleAgentPermission(user.id)"
>
<div
class="w-5 h-5 rounded border flex items-center justify-center transition-colors"
:class="agentPermissionUserIds.includes(user.id) ? 'bg-blue-600 border-blue-600' : 'bg-white border-gray-300'"
>
<svg v-if="agentPermissionUserIds.includes(user.id)" xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5 text-white" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
</svg>
</div>
<div>
<div class="font-medium text-gray-900 text-sm">{{ user.username }}</div>
<div class="text-xs text-gray-500">{{ user.real_name || user.email }}</div>
</div>
</div>
</div>
</div>
<div class="px-8 py-6 border-t border-gray-100 bg-gray-50 rounded-b-2xl flex justify-end gap-3">
<button
@click="showAgentPermissionModal = false"
class="px-5 py-2.5 text-gray-600 font-medium hover:bg-gray-200 rounded-xl transition-colors"
>
{{ t('admin.cancel') }}
</button>
<button
@click="saveAgentPermissions"
:disabled="isSaving"
class="px-6 py-2.5 bg-blue-600 text-white font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-lg shadow-blue-200 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
>
<div v-if="isSaving" class="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></div>
{{ t('admin.perm.agentModal.save') }}
</button>
</div>
</div>
</div>
<!-- Batch Edit User Modal -->
<div v-if="showBatchEditModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div class="bg-white rounded-2xl shadow-xl w-full max-w-md animate-fade-in-up">
<div class="px-8 py-6 border-b border-gray-100">
<h3 class="text-lg font-bold text-gray-900">{{ t('admin.batchEdit.title') }}</h3>
<p class="text-sm text-gray-500">{{ t('admin.batchEdit.selected', { count: selectedUserIds.length }) }}</p>
</div>
<div class="p-8 space-y-4">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.batchEdit.fields.dept') }}</label>
<select v-model="batchEditForm.department" class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none bg-gray-50 focus:bg-white">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option v-for="d in departments" :key="d.id" :value="d.name">{{ d.name }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.batchEdit.fields.role') }}</label>
<select v-model="batchEditForm.role" class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none bg-gray-50 focus:bg-white">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="user">{{ t('admin.role.user') }}</option>
<option value="admin">{{ t('admin.role.admin') }}</option>
</select>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.batchEdit.fields.status') }}</label>
<select v-model="batchEditForm.status" class="w-full border-gray-200 rounded-xl px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none bg-gray-50 focus:bg-white">
<option value="">{{ t('admin.batchEdit.fields.keepUnchanged') }}</option>
<option value="active">{{ t('admin.status.active') }}</option>
<option value="disabled">{{ t('admin.status.disabled') }}</option>
</select>
</div>
</div>
<div class="px-8 py-6 border-t border-gray-100 bg-gray-50 rounded-b-2xl flex justify-end gap-3">
<button @click="showBatchEditModal = false" class="px-5 py-2.5 text-gray-600 font-medium hover:bg-gray-200 rounded-xl transition-colors">{{ t('admin.cancel') }}</button>
<button @click="submitBatchEdit" :disabled="isSaving" class="px-6 py-2.5 bg-blue-600 text-white font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-lg shadow-blue-200 disabled:opacity-50">
{{ isSaving ? t('admin.save') + '...' : t('admin.batchEdit.update') }}
</button>
</div>
</div>
</div>
<!-- Batch Permission Modal -->
<div v-if="showBatchPermissionModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
<div class="bg-white rounded-2xl shadow-xl w-full max-w-lg animate-fade-in-up">
<div class="px-8 py-6 border-b border-gray-100">
<h3 class="text-lg font-bold text-gray-900">{{ t('admin.perm.batchModal.title') }}</h3>
<p class="text-sm text-gray-500">{{ t('admin.perm.batchModal.selected', { count: selectedUserIds.length }) }}</p>
</div>
<div class="p-8 space-y-6">
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.perm.batchModal.action') }}</label>
<div class="flex gap-4">
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" v-model="batchPermissionForm.action" value="add" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.add') }}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" v-model="batchPermissionForm.action" value="remove" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.remove') }}</span>
</label>
<label class="flex items-center gap-2 cursor-pointer">
<input type="radio" v-model="batchPermissionForm.action" value="set" class="text-blue-600 focus:ring-blue-500" />
<span class="text-sm">{{ t('admin.perm.batchModal.set') }}</span>
</label>
</div>
</div>
<div class="space-y-1.5">
<label class="block text-xs font-semibold text-gray-500 uppercase tracking-wider">{{ t('admin.perm.batchModal.selectAgents') }}</label>
<div class="grid grid-cols-2 gap-3 max-h-60 overflow-y-auto p-1">
<label
v-for="agent in agents"
:key="agent.id"
class="flex items-center gap-2 p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
:class="batchPermissionForm.agent_ids.includes(agent.id) ? 'border-blue-500 bg-blue-50' : ''"
>
<input
type="checkbox"
:value="agent.id"
v-model="batchPermissionForm.agent_ids"
class="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
>
<span class="text-sm font-medium text-gray-700">{{ agent.name }}</span>
</label>
</div>
</div>
</div>
<div class="px-8 py-6 border-t border-gray-100 bg-gray-50 rounded-b-2xl flex justify-end gap-3">
<button @click="showBatchPermissionModal = false" class="px-5 py-2.5 text-gray-600 font-medium hover:bg-gray-200 rounded-xl transition-colors">{{ t('admin.cancel') }}</button>
<button @click="submitBatchPermission" :disabled="isSaving" class="px-6 py-2.5 bg-blue-600 text-white font-medium rounded-xl hover:bg-blue-700 transition-colors shadow-lg shadow-blue-200 disabled:opacity-50">
{{ isSaving ? t('admin.save') + '...' : t('admin.perm.batchModal.apply') }}
</button>
</div>
</div>
</div>
<!-- Department Management Modal -->
<div v-if="isManagingDepts" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-fade-in">
<div class="bg-white rounded-2xl shadow-xl w-full max-w-lg p-6 animate-fade-in-up">
<h3 class="text-xl font-bold text-gray-900 mb-6">{{ t('admin.user.manageDepts') }}</h3>
<div class="flex gap-2 mb-6">
<input
v-model="editingDept.name"
:placeholder="t('admin.dept.fields.name')"
class="flex-1 px-4 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none"
@keyup.enter="saveDepartment"
/>
<button
@click="saveDepartment"
class="px-4 py-2 bg-blue-600 text-white rounded-xl text-sm font-medium hover:bg-blue-700 transition-colors shadow-md shadow-blue-200"
>
{{ t('admin.add') }}
</button>
</div>
<div class="max-h-[50vh] overflow-y-auto border border-gray-100 rounded-xl divide-y divide-gray-50 bg-gray-50/50">
<div v-if="departments.length === 0" class="p-8 text-center text-gray-400 text-sm">{{ t('admin.dept.noDepts') }}</div>
<div v-for="d in departments" :key="d.id" class="p-3 flex justify-between items-center hover:bg-white transition-colors group">
<span class="text-sm font-medium text-gray-700 ml-2">{{ d.name }}</span>
<button
@click="deleteDepartment(d.id)"
class="text-gray-400 hover:text-red-500 hover:bg-red-50 p-1.5 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
:title="t('admin.delete')"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
<div class="mt-6 flex justify-end">
<button
@click="isManagingDepts = false"
class="px-5 py-2.5 text-gray-600 hover:bg-gray-100 rounded-xl text-sm font-medium transition-colors"
>
{{ t('admin.close') }}
</button>
</div>
</div>
</div>
</div>
</template>