admin-resource.component.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. import { CommonModule } from '@angular/common';
  2. import { ChangeDetectionStrategy, Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
  3. import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
  4. import { FormsModule } from '@angular/forms';
  5. import { ActivatedRoute } from '@angular/router';
  6. import { ChevronLeft, ChevronRight, Eye, KeyRound, LoaderCircle, LucideAngularModule, Pencil, Plus, RefreshCw, Search, Trash2, X } from 'lucide-angular';
  7. import { AdminClassSchema, AdminFieldSchema, ResourcePage } from '../admin.models';
  8. import { CloudFunctionsService } from '../cloud-functions.service';
  9. @Component({
  10. selector: 'app-admin-resource',
  11. standalone: true,
  12. imports: [CommonModule, FormsModule, LucideAngularModule],
  13. templateUrl: './admin-resource.component.html',
  14. styleUrl: './admin-resource.component.scss',
  15. changeDetection: ChangeDetectionStrategy.OnPush,
  16. })
  17. export class AdminResourceComponent implements OnInit {
  18. readonly className = signal('');
  19. readonly schema = signal<AdminClassSchema | null>(null);
  20. readonly page = signal<ResourcePage | null>(null);
  21. readonly loading = signal(true);
  22. readonly saving = signal(false);
  23. readonly resettingPassword = signal(false);
  24. readonly error = signal('');
  25. readonly search = signal('');
  26. readonly editorOpen = signal(false);
  27. readonly draftId = signal('');
  28. readonly draft = signal<Record<string, unknown>>({});
  29. readonly fieldErrors = signal<Record<string, string>>({});
  30. readonly fieldInputs = signal<Record<string, string>>({});
  31. readonly newPassword = signal('');
  32. readonly confirmPassword = signal('');
  33. readonly passwordMessage = signal('');
  34. readonly passwordError = signal('');
  35. readonly createUsername = signal('');
  36. readonly createPassword = signal('');
  37. readonly createConfirmPassword = signal('');
  38. readonly createDisplayName = signal('');
  39. readonly createMobile = signal('');
  40. readonly createInviteUsername = signal('');
  41. readonly createUserError = signal('');
  42. readonly userGroups = signal<Record<string, unknown>[]>([]);
  43. readonly selectedUserGroupId = signal(0);
  44. readonly userActionReason = signal('');
  45. readonly userActionError = signal('');
  46. readonly userActionMessage = signal('');
  47. readonly updatingUser = signal(false);
  48. readonly selectedContentStatus = signal(0);
  49. readonly targetContentNodeId = signal(0);
  50. readonly updatingContent = signal(false);
  51. readonly contentActionError = signal('');
  52. readonly contentActionMessage = signal('');
  53. readonly targetNodeParentId = signal(0);
  54. readonly updatingNode = signal(false);
  55. readonly nodeActionError = signal('');
  56. readonly nodeActionMessage = signal('');
  57. readonly targetSpecialParentId = signal(0);
  58. readonly updatingSpecial = signal(false);
  59. readonly specialActionError = signal('');
  60. readonly specialActionMessage = signal('');
  61. readonly selectedGuestbookStatus = signal(99);
  62. readonly guestbookReplyTitle = signal('');
  63. readonly guestbookReplyContent = signal('');
  64. readonly updatingGuestbook = signal(false);
  65. readonly guestbookActionError = signal('');
  66. readonly guestbookActionMessage = signal('');
  67. readonly guestCategoryType = signal(0);
  68. readonly targetGuestCategoryParentId = signal(0);
  69. readonly targetBarCategoryId = signal(0);
  70. readonly updatingBar = signal(false);
  71. readonly barActionError = signal('');
  72. readonly barActionMessage = signal('');
  73. readonly targetExamClassParentId = signal(0);
  74. readonly examClassType = signal(1);
  75. readonly examClassOrder = signal(0);
  76. readonly targetExamPointParentId = signal(0);
  77. readonly examPointOrder = signal(0);
  78. readonly targetKnowledgeClassId = signal(0);
  79. readonly targetKnowledgeParentId = signal(0);
  80. readonly knowledgeOrder = signal(0);
  81. readonly targetTeacherClassId = signal(0);
  82. readonly targetDictionaryCategoryId = signal(0);
  83. readonly dictionaryCategories = signal<Record<string, unknown>[]>([]);
  84. readonly updatingDictionary = signal(false);
  85. readonly targetGradeCategoryId = signal(0);
  86. readonly targetGradeParentId = signal(0);
  87. readonly filterGradeCategoryId = signal(0);
  88. readonly filterGradeParentId = signal(0);
  89. readonly gradeCategories = signal<Record<string, unknown>[]>([]);
  90. readonly updatingGrade = signal(false);
  91. readonly updatingCurrency = signal(false);
  92. readonly selectedIds = signal<string[]>([]);
  93. readonly bulkError = signal('');
  94. readonly bulkMessage = signal('');
  95. readonly icons = { ChevronLeft, ChevronRight, Eye, KeyRound, LoaderCircle, Pencil, Plus, RefreshCw, Search, Trash2, X };
  96. readonly columns = computed(() => {
  97. const fields = this.schema()?.fields ?? [];
  98. const preferred = ['objectId', 'name', 'title', 'categoryname', 'dicname', 'cateName', 'gradeName', 'cClassName', 'testPoint', 'kName', 'tname', 'username', 'realName', 'mobile', 'sourceKey', 'status', 'createdAt', 'updatedAt'];
  99. const rank = (name: string): number => { const index = preferred.indexOf(name); return index < 0 ? preferred.length : index; };
  100. return fields.map((field, index) => ({ field, index })).sort((a, b) => rank(a.field.name) - rank(b.field.name) || a.index - b.index).map(({ field }) => field).slice(0, 7);
  101. });
  102. readonly pageCount = computed(() => Math.max(1, Math.ceil((this.page()?.total ?? 0) / (this.page()?.pageSize || 20))));
  103. readonly bulkEnabled = computed(() => ['_User', 'CommonModel', 'Node', 'Special', 'Guestbook', 'GuestBar', 'Datadiccategory', 'Datadic', 'GradeCate', 'Grade', 'Currency'].includes(this.className()));
  104. readonly allPageSelected = computed(() => {
  105. const ids = (this.page()?.results || []).map((row) => String(row['objectId'] || '')).filter(Boolean);
  106. return Boolean(ids.length) && ids.every((id) => this.selectedIds().includes(id));
  107. });
  108. private readonly functions = inject(CloudFunctionsService);
  109. private readonly route = inject(ActivatedRoute);
  110. private readonly destroyRef = inject(DestroyRef);
  111. ngOnInit(): void {
  112. this.route.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
  113. this.className.set(params.get('className') ?? '');
  114. this.search.set('');
  115. this.filterGradeCategoryId.set(0); this.filterGradeParentId.set(0);
  116. void this.load(1, true);
  117. });
  118. }
  119. async load(pageNumber = this.page()?.page ?? 1, reloadSchema = false): Promise<void> {
  120. this.loading.set(true); this.error.set(''); this.selectedIds.set([]); this.bulkError.set(''); this.bulkMessage.set('');
  121. try {
  122. if (reloadSchema || !this.schema()) this.schema.set(await this.functions.admin<AdminClassSchema>('schema', { className: this.className() }));
  123. if (this.className() === 'Grade' && reloadSchema) { await this.loadGradeCategories(); if (!this.filterGradeCategoryId() && this.gradeCategories().length) this.filterGradeCategoryId.set(this.gradeCategoryIdOf(this.gradeCategories()[0])); }
  124. const pageOperation = this.className() === 'Grade' && this.filterGradeCategoryId() > 0 ? 'gradeOptions' : 'list';
  125. const pagePayload: Record<string, unknown> = { className: this.className(), page: pageNumber, pageSize: 20, search: this.search().trim() };
  126. if (pageOperation === 'gradeOptions') { pagePayload['categoryId'] = this.filterGradeCategoryId(); pagePayload['parentId'] = this.filterGradeParentId(); }
  127. this.page.set(await this.functions.admin<ResourcePage>(pageOperation, pagePayload));
  128. if (this.className() === '_User' && reloadSchema) await this.loadUserGroups();
  129. if (this.className() === 'Datadic' && reloadSchema) await this.loadDictionaryCategories();
  130. } catch (error) { this.error.set(error instanceof Error ? error.message : '数据加载失败'); }
  131. finally { this.loading.set(false); }
  132. }
  133. openCreate(): void { this.draftId.set(''); this.draft.set({}); this.fieldErrors.set({}); this.fieldInputs.set({}); this.resetPasswordFields(); this.resetCreateUserFields(); this.resetUserActions(); this.resetContentActions(); this.resetNodeActions(); this.resetSpecialActions(); this.resetGuestbookActions(); this.resetGuestCategoryActions(); this.resetBarActions(); this.resetExamClassActions(); this.resetExamPointActions(); this.resetKnowledgeActions(); this.resetTeacherActions(); this.resetDictionaryActions(); this.resetGradeActions(); this.editorOpen.set(true); }
  134. async openEdit(row: Record<string, unknown>): Promise<void> {
  135. const objectId = String(row['objectId'] ?? '');
  136. this.error.set('');
  137. try {
  138. const detail = await this.functions.admin<Record<string, unknown>>('get', { className: this.className(), objectId });
  139. this.draftId.set(objectId); this.draft.set(detail); this.fieldErrors.set({}); this.fieldInputs.set({}); this.resetPasswordFields(); this.resetCreateUserFields(); this.resetUserActions(detail); this.resetContentActions(detail); this.resetNodeActions(detail); this.resetSpecialActions(detail); this.resetGuestbookActions(detail); this.resetGuestCategoryActions(detail); this.resetBarActions(detail); this.resetExamClassActions(detail); this.resetExamPointActions(detail); this.resetKnowledgeActions(detail); this.resetTeacherActions(detail); this.resetDictionaryActions(detail); this.resetGradeActions(detail); this.editorOpen.set(true);
  140. if (this.className() === '_User') await this.loadUserGroups();
  141. } catch (error) { this.error.set(error instanceof Error ? error.message : '详情加载失败'); }
  142. }
  143. closeEditor(): void { this.editorOpen.set(false); this.draft.set({}); this.draftId.set(''); this.fieldErrors.set({}); this.fieldInputs.set({}); this.resetPasswordFields(); this.resetCreateUserFields(); this.resetUserActions(); this.resetContentActions(); this.resetNodeActions(); this.resetSpecialActions(); this.resetGuestbookActions(); this.resetGuestCategoryActions(); this.resetBarActions(); this.resetExamClassActions(); this.resetExamPointActions(); this.resetKnowledgeActions(); this.resetTeacherActions(); this.resetDictionaryActions(); this.resetGradeActions(); }
  144. setField(field: AdminFieldSchema, raw: unknown): void {
  145. let value = raw;
  146. if (field.type === 'Number') value = raw === '' ? null : Number(raw);
  147. if (field.type === 'Pointer') value = raw ? { __type: 'Pointer', className: field.targetClass, objectId: String(raw) } : null;
  148. if ((field.type === 'Object' || field.type === 'Array') && typeof raw === 'string') {
  149. this.fieldInputs.update((current) => ({ ...current, [field.name]: raw }));
  150. try {
  151. value = raw.trim() ? JSON.parse(raw) : field.type === 'Array' ? [] : {};
  152. const valid = field.type === 'Array' ? Array.isArray(value) : Boolean(value) && typeof value === 'object' && !Array.isArray(value);
  153. if (!valid) throw new Error();
  154. this.fieldErrors.update((current) => { const next = { ...current }; delete next[field.name]; return next; });
  155. } catch {
  156. this.fieldErrors.update((current) => ({ ...current, [field.name]: field.type === 'Array' ? '请输入有效的 JSON 数组' : '请输入有效的 JSON 对象' }));
  157. return;
  158. }
  159. }
  160. this.draft.update((current) => ({ ...current, [field.name]: value }));
  161. }
  162. inputValue(field: AdminFieldSchema): string | number {
  163. const value = this.draft()[field.name];
  164. if (field.type === 'Pointer') return String((value as { objectId?: string } | null)?.objectId ?? '');
  165. if (field.type === 'Date') return String((value as { iso?: string } | string | null)?.hasOwnProperty?.('iso') ? (value as { iso: string }).iso.slice(0, 16) : String(value ?? '').slice(0, 16));
  166. if (field.type === 'Object' || field.type === 'Array') return this.fieldInputs()[field.name] ?? (value == null ? '' : JSON.stringify(value, null, 2));
  167. return typeof value === 'number' ? value : String(value ?? '');
  168. }
  169. async save(): Promise<void> {
  170. const invalidFields = Object.keys(this.fieldErrors());
  171. if (invalidFields.length) { this.error.set(`请先修正字段格式:${invalidFields.join('、')}`); return; }
  172. this.saving.set(true); this.error.set('');
  173. try {
  174. const operation = this.className() === 'Group' ? 'saveGroup'
  175. : this.className() === 'Node' ? 'saveNode'
  176. : this.className() === 'Special' ? 'saveSpecial'
  177. : this.className() === 'Model' ? 'saveModelMetadata'
  178. : this.className() === 'ModelField' ? 'saveModelFieldMetadata'
  179. : this.className() === 'Guestbook' ? 'saveGuestbook'
  180. : this.className() === 'Guestcate' ? 'saveGuestCategory'
  181. : this.className() === 'ExamClass' ? 'saveExamClass'
  182. : this.className() === 'ExamPoint' ? 'saveExamPoint'
  183. : this.className() === 'QuestionsKnowledge' ? 'saveKnowledge'
  184. : this.className() === 'ExTeacher' ? 'saveExamTeacher'
  185. : this.className() === 'Datadiccategory' ? 'saveDictionaryCategory'
  186. : this.className() === 'Datadic' ? 'saveDictionaryItem'
  187. : this.className() === 'GradeCate' ? 'saveGradeCategory'
  188. : this.className() === 'Grade' ? 'saveGradeOption'
  189. : this.className() === 'Currency' ? 'saveCurrency' : 'save';
  190. const payload: Record<string, unknown> = { className: this.className(), objectId: this.draftId() || undefined, fields: this.draft() };
  191. if (this.className() === 'Node') payload['parentId'] = this.targetNodeParentId();
  192. if (this.className() === 'Special') payload['pid'] = this.targetSpecialParentId();
  193. if (this.className() === 'Guestcate') { payload['gtype'] = this.guestCategoryType(); payload['parentId'] = this.targetGuestCategoryParentId(); }
  194. if (this.className() === 'ExamClass') { payload['parentId'] = this.targetExamClassParentId(); payload['classType'] = this.examClassType(); payload['orderId'] = this.examClassOrder(); }
  195. if (this.className() === 'ExamPoint') { payload['parentId'] = this.targetExamPointParentId(); payload['orderId'] = this.examPointOrder(); }
  196. if (this.className() === 'QuestionsKnowledge') { payload['classId'] = this.targetKnowledgeClassId(); payload['parentId'] = this.targetKnowledgeParentId(); payload['orderId'] = this.knowledgeOrder(); }
  197. if (this.className() === 'ExTeacher') payload['classId'] = this.targetTeacherClassId();
  198. if (this.className() === 'Datadic') payload['categoryId'] = this.targetDictionaryCategoryId();
  199. if (this.className() === 'Grade') { payload['categoryId'] = this.targetGradeCategoryId(); payload['parentId'] = this.targetGradeParentId(); }
  200. await this.functions.admin(operation, payload);
  201. this.closeEditor(); await this.load();
  202. } catch (error) { this.error.set(error instanceof Error ? error.message : '保存失败'); }
  203. finally { this.saving.set(false); }
  204. }
  205. async submitEditor(): Promise<void> {
  206. if (this.className() === '_User' && !this.draftId()) await this.createUser();
  207. else await this.save();
  208. }
  209. async createUser(): Promise<void> {
  210. const username = this.createUsername().trim();
  211. const password = this.createPassword();
  212. this.createUserError.set('');
  213. if (this.className() !== '_User' || this.draftId()) { this.createUserError.set('只能从用户管理的新建入口开户'); return; }
  214. if (username.length < 3 || username.length > 64) { this.createUserError.set('账号长度应为 3 至 64 位'); return; }
  215. if (password.length < 8 || password.length > 72) { this.createUserError.set('密码长度应为 8 至 72 位'); return; }
  216. if (password !== this.createConfirmPassword()) { this.createUserError.set('两次输入的密码不一致'); return; }
  217. const payload: Record<string, unknown> = { username, password };
  218. const displayName = this.createDisplayName().trim();
  219. const mobile = this.createMobile().trim();
  220. const inviteUsername = this.createInviteUsername().trim();
  221. if (displayName) payload['displayName'] = displayName;
  222. if (mobile) payload['mobile'] = mobile;
  223. if (inviteUsername) payload['inviteUsername'] = inviteUsername;
  224. this.saving.set(true); this.error.set('');
  225. try {
  226. await this.functions.admin('createUser', payload);
  227. this.closeEditor(); await this.load();
  228. } catch (error) { this.createUserError.set(error instanceof Error ? error.message : '用户开户失败'); }
  229. finally { this.saving.set(false); }
  230. }
  231. async resetPassword(): Promise<void> {
  232. this.passwordError.set(''); this.passwordMessage.set('');
  233. if (this.className() !== '_User' || !this.draftId()) { this.passwordError.set('只能重置现有用户密码'); return; }
  234. if (this.newPassword().length < 8) { this.passwordError.set('新密码至少 8 位'); return; }
  235. if (this.newPassword() !== this.confirmPassword()) { this.passwordError.set('两次输入的密码不一致'); return; }
  236. this.resettingPassword.set(true);
  237. try {
  238. await this.functions.admin('resetPassword', { className: '_User', objectId: this.draftId(), newPassword: this.newPassword() });
  239. this.newPassword.set(''); this.confirmPassword.set(''); this.passwordMessage.set('密码已安全重置');
  240. } catch (error) { this.passwordError.set(error instanceof Error ? error.message : '密码重置失败'); }
  241. finally { this.resettingPassword.set(false); }
  242. }
  243. async setUserDisabled(disabled: boolean): Promise<void> {
  244. this.userActionError.set(''); this.userActionMessage.set('');
  245. if (this.className() !== '_User' || !this.draftId()) { this.userActionError.set('只能管理现有用户状态'); return; }
  246. if (disabled && !confirm('确认停用该账号并撤销其全部登录会话?')) return;
  247. this.updatingUser.set(true);
  248. try {
  249. const result = await this.functions.admin<{ results: Record<string, unknown>[]; revokedSessions: number }>('userBatch', {
  250. className: '_User', action: disabled ? 'lock' : 'unlock', objectIds: [this.draftId()], reason: this.userActionReason().trim(),
  251. });
  252. if (result.results?.[0]) this.draft.set(result.results[0]);
  253. this.userActionMessage.set(disabled ? `账号已停用,撤销 ${result.revokedSessions || 0} 个会话` : '账号已恢复使用');
  254. await this.load();
  255. } catch (error) { this.userActionError.set(error instanceof Error ? error.message : '账号状态更新失败'); }
  256. finally { this.updatingUser.set(false); }
  257. }
  258. async moveUserGroup(): Promise<void> {
  259. this.userActionError.set(''); this.userActionMessage.set('');
  260. const groupId = this.selectedUserGroupId();
  261. if (this.className() !== '_User' || !this.draftId() || !Number.isInteger(groupId) || groupId < 1) { this.userActionError.set('请选择有效用户组'); return; }
  262. this.updatingUser.set(true);
  263. try {
  264. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('userBatch', { className: '_User', action: 'move', objectIds: [this.draftId()], groupId });
  265. if (result.results?.[0]) this.draft.set(result.results[0]);
  266. this.userActionMessage.set(`已移动到用户组 ${groupId}`);
  267. await this.load();
  268. } catch (error) { this.userActionError.set(error instanceof Error ? error.message : '用户组更新失败'); }
  269. finally { this.updatingUser.set(false); }
  270. }
  271. async applyContentAction(action: 'status' | 'recycle' | 'recover' | 'move'): Promise<void> {
  272. this.contentActionError.set(''); this.contentActionMessage.set('');
  273. if (this.className() !== 'CommonModel' || !this.draftId()) { this.contentActionError.set('只能管理现有内容'); return; }
  274. if (action === 'recycle' && !confirm('确认将该内容移入回收站?')) return;
  275. const payload: Record<string, unknown> = { className: 'CommonModel', action, objectIds: [this.draftId()] };
  276. if (action === 'status') {
  277. const status = this.selectedContentStatus();
  278. if (![-3, -1, 0, 99].includes(status)) { this.contentActionError.set('请选择有效内容状态'); return; }
  279. payload['status'] = status;
  280. }
  281. if (action === 'move') {
  282. const nodeId = this.targetContentNodeId();
  283. if (!Number.isInteger(nodeId) || nodeId < 1) { this.contentActionError.set('请输入有效目标节点 ID'); return; }
  284. payload['nodeId'] = nodeId;
  285. }
  286. this.updatingContent.set(true);
  287. try {
  288. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('contentBatch', payload);
  289. if (result.results?.[0]) {
  290. this.draft.set(result.results[0]);
  291. this.selectedContentStatus.set(Number(result.results[0]['status']) || 0);
  292. this.targetContentNodeId.set(Number(result.results[0]['nodeId']) || 0);
  293. }
  294. const messages = { status: `内容状态已更新为${this.contentStatusLabel(this.selectedContentStatus())}`, recycle: '内容已移入回收站', recover: '内容已恢复为待审核', move: `内容已移动到节点 ${this.targetContentNodeId()}` };
  295. this.contentActionMessage.set(messages[action]);
  296. await this.load();
  297. } catch (error) { this.contentActionError.set(error instanceof Error ? error.message : '内容操作失败'); }
  298. finally { this.updatingContent.set(false); }
  299. }
  300. toggleSelection(objectId: string, selected: boolean): void {
  301. this.selectedIds.update((current) => selected ? [...new Set([...current, objectId])] : current.filter((id) => id !== objectId));
  302. }
  303. togglePageSelection(selected: boolean): void {
  304. const pageIds = (this.page()?.results || []).map((row) => String(row['objectId'] || '')).filter(Boolean);
  305. this.selectedIds.set(selected ? pageIds : []);
  306. }
  307. isSelected(objectId: unknown): boolean { return this.selectedIds().includes(String(objectId || '')); }
  308. async applyBulkUserAction(action: 'lock' | 'unlock' | 'move'): Promise<void> {
  309. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  310. if (this.className() !== '_User' || !objectIds.length) { this.bulkError.set('请先选择用户'); return; }
  311. if (action === 'lock' && !confirm(`确认停用选中的 ${objectIds.length} 个账号并撤销全部会话?`)) return;
  312. const payload: Record<string, unknown> = { className: '_User', action, objectIds };
  313. if (action === 'move') {
  314. const groupId = this.selectedUserGroupId();
  315. if (!Number.isInteger(groupId) || groupId < 1) { this.bulkError.set('请选择有效用户组'); return; }
  316. payload['groupId'] = groupId;
  317. } else payload['reason'] = this.userActionReason().trim();
  318. this.updatingUser.set(true);
  319. try {
  320. const result = await this.functions.admin<{ updated: number; revokedSessions: number }>('userBatch', payload);
  321. const message = action === 'lock' ? `已停用 ${result.updated} 个账号并撤销 ${result.revokedSessions || 0} 个会话` : action === 'unlock' ? `已解锁 ${result.updated} 个账号` : `已移动 ${result.updated} 个用户`;
  322. await this.load(); this.bulkMessage.set(message);
  323. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量用户操作失败'); }
  324. finally { this.updatingUser.set(false); }
  325. }
  326. async applyBulkContentAction(action: 'status' | 'recycle' | 'recover' | 'move'): Promise<void> {
  327. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  328. if (this.className() !== 'CommonModel' || !objectIds.length) { this.bulkError.set('请先选择内容'); return; }
  329. if (action === 'recycle' && !confirm(`确认将选中的 ${objectIds.length} 条内容移入回收站?`)) return;
  330. const payload: Record<string, unknown> = { className: 'CommonModel', action, objectIds };
  331. if (action === 'status') {
  332. const status = this.selectedContentStatus();
  333. if (![-3, -1, 0, 99].includes(status)) { this.bulkError.set('请选择有效内容状态'); return; }
  334. payload['status'] = status;
  335. }
  336. if (action === 'move') {
  337. const nodeId = this.targetContentNodeId();
  338. if (!Number.isInteger(nodeId) || nodeId < 1) { this.bulkError.set('请输入有效目标节点 ID'); return; }
  339. payload['nodeId'] = nodeId;
  340. }
  341. this.updatingContent.set(true);
  342. try {
  343. const result = await this.functions.admin<{ updated: number }>('contentBatch', payload);
  344. const message = `已处理 ${result.updated} 条内容`; await this.load(); this.bulkMessage.set(message);
  345. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量内容操作失败'); }
  346. finally { this.updatingContent.set(false); }
  347. }
  348. async applyNodeAction(action: 'recycle' | 'recover' | 'move'): Promise<void> {
  349. this.nodeActionError.set(''); this.nodeActionMessage.set('');
  350. if (this.className() !== 'Node' || !this.draftId()) { this.nodeActionError.set('只能管理现有栏目'); return; }
  351. if (action === 'recycle' && !confirm('确认将该栏目移入回收站?')) return;
  352. const payload: Record<string, unknown> = { className: 'Node', action, objectIds: [this.draftId()] };
  353. if (action === 'move') {
  354. const parentId = this.targetNodeParentId();
  355. if (!Number.isInteger(parentId) || parentId < 0) { this.nodeActionError.set('请输入有效父节点 ID,顶级栏目填 0'); return; }
  356. payload['parentId'] = parentId;
  357. }
  358. this.updatingNode.set(true);
  359. try {
  360. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('nodeBatch', payload);
  361. if (result.results?.[0]) { this.draft.set(result.results[0]); this.targetNodeParentId.set(Number(result.results[0]['parentId']) || 0); }
  362. this.nodeActionMessage.set(action === 'recycle' ? '栏目已移入回收站' : action === 'recover' ? '栏目已恢复' : `栏目已移动到父节点 ${this.targetNodeParentId()}`);
  363. await this.load();
  364. } catch (error) { this.nodeActionError.set(error instanceof Error ? error.message : '栏目操作失败'); }
  365. finally { this.updatingNode.set(false); }
  366. }
  367. async applyBulkNodeAction(action: 'recycle' | 'recover' | 'move'): Promise<void> {
  368. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  369. if (this.className() !== 'Node' || !objectIds.length) { this.bulkError.set('请先选择栏目'); return; }
  370. if (action === 'recycle' && !confirm(`确认将选中的 ${objectIds.length} 个栏目移入回收站?`)) return;
  371. const payload: Record<string, unknown> = { className: 'Node', action, objectIds };
  372. if (action === 'move') {
  373. const parentId = this.targetNodeParentId();
  374. if (!Number.isInteger(parentId) || parentId < 0) { this.bulkError.set('请输入有效父节点 ID,顶级栏目填 0'); return; }
  375. payload['parentId'] = parentId;
  376. }
  377. this.updatingNode.set(true);
  378. try {
  379. const result = await this.functions.admin<{ updated: number }>('nodeBatch', payload);
  380. await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 个栏目`);
  381. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量栏目操作失败'); }
  382. finally { this.updatingNode.set(false); }
  383. }
  384. async moveSpecial(): Promise<void> {
  385. this.specialActionError.set(''); this.specialActionMessage.set('');
  386. const pid = this.targetSpecialParentId();
  387. if (this.className() !== 'Special' || !this.draftId() || !Number.isInteger(pid) || pid < 0) { this.specialActionError.set('请输入有效父专题 ID,顶级专题填 0'); return; }
  388. this.updatingSpecial.set(true);
  389. try {
  390. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('specialBatch', { className: 'Special', action: 'move', objectIds: [this.draftId()], pid });
  391. if (result.results?.[0]) { this.draft.set(result.results[0]); this.targetSpecialParentId.set(Number(result.results[0]['pid']) || 0); }
  392. this.specialActionMessage.set(`专题已移动到父专题 ${pid}`); await this.load();
  393. } catch (error) { this.specialActionError.set(error instanceof Error ? error.message : '专题移动失败'); }
  394. finally { this.updatingSpecial.set(false); }
  395. }
  396. async applyBulkSpecialMove(): Promise<void> {
  397. const objectIds = this.selectedIds(); const pid = this.targetSpecialParentId(); this.bulkError.set(''); this.bulkMessage.set('');
  398. if (this.className() !== 'Special' || !objectIds.length) { this.bulkError.set('请先选择专题'); return; }
  399. if (!Number.isInteger(pid) || pid < 0) { this.bulkError.set('请输入有效父专题 ID,顶级专题填 0'); return; }
  400. this.updatingSpecial.set(true);
  401. try {
  402. const result = await this.functions.admin<{ updated: number }>('specialBatch', { className: 'Special', action: 'move', objectIds, pid });
  403. await this.load(); this.bulkMessage.set(`已移动 ${result.updated} 个专题`);
  404. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量专题移动失败'); }
  405. finally { this.updatingSpecial.set(false); }
  406. }
  407. async applyGuestbookAction(action: 'audit' | 'unaudit' | 'recycle' | 'recover'): Promise<void> {
  408. this.guestbookActionError.set(''); this.guestbookActionMessage.set('');
  409. if (this.className() !== 'Guestbook' || !this.draftId()) { this.guestbookActionError.set('只能管理现有留言'); return; }
  410. if (action === 'recycle' && !confirm('确认将该留言移入回收站?')) return;
  411. this.updatingGuestbook.set(true);
  412. try {
  413. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('guestbookBatch', { className: 'Guestbook', action, objectIds: [this.draftId()] });
  414. if (result.results?.[0]) { this.draft.set(result.results[0]); this.selectedGuestbookStatus.set(Number(result.results[0]['status']) || 0); }
  415. this.guestbookActionMessage.set(action === 'audit' ? '留言已审核' : action === 'unaudit' ? '留言已取消审核' : action === 'recycle' ? '留言已移入回收站' : '留言已恢复'); await this.load();
  416. } catch (error) { this.guestbookActionError.set(error instanceof Error ? error.message : '留言状态更新失败'); }
  417. finally { this.updatingGuestbook.set(false); }
  418. }
  419. async replyGuestbook(): Promise<void> {
  420. this.guestbookActionError.set(''); this.guestbookActionMessage.set('');
  421. const content = this.guestbookReplyContent();
  422. if (this.className() !== 'Guestbook' || !this.draftId() || !content.trim()) { this.guestbookActionError.set('请输入回复内容'); return; }
  423. this.updatingGuestbook.set(true);
  424. try {
  425. await this.functions.admin('guestbookReply', { className: 'Guestbook', parentObjectId: this.draftId(), title: this.guestbookReplyTitle().trim(), content });
  426. this.guestbookReplyTitle.set(''); this.guestbookReplyContent.set(''); this.guestbookActionMessage.set('管理员回复已发布');
  427. } catch (error) { this.guestbookActionError.set(error instanceof Error ? error.message : '管理员回复失败'); }
  428. finally { this.updatingGuestbook.set(false); }
  429. }
  430. async applyBulkGuestbookAction(action: 'audit' | 'unaudit' | 'recycle' | 'recover'): Promise<void> {
  431. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  432. if (this.className() !== 'Guestbook' || !objectIds.length) { this.bulkError.set('请先选择留言'); return; }
  433. if (action === 'recycle' && !confirm(`确认将选中的 ${objectIds.length} 条留言移入回收站?`)) return;
  434. this.updatingGuestbook.set(true);
  435. try {
  436. const result = await this.functions.admin<{ updated: number }>('guestbookBatch', { className: 'Guestbook', action, objectIds });
  437. await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条留言`);
  438. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量留言操作失败'); }
  439. finally { this.updatingGuestbook.set(false); }
  440. }
  441. async applyBarAction(action: 'audit' | 'unaudit' | 'recycle' | 'recover' | 'move' | 'top-global' | 'top-section' | 'top-undo' | 'elite' | 'elite-undo' | 'bottom' | 'bottom-undo'): Promise<void> {
  442. this.barActionError.set(''); this.barActionMessage.set('');
  443. if (this.className() !== 'GuestBar' || !this.draftId()) { this.barActionError.set('只能管理现有帖子'); return; }
  444. if (action === 'recycle' && !confirm('确认将该帖子移入回收站?')) return;
  445. const payload: Record<string, unknown> = { className: 'GuestBar', action, objectIds: [this.draftId()] };
  446. if (action === 'move') {
  447. const cateId = this.targetBarCategoryId();
  448. if (!Number.isInteger(cateId) || cateId < 1) { this.barActionError.set('请输入有效目标贴吧分类 ID'); return; }
  449. payload['cateId'] = cateId;
  450. }
  451. this.updatingBar.set(true);
  452. try {
  453. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('barBatch', payload);
  454. if (result.results?.[0]) { this.draft.set(result.results[0]); this.targetBarCategoryId.set(Number(result.results[0]['cateId']) || 0); }
  455. this.barActionMessage.set('帖子状态已更新'); await this.load();
  456. } catch (error) { this.barActionError.set(error instanceof Error ? error.message : '帖子操作失败'); }
  457. finally { this.updatingBar.set(false); }
  458. }
  459. async applyBulkBarAction(action: 'audit' | 'unaudit' | 'recycle' | 'recover' | 'move' | 'top-global' | 'top-section' | 'top-undo' | 'elite' | 'elite-undo' | 'bottom' | 'bottom-undo'): Promise<void> {
  460. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  461. if (this.className() !== 'GuestBar' || !objectIds.length) { this.bulkError.set('请先选择帖子'); return; }
  462. if (action === 'recycle' && !confirm(`确认将选中的 ${objectIds.length} 条帖子移入回收站?`)) return;
  463. const payload: Record<string, unknown> = { className: 'GuestBar', action, objectIds };
  464. if (action === 'move') {
  465. const cateId = this.targetBarCategoryId();
  466. if (!Number.isInteger(cateId) || cateId < 1) { this.bulkError.set('请输入有效目标贴吧分类 ID'); return; }
  467. payload['cateId'] = cateId;
  468. }
  469. this.updatingBar.set(true);
  470. try { const result = await this.functions.admin<{ updated: number }>('barBatch', payload); await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条帖子`); }
  471. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量帖子操作失败'); }
  472. finally { this.updatingBar.set(false); }
  473. }
  474. async applyBulkDictionaryAction(action: 'enable' | 'disable' | 'delete'): Promise<void> {
  475. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  476. if (!['Datadiccategory', 'Datadic'].includes(this.className()) || !objectIds.length) { this.bulkError.set('请先选择字典记录'); return; }
  477. if (action === 'delete' && !confirm(`确认删除选中的 ${objectIds.length} 条字典记录?`)) return;
  478. this.updatingDictionary.set(true);
  479. try {
  480. const result = await this.functions.admin<{ updated: number }>('dictionaryBatch', { className: this.className(), action, objectIds });
  481. await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条字典记录`);
  482. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量字典操作失败'); }
  483. finally { this.updatingDictionary.set(false); }
  484. }
  485. async applyBulkGradeDelete(): Promise<void> {
  486. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  487. if (!['GradeCate', 'Grade'].includes(this.className()) || !objectIds.length) { this.bulkError.set('请先选择多级字典记录'); return; }
  488. if (!confirm(`确认删除选中的 ${objectIds.length} 条多级字典记录?`)) return;
  489. this.updatingGrade.set(true);
  490. try { const result = await this.functions.admin<{ updated: number }>('gradeBatch', { className: this.className(), action: 'delete', objectIds }); await this.load(); this.bulkMessage.set(`已删除 ${result.updated} 条多级字典记录`); }
  491. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量删除多级字典失败'); }
  492. finally { this.updatingGrade.set(false); }
  493. }
  494. async applyBulkCurrencyDelete(): Promise<void> {
  495. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  496. if (this.className() !== 'Currency' || !objectIds.length) { this.bulkError.set('请先选择货币记录'); return; }
  497. if (!confirm(`确认删除选中的 ${objectIds.length} 条货币记录?`)) return;
  498. this.updatingCurrency.set(true);
  499. try { const result = await this.functions.admin<{ updated: number }>('currencyBatch', { className: 'Currency', action: 'delete', objectIds }); await this.load(); this.bulkMessage.set(`已删除 ${result.updated} 条货币记录`); }
  500. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量删除货币失败'); }
  501. finally { this.updatingCurrency.set(false); }
  502. }
  503. async remove(row: Record<string, unknown>): Promise<void> {
  504. const objectId = String(row['objectId'] ?? '');
  505. const verb = ['CommonModel', 'Node', 'Guestbook'].includes(this.className()) ? '移入回收站' : '删除';
  506. if (!objectId || !confirm(`确认${verb} ${this.className()} / ${objectId}?`)) return;
  507. try { await this.functions.admin('delete', { className: this.className(), objectId }); await this.load(); }
  508. catch (error) { this.error.set(error instanceof Error ? error.message : '删除失败'); }
  509. }
  510. display(value: unknown): string {
  511. if (value == null || value === '') return '—';
  512. if (typeof value === 'object') {
  513. const data = value as Record<string, unknown>;
  514. return String(data['name'] ?? data['title'] ?? data['username'] ?? data['objectId'] ?? JSON.stringify(value));
  515. }
  516. return String(value);
  517. }
  518. groupIdOf(group: Record<string, unknown>): number { return Number(group['groupId']) || 0; }
  519. groupLabel(group: Record<string, unknown>): string { return `${String(group['groupName'] || group['name'] || '未命名组')}(${this.groupIdOf(group)})`; }
  520. dictionaryCategoryIdOf(category: Record<string, unknown>): number { return Number(category['diccateid']) || 0; }
  521. gradeCategoryIdOf(category: Record<string, unknown>): number { return Number(category['cateId']) || 0; }
  522. contentStatusValue(): number { return Number(this.draft()['status']) || 0; }
  523. contentStatusLabel(status: number): string { return ({ [-3]: '草稿', [-2]: '回收站', [-1]: '未通过', 0: '待审核', 99: '已审核' } as Record<number, string>)[status] || String(status); }
  524. nodeStatusValue(): number { return Number(this.draft()['zstatus'] ?? 99); }
  525. private async loadUserGroups(): Promise<void> {
  526. try {
  527. const groups = await this.functions.admin<ResourcePage>('list', { className: 'Group', page: 1, pageSize: 100, sort: 'orderId', order: 'asc' });
  528. this.userGroups.set(groups.results);
  529. } catch (error) { this.userGroups.set([]); this.userActionError.set(error instanceof Error ? error.message : '用户组加载失败'); }
  530. }
  531. private async loadDictionaryCategories(): Promise<void> {
  532. try {
  533. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('dictionaryCategories', { enabledOnly: false });
  534. this.dictionaryCategories.set(result.results || []);
  535. } catch (error) { this.dictionaryCategories.set([]); this.error.set(error instanceof Error ? error.message : '字典分类加载失败'); }
  536. }
  537. private async loadGradeCategories(): Promise<void> {
  538. try { const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('gradeCategories', {}); this.gradeCategories.set(result.results || []); }
  539. catch (error) { this.gradeCategories.set([]); this.error.set(error instanceof Error ? error.message : '多级字典分类加载失败'); }
  540. }
  541. private resetPasswordFields(): void { this.newPassword.set(''); this.confirmPassword.set(''); this.passwordMessage.set(''); this.passwordError.set(''); }
  542. private resetCreateUserFields(): void { this.createUsername.set(''); this.createPassword.set(''); this.createConfirmPassword.set(''); this.createDisplayName.set(''); this.createMobile.set(''); this.createInviteUsername.set(''); this.createUserError.set(''); }
  543. private resetUserActions(detail: Record<string, unknown> = {}): void { this.userGroups.set([]); this.selectedUserGroupId.set(Number(detail['legacyGroupId'] ?? (detail['legacyUserData'] as Record<string, unknown> | undefined)?.['GroupID']) || 0); this.userActionReason.set(''); this.userActionError.set(''); this.userActionMessage.set(''); }
  544. private resetContentActions(detail: Record<string, unknown> = {}): void { this.selectedContentStatus.set(Number(detail['status']) || 0); this.targetContentNodeId.set(Number(detail['nodeId']) || 0); this.contentActionError.set(''); this.contentActionMessage.set(''); }
  545. private resetNodeActions(detail: Record<string, unknown> = {}): void { this.targetNodeParentId.set(Number(detail['parentId']) || 0); this.nodeActionError.set(''); this.nodeActionMessage.set(''); }
  546. private resetSpecialActions(detail: Record<string, unknown> = {}): void { this.targetSpecialParentId.set(Number(detail['pid']) || 0); this.specialActionError.set(''); this.specialActionMessage.set(''); }
  547. private resetGuestbookActions(detail: Record<string, unknown> = {}): void { this.selectedGuestbookStatus.set(Number(detail['status'] ?? 99)); this.guestbookReplyTitle.set(''); this.guestbookReplyContent.set(''); this.guestbookActionError.set(''); this.guestbookActionMessage.set(''); }
  548. private resetGuestCategoryActions(detail: Record<string, unknown> = {}): void { this.guestCategoryType.set(Number(detail['gtype']) || 0); this.targetGuestCategoryParentId.set(Number(detail['parentId']) || 0); }
  549. private resetBarActions(detail: Record<string, unknown> = {}): void { this.targetBarCategoryId.set(Number(detail['cateId']) || 0); this.barActionError.set(''); this.barActionMessage.set(''); }
  550. private resetExamClassActions(detail: Record<string, unknown> = {}): void { this.targetExamClassParentId.set(Number(detail['cClassid']) || 0); this.examClassType.set(Number(detail['cClassType']) || 1); this.examClassOrder.set(Number(detail['cOrderBy']) || 0); }
  551. private resetExamPointActions(detail: Record<string, unknown> = {}): void { this.targetExamPointParentId.set(Number(detail['tid']) || 0); this.examPointOrder.set(Number(detail['orderBy']) || 0); }
  552. private resetKnowledgeActions(detail: Record<string, unknown> = {}): void { this.targetKnowledgeClassId.set(Number(detail['kClassId']) || 0); this.targetKnowledgeParentId.set(Number(detail['pid']) || 0); this.knowledgeOrder.set(Number(detail['kOrderBy']) || 0); }
  553. private resetTeacherActions(detail: Record<string, unknown> = {}): void { this.targetTeacherClassId.set(Number(detail['tclsss']) || 0); }
  554. private resetDictionaryActions(detail: Record<string, unknown> = {}): void { this.targetDictionaryCategoryId.set(Number(detail['diccate']) || 0); }
  555. private resetGradeActions(detail: Record<string, unknown> = {}): void { this.targetGradeCategoryId.set(Number(detail['cate']) || this.filterGradeCategoryId()); this.targetGradeParentId.set(Number(detail['parentId']) || this.filterGradeParentId()); }
  556. }