admin-resource.component.ts 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  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. interface SurveyChart {
  10. survey: Record<string, unknown>;
  11. responseCount: number;
  12. invalidAnswers: number;
  13. questions: { id: string; title: string; type: string; options: { text: string; value: string; count: number }[]; otherCount: number }[];
  14. }
  15. @Component({
  16. selector: 'app-admin-resource',
  17. standalone: true,
  18. imports: [CommonModule, FormsModule, LucideAngularModule],
  19. templateUrl: './admin-resource.component.html',
  20. styleUrl: './admin-resource.component.scss',
  21. changeDetection: ChangeDetectionStrategy.OnPush,
  22. })
  23. export class AdminResourceComponent implements OnInit {
  24. readonly className = signal('');
  25. readonly schema = signal<AdminClassSchema | null>(null);
  26. readonly page = signal<ResourcePage | null>(null);
  27. readonly loading = signal(true);
  28. readonly saving = signal(false);
  29. readonly resettingPassword = signal(false);
  30. readonly error = signal('');
  31. readonly search = signal('');
  32. readonly editorOpen = signal(false);
  33. readonly draftId = signal('');
  34. readonly draft = signal<Record<string, unknown>>({});
  35. readonly fieldErrors = signal<Record<string, string>>({});
  36. readonly fieldInputs = signal<Record<string, string>>({});
  37. readonly newPassword = signal('');
  38. readonly confirmPassword = signal('');
  39. readonly passwordMessage = signal('');
  40. readonly passwordError = signal('');
  41. readonly createUsername = signal('');
  42. readonly createPassword = signal('');
  43. readonly createConfirmPassword = signal('');
  44. readonly createDisplayName = signal('');
  45. readonly createMobile = signal('');
  46. readonly createInviteUsername = signal('');
  47. readonly createUserError = signal('');
  48. readonly userGroups = signal<Record<string, unknown>[]>([]);
  49. readonly selectedUserGroupId = signal(0);
  50. readonly userActionReason = signal('');
  51. readonly userActionError = signal('');
  52. readonly userActionMessage = signal('');
  53. readonly updatingUser = signal(false);
  54. readonly selectedContentStatus = signal(0);
  55. readonly targetContentNodeId = signal(0);
  56. readonly updatingContent = signal(false);
  57. readonly contentActionError = signal('');
  58. readonly contentActionMessage = signal('');
  59. readonly targetNodeParentId = signal(0);
  60. readonly updatingNode = signal(false);
  61. readonly nodeActionError = signal('');
  62. readonly nodeActionMessage = signal('');
  63. readonly targetSpecialParentId = signal(0);
  64. readonly updatingSpecial = signal(false);
  65. readonly specialActionError = signal('');
  66. readonly specialActionMessage = signal('');
  67. readonly selectedGuestbookStatus = signal(99);
  68. readonly guestbookReplyTitle = signal('');
  69. readonly guestbookReplyContent = signal('');
  70. readonly updatingGuestbook = signal(false);
  71. readonly guestbookActionError = signal('');
  72. readonly guestbookActionMessage = signal('');
  73. readonly guestCategoryType = signal(0);
  74. readonly targetGuestCategoryParentId = signal(0);
  75. readonly targetBarCategoryId = signal(0);
  76. readonly updatingBar = signal(false);
  77. readonly barActionError = signal('');
  78. readonly barActionMessage = signal('');
  79. readonly targetExamClassParentId = signal(0);
  80. readonly examClassType = signal(1);
  81. readonly examClassOrder = signal(0);
  82. readonly targetExamPointParentId = signal(0);
  83. readonly examPointOrder = signal(0);
  84. readonly targetKnowledgeClassId = signal(0);
  85. readonly targetKnowledgeParentId = signal(0);
  86. readonly knowledgeOrder = signal(0);
  87. readonly targetTeacherClassId = signal(0);
  88. readonly targetDictionaryCategoryId = signal(0);
  89. readonly dictionaryCategories = signal<Record<string, unknown>[]>([]);
  90. readonly updatingDictionary = signal(false);
  91. readonly targetGradeCategoryId = signal(0);
  92. readonly targetGradeParentId = signal(0);
  93. readonly filterGradeCategoryId = signal(0);
  94. readonly filterGradeParentId = signal(0);
  95. readonly gradeCategories = signal<Record<string, unknown>[]>([]);
  96. readonly updatingGrade = signal(false);
  97. readonly updatingCurrency = signal(false);
  98. readonly updatingHoliday = signal(false);
  99. readonly filterSearchNavigationType = signal(1);
  100. readonly filterSearchNavigationState = signal(-100);
  101. readonly filterSearchNavigationElite = signal(-100);
  102. readonly searchNavigationOrderStart = signal(1);
  103. readonly updatingSearchNavigation = signal(false);
  104. readonly filterAdZoneType = signal('');
  105. readonly filterAdStatus = signal(-100);
  106. readonly filterAdInfoZoneId = signal('');
  107. readonly targetAdZoneId = signal('');
  108. readonly adZones = signal<Record<string, unknown>[]>([]);
  109. readonly adPreview = signal<Record<string, unknown>[]>([]);
  110. readonly adPreviewLoading = signal(false);
  111. readonly adPreviewError = signal('');
  112. readonly updatingAdvertisement = signal(false);
  113. readonly filterFontShapeTypeId = signal(0);
  114. readonly targetFontShapeTypeId = signal(0);
  115. readonly fontShapeTypes = signal<Record<string, unknown>[]>([]);
  116. readonly fontShapePreview = signal('');
  117. readonly updatingFontShape = signal(false);
  118. readonly filterSurveyStatus = signal(-100);
  119. readonly filterSurveyId = signal(0);
  120. readonly surveys = signal<Record<string, unknown>[]>([]);
  121. readonly surveyOrderStart = signal(1);
  122. readonly surveyChart = signal<SurveyChart | null>(null);
  123. readonly surveyChartLoading = signal(false);
  124. readonly surveyChartError = signal('');
  125. readonly updatingSurvey = signal(false);
  126. readonly targetServiceSeatUsername = signal('');
  127. readonly updatingService = signal(false);
  128. readonly filterStoreStatus = signal(-100);
  129. readonly targetStoreStyleId = signal(0);
  130. readonly targetStoreUsername = signal('');
  131. readonly storeStyles = signal<Record<string, unknown>[]>([]);
  132. readonly updatingStore = signal(false);
  133. readonly tagKeyContent = signal('');
  134. readonly selectedIds = signal<string[]>([]);
  135. readonly bulkError = signal('');
  136. readonly bulkMessage = signal('');
  137. readonly icons = { ChevronLeft, ChevronRight, Eye, KeyRound, LoaderCircle, Pencil, Plus, RefreshCw, Search, Trash2, X };
  138. readonly columns = computed(() => {
  139. const fields = this.schema()?.fields ?? [];
  140. const preferred = ['objectId', 'name', 'title', 'qtitle', 'sName', 'storeName', 'styleName', 'count', 'content', 'str1', 'categoryname', 'dicname', 'cateName', 'gradeName', 'cClassName', 'testPoint', 'kName', 'tname', 'username', 'userName', 'realName', 'sRemrk', 'askId', 'zoneId', 'typeId', 'shape', 'qtype', 'required', 'ztype', 'priority', 'zstatus', 'storeState', 'storeCommendState', 'storeStyleId', 'sDefault', 'sIndex', 'str4', 'sdate', 'edate', 'fileUrl', 'type', 'state', 'eliteLevel', 'orderId', 'mobile', 'sourceKey', 'status', 'createdAt', 'updatedAt'];
  141. const rank = (name: string): number => { const index = preferred.indexOf(name); return index < 0 ? preferred.length : index; };
  142. 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);
  143. });
  144. readonly pageCount = computed(() => Math.max(1, Math.ceil((this.page()?.total ?? 0) / (this.page()?.pageSize || 20))));
  145. readonly bulkEnabled = computed(() => ['_User', 'CommonModel', 'Node', 'Special', 'Guestbook', 'GuestBar', 'Datadiccategory', 'Datadic', 'GradeCate', 'Grade', 'Currency', 'SysHoliday', 'Search', 'AdZone', 'AdInfo', 'FontPicShape', 'FontPicShapeType', 'DesignAsk', 'DesignQuestion', 'DesignAnswer', 'ServiceSeat', 'Temp', 'StoreApplication', 'StoreStyle'].includes(this.className()));
  146. readonly allPageSelected = computed(() => {
  147. const ids = (this.page()?.results || []).map((row) => String(row['objectId'] || '')).filter(Boolean);
  148. return Boolean(ids.length) && ids.every((id) => this.selectedIds().includes(id));
  149. });
  150. private readonly functions = inject(CloudFunctionsService);
  151. private readonly route = inject(ActivatedRoute);
  152. private readonly destroyRef = inject(DestroyRef);
  153. ngOnInit(): void {
  154. this.route.paramMap.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((params) => {
  155. this.className.set(params.get('className') ?? '');
  156. this.search.set('');
  157. this.filterGradeCategoryId.set(0); this.filterGradeParentId.set(0);
  158. this.filterSearchNavigationType.set(1); this.filterSearchNavigationState.set(-100); this.filterSearchNavigationElite.set(-100); this.searchNavigationOrderStart.set(1);
  159. this.filterAdZoneType.set(''); this.filterAdStatus.set(-100); this.filterAdInfoZoneId.set(''); this.resetAdActions();
  160. this.filterFontShapeTypeId.set(0); this.resetFontShapeActions();
  161. this.filterSurveyStatus.set(-100); this.filterSurveyId.set(0); this.resetSurveyActions();
  162. this.resetServiceActions();
  163. this.filterStoreStatus.set(-100); this.resetStoreActions();
  164. this.resetTagKeyActions();
  165. void this.load(1, true);
  166. });
  167. }
  168. async load(pageNumber = this.page()?.page ?? 1, reloadSchema = false): Promise<void> {
  169. this.loading.set(true); this.error.set(''); this.selectedIds.set([]); this.bulkError.set(''); this.bulkMessage.set('');
  170. try {
  171. if (reloadSchema || !this.schema()) this.schema.set(await this.functions.admin<AdminClassSchema>('schema', { className: this.className() }));
  172. if (this.className() === 'Grade' && reloadSchema) { await this.loadGradeCategories(); if (!this.filterGradeCategoryId() && this.gradeCategories().length) this.filterGradeCategoryId.set(this.gradeCategoryIdOf(this.gradeCategories()[0])); }
  173. if (this.className() === 'AdInfo' && reloadSchema) await this.loadAdZones();
  174. if (this.className() === 'FontPicShape' && reloadSchema) await this.loadFontShapeTypes();
  175. if (['DesignQuestion', 'DesignAnswer'].includes(this.className()) && reloadSchema) { await this.loadSurveys(); if (!this.filterSurveyId() && this.surveys().length) this.filterSurveyId.set(this.surveyIdOf(this.surveys()[0])); }
  176. if (this.className() === 'StoreApplication' && reloadSchema) await this.loadStoreStyles();
  177. const pageOperation = this.className() === 'Grade' && this.filterGradeCategoryId() > 0 ? 'gradeOptions' : this.className() === 'Search' ? 'searchNavigations' : this.className() === 'AdZone' ? 'adZones' : this.className() === 'AdInfo' ? 'adInfos' : this.className() === 'FontPicShape' ? 'fontShapes' : this.className() === 'FontPicShapeType' ? 'fontShapeTypes' : this.className() === 'DesignAsk' ? 'surveys' : this.className() === 'DesignQuestion' ? 'surveyQuestions' : this.className() === 'DesignAnswer' ? 'surveyResults' : this.className() === 'ServiceSeat' ? 'serviceSeats' : this.className() === 'Temp' ? 'serviceCodes' : this.className() === 'StoreApplication' ? 'storeApplications' : this.className() === 'StoreStyle' ? 'storeStyles' : this.className() === 'ContentTagKey' ? 'contentTagKeys' : 'list';
  178. const pagePayload: Record<string, unknown> = { className: this.className(), page: pageNumber, pageSize: 20, search: this.search().trim() };
  179. if (pageOperation === 'gradeOptions') { pagePayload['categoryId'] = this.filterGradeCategoryId(); pagePayload['parentId'] = this.filterGradeParentId(); }
  180. if (pageOperation === 'searchNavigations') { pagePayload['type'] = this.filterSearchNavigationType(); pagePayload['state'] = this.filterSearchNavigationState(); pagePayload['elite'] = this.filterSearchNavigationElite(); }
  181. if (pageOperation === 'adZones') { pagePayload['type'] = this.filterAdZoneType(); pagePayload['status'] = this.filterAdStatus(); }
  182. if (pageOperation === 'adInfos') { pagePayload['zoneId'] = this.filterAdInfoZoneId(); pagePayload['status'] = this.filterAdStatus(); }
  183. if (pageOperation === 'fontShapes') pagePayload['typeId'] = this.filterFontShapeTypeId();
  184. if (pageOperation === 'surveys') pagePayload['status'] = this.filterSurveyStatus();
  185. if (pageOperation === 'surveyQuestions' || pageOperation === 'surveyResults') pagePayload['askId'] = this.filterSurveyId();
  186. if (pageOperation === 'storeApplications') pagePayload['status'] = this.filterStoreStatus();
  187. this.page.set(await this.functions.admin<ResourcePage>(pageOperation, pagePayload));
  188. if (this.className() === '_User' && reloadSchema) await this.loadUserGroups();
  189. if (this.className() === 'Datadic' && reloadSchema) await this.loadDictionaryCategories();
  190. } catch (error) { this.error.set(error instanceof Error ? error.message : '数据加载失败'); }
  191. finally { this.loading.set(false); }
  192. }
  193. 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.resetAdActions(); this.resetFontShapeActions(); this.resetSurveyActions(); this.resetServiceActions(); this.resetStoreActions(); this.resetTagKeyActions(); this.editorOpen.set(true); }
  194. async openEdit(row: Record<string, unknown>): Promise<void> {
  195. const objectId = String(row['objectId'] ?? '');
  196. this.error.set('');
  197. try {
  198. const detailOperation = this.className() === 'ContentTagKey' ? 'getContentTagKeys' : 'get';
  199. const detail = await this.functions.admin<Record<string, unknown>>(detailOperation, { className: this.className(), objectId });
  200. 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.resetAdActions(detail); this.resetFontShapeActions(detail); this.resetSurveyActions(); this.resetServiceActions(detail); this.resetStoreActions(detail); this.resetTagKeyActions(detail); this.editorOpen.set(true);
  201. if (this.className() === '_User') await this.loadUserGroups();
  202. if (this.className() === 'AdInfo' && !this.adZones().length) await this.loadAdZones();
  203. if (this.className() === 'AdZone') await this.loadAdPreview();
  204. if (this.className() === 'FontPicShape' && !this.fontShapeTypes().length) await this.loadFontShapeTypes();
  205. } catch (error) { this.error.set(error instanceof Error ? error.message : '详情加载失败'); }
  206. }
  207. 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(); this.resetAdActions(); this.resetFontShapeActions(); this.resetSurveyActions(); this.resetServiceActions(); this.resetStoreActions(); this.resetTagKeyActions(); }
  208. setField(field: AdminFieldSchema, raw: unknown): void {
  209. let value = raw;
  210. if (field.type === 'Number') value = raw === '' ? null : Number(raw);
  211. if (field.type === 'Pointer') value = raw ? { __type: 'Pointer', className: field.targetClass, objectId: String(raw) } : null;
  212. if ((field.type === 'Object' || field.type === 'Array') && typeof raw === 'string') {
  213. this.fieldInputs.update((current) => ({ ...current, [field.name]: raw }));
  214. try {
  215. value = raw.trim() ? JSON.parse(raw) : field.type === 'Array' ? [] : {};
  216. const valid = field.type === 'Array' ? Array.isArray(value) : Boolean(value) && typeof value === 'object' && !Array.isArray(value);
  217. if (!valid) throw new Error();
  218. this.fieldErrors.update((current) => { const next = { ...current }; delete next[field.name]; return next; });
  219. } catch {
  220. this.fieldErrors.update((current) => ({ ...current, [field.name]: field.type === 'Array' ? '请输入有效的 JSON 数组' : '请输入有效的 JSON 对象' }));
  221. return;
  222. }
  223. }
  224. this.draft.update((current) => ({ ...current, [field.name]: value }));
  225. }
  226. inputValue(field: AdminFieldSchema): string | number {
  227. const value = this.draft()[field.name];
  228. if (field.type === 'Pointer') return String((value as { objectId?: string } | null)?.objectId ?? '');
  229. 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));
  230. if (field.type === 'Object' || field.type === 'Array') return this.fieldInputs()[field.name] ?? (value == null ? '' : JSON.stringify(value, null, 2));
  231. return typeof value === 'number' ? value : String(value ?? '');
  232. }
  233. async save(): Promise<void> {
  234. const invalidFields = Object.keys(this.fieldErrors());
  235. if (invalidFields.length) { this.error.set(`请先修正字段格式:${invalidFields.join('、')}`); return; }
  236. this.saving.set(true); this.error.set('');
  237. try {
  238. const operation = this.className() === 'Group' ? 'saveGroup'
  239. : this.className() === 'Node' ? 'saveNode'
  240. : this.className() === 'Special' ? 'saveSpecial'
  241. : this.className() === 'Model' ? 'saveModelMetadata'
  242. : this.className() === 'ModelField' ? 'saveModelFieldMetadata'
  243. : this.className() === 'Guestbook' ? 'saveGuestbook'
  244. : this.className() === 'Guestcate' ? 'saveGuestCategory'
  245. : this.className() === 'ExamClass' ? 'saveExamClass'
  246. : this.className() === 'ExamPoint' ? 'saveExamPoint'
  247. : this.className() === 'QuestionsKnowledge' ? 'saveKnowledge'
  248. : this.className() === 'ExTeacher' ? 'saveExamTeacher'
  249. : this.className() === 'Datadiccategory' ? 'saveDictionaryCategory'
  250. : this.className() === 'Datadic' ? 'saveDictionaryItem'
  251. : this.className() === 'GradeCate' ? 'saveGradeCategory'
  252. : this.className() === 'Grade' ? 'saveGradeOption'
  253. : this.className() === 'Currency' ? 'saveCurrency'
  254. : this.className() === 'SysHoliday' ? 'saveHoliday'
  255. : this.className() === 'Search' ? 'saveSearchNavigation'
  256. : this.className() === 'AdZone' ? 'saveAdZone'
  257. : this.className() === 'AdInfo' ? 'saveAdInfo'
  258. : this.className() === 'FontPicShape' ? 'saveFontShape'
  259. : this.className() === 'FontPicShapeType' ? 'saveFontShapeType'
  260. : this.className() === 'DesignAsk' ? 'saveSurvey'
  261. : this.className() === 'DesignQuestion' ? 'saveSurveyQuestion'
  262. : this.className() === 'ServiceSeat' ? 'saveServiceSeat'
  263. : this.className() === 'Temp' ? 'saveServiceCode'
  264. : this.className() === 'StoreApplication' ? 'saveStoreApplication'
  265. : this.className() === 'StoreStyle' ? 'saveStoreStyle'
  266. : this.className() === 'ContentTagKey' ? 'saveContentTagKeys' : 'save';
  267. const payload: Record<string, unknown> = { className: this.className(), objectId: this.draftId() || undefined, fields: this.draft() };
  268. if (this.className() === 'Node') payload['parentId'] = this.targetNodeParentId();
  269. if (this.className() === 'Special') payload['pid'] = this.targetSpecialParentId();
  270. if (this.className() === 'Guestcate') { payload['gtype'] = this.guestCategoryType(); payload['parentId'] = this.targetGuestCategoryParentId(); }
  271. if (this.className() === 'ExamClass') { payload['parentId'] = this.targetExamClassParentId(); payload['classType'] = this.examClassType(); payload['orderId'] = this.examClassOrder(); }
  272. if (this.className() === 'ExamPoint') { payload['parentId'] = this.targetExamPointParentId(); payload['orderId'] = this.examPointOrder(); }
  273. if (this.className() === 'QuestionsKnowledge') { payload['classId'] = this.targetKnowledgeClassId(); payload['parentId'] = this.targetKnowledgeParentId(); payload['orderId'] = this.knowledgeOrder(); }
  274. if (this.className() === 'ExTeacher') payload['classId'] = this.targetTeacherClassId();
  275. if (this.className() === 'Datadic') payload['categoryId'] = this.targetDictionaryCategoryId();
  276. if (this.className() === 'Grade') { payload['categoryId'] = this.targetGradeCategoryId(); payload['parentId'] = this.targetGradeParentId(); }
  277. if (this.className() === 'AdInfo') payload['zoneId'] = this.targetAdZoneId();
  278. if (this.className() === 'FontPicShape') payload['typeId'] = this.targetFontShapeTypeId();
  279. if (this.className() === 'ServiceSeat') payload['username'] = this.targetServiceSeatUsername();
  280. if (this.className() === 'StoreApplication') { payload['username'] = this.targetStoreUsername(); payload['styleId'] = this.targetStoreStyleId(); }
  281. if (this.className() === 'ContentTagKey') payload['content'] = this.tagKeyContent();
  282. await this.functions.admin(operation, payload);
  283. this.closeEditor(); await this.load();
  284. } catch (error) { this.error.set(error instanceof Error ? error.message : '保存失败'); }
  285. finally { this.saving.set(false); }
  286. }
  287. async submitEditor(): Promise<void> {
  288. if (this.className() === '_User' && !this.draftId()) await this.createUser();
  289. else await this.save();
  290. }
  291. async createUser(): Promise<void> {
  292. const username = this.createUsername().trim();
  293. const password = this.createPassword();
  294. this.createUserError.set('');
  295. if (this.className() !== '_User' || this.draftId()) { this.createUserError.set('只能从用户管理的新建入口开户'); return; }
  296. if (username.length < 3 || username.length > 64) { this.createUserError.set('账号长度应为 3 至 64 位'); return; }
  297. if (password.length < 8 || password.length > 72) { this.createUserError.set('密码长度应为 8 至 72 位'); return; }
  298. if (password !== this.createConfirmPassword()) { this.createUserError.set('两次输入的密码不一致'); return; }
  299. const payload: Record<string, unknown> = { username, password };
  300. const displayName = this.createDisplayName().trim();
  301. const mobile = this.createMobile().trim();
  302. const inviteUsername = this.createInviteUsername().trim();
  303. if (displayName) payload['displayName'] = displayName;
  304. if (mobile) payload['mobile'] = mobile;
  305. if (inviteUsername) payload['inviteUsername'] = inviteUsername;
  306. this.saving.set(true); this.error.set('');
  307. try {
  308. await this.functions.admin('createUser', payload);
  309. this.closeEditor(); await this.load();
  310. } catch (error) { this.createUserError.set(error instanceof Error ? error.message : '用户开户失败'); }
  311. finally { this.saving.set(false); }
  312. }
  313. async resetPassword(): Promise<void> {
  314. this.passwordError.set(''); this.passwordMessage.set('');
  315. if (this.className() !== '_User' || !this.draftId()) { this.passwordError.set('只能重置现有用户密码'); return; }
  316. if (this.newPassword().length < 8) { this.passwordError.set('新密码至少 8 位'); return; }
  317. if (this.newPassword() !== this.confirmPassword()) { this.passwordError.set('两次输入的密码不一致'); return; }
  318. this.resettingPassword.set(true);
  319. try {
  320. await this.functions.admin('resetPassword', { className: '_User', objectId: this.draftId(), newPassword: this.newPassword() });
  321. this.newPassword.set(''); this.confirmPassword.set(''); this.passwordMessage.set('密码已安全重置');
  322. } catch (error) { this.passwordError.set(error instanceof Error ? error.message : '密码重置失败'); }
  323. finally { this.resettingPassword.set(false); }
  324. }
  325. async setUserDisabled(disabled: boolean): Promise<void> {
  326. this.userActionError.set(''); this.userActionMessage.set('');
  327. if (this.className() !== '_User' || !this.draftId()) { this.userActionError.set('只能管理现有用户状态'); return; }
  328. if (disabled && !confirm('确认停用该账号并撤销其全部登录会话?')) return;
  329. this.updatingUser.set(true);
  330. try {
  331. const result = await this.functions.admin<{ results: Record<string, unknown>[]; revokedSessions: number }>('userBatch', {
  332. className: '_User', action: disabled ? 'lock' : 'unlock', objectIds: [this.draftId()], reason: this.userActionReason().trim(),
  333. });
  334. if (result.results?.[0]) this.draft.set(result.results[0]);
  335. this.userActionMessage.set(disabled ? `账号已停用,撤销 ${result.revokedSessions || 0} 个会话` : '账号已恢复使用');
  336. await this.load();
  337. } catch (error) { this.userActionError.set(error instanceof Error ? error.message : '账号状态更新失败'); }
  338. finally { this.updatingUser.set(false); }
  339. }
  340. async moveUserGroup(): Promise<void> {
  341. this.userActionError.set(''); this.userActionMessage.set('');
  342. const groupId = this.selectedUserGroupId();
  343. if (this.className() !== '_User' || !this.draftId() || !Number.isInteger(groupId) || groupId < 1) { this.userActionError.set('请选择有效用户组'); return; }
  344. this.updatingUser.set(true);
  345. try {
  346. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('userBatch', { className: '_User', action: 'move', objectIds: [this.draftId()], groupId });
  347. if (result.results?.[0]) this.draft.set(result.results[0]);
  348. this.userActionMessage.set(`已移动到用户组 ${groupId}`);
  349. await this.load();
  350. } catch (error) { this.userActionError.set(error instanceof Error ? error.message : '用户组更新失败'); }
  351. finally { this.updatingUser.set(false); }
  352. }
  353. async applyContentAction(action: 'status' | 'recycle' | 'recover' | 'move'): Promise<void> {
  354. this.contentActionError.set(''); this.contentActionMessage.set('');
  355. if (this.className() !== 'CommonModel' || !this.draftId()) { this.contentActionError.set('只能管理现有内容'); return; }
  356. if (action === 'recycle' && !confirm('确认将该内容移入回收站?')) return;
  357. const payload: Record<string, unknown> = { className: 'CommonModel', action, objectIds: [this.draftId()] };
  358. if (action === 'status') {
  359. const status = this.selectedContentStatus();
  360. if (![-3, -1, 0, 99].includes(status)) { this.contentActionError.set('请选择有效内容状态'); return; }
  361. payload['status'] = status;
  362. }
  363. if (action === 'move') {
  364. const nodeId = this.targetContentNodeId();
  365. if (!Number.isInteger(nodeId) || nodeId < 1) { this.contentActionError.set('请输入有效目标节点 ID'); return; }
  366. payload['nodeId'] = nodeId;
  367. }
  368. this.updatingContent.set(true);
  369. try {
  370. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('contentBatch', payload);
  371. if (result.results?.[0]) {
  372. this.draft.set(result.results[0]);
  373. this.selectedContentStatus.set(Number(result.results[0]['status']) || 0);
  374. this.targetContentNodeId.set(Number(result.results[0]['nodeId']) || 0);
  375. }
  376. const messages = { status: `内容状态已更新为${this.contentStatusLabel(this.selectedContentStatus())}`, recycle: '内容已移入回收站', recover: '内容已恢复为待审核', move: `内容已移动到节点 ${this.targetContentNodeId()}` };
  377. this.contentActionMessage.set(messages[action]);
  378. await this.load();
  379. } catch (error) { this.contentActionError.set(error instanceof Error ? error.message : '内容操作失败'); }
  380. finally { this.updatingContent.set(false); }
  381. }
  382. toggleSelection(objectId: string, selected: boolean): void {
  383. this.selectedIds.update((current) => selected ? [...new Set([...current, objectId])] : current.filter((id) => id !== objectId));
  384. }
  385. togglePageSelection(selected: boolean): void {
  386. const pageIds = (this.page()?.results || []).map((row) => String(row['objectId'] || '')).filter(Boolean);
  387. this.selectedIds.set(selected ? pageIds : []);
  388. }
  389. isSelected(objectId: unknown): boolean { return this.selectedIds().includes(String(objectId || '')); }
  390. async applyBulkUserAction(action: 'lock' | 'unlock' | 'move'): Promise<void> {
  391. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  392. if (this.className() !== '_User' || !objectIds.length) { this.bulkError.set('请先选择用户'); return; }
  393. if (action === 'lock' && !confirm(`确认停用选中的 ${objectIds.length} 个账号并撤销全部会话?`)) return;
  394. const payload: Record<string, unknown> = { className: '_User', action, objectIds };
  395. if (action === 'move') {
  396. const groupId = this.selectedUserGroupId();
  397. if (!Number.isInteger(groupId) || groupId < 1) { this.bulkError.set('请选择有效用户组'); return; }
  398. payload['groupId'] = groupId;
  399. } else payload['reason'] = this.userActionReason().trim();
  400. this.updatingUser.set(true);
  401. try {
  402. const result = await this.functions.admin<{ updated: number; revokedSessions: number }>('userBatch', payload);
  403. const message = action === 'lock' ? `已停用 ${result.updated} 个账号并撤销 ${result.revokedSessions || 0} 个会话` : action === 'unlock' ? `已解锁 ${result.updated} 个账号` : `已移动 ${result.updated} 个用户`;
  404. await this.load(); this.bulkMessage.set(message);
  405. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量用户操作失败'); }
  406. finally { this.updatingUser.set(false); }
  407. }
  408. async applyBulkContentAction(action: 'status' | 'recycle' | 'recover' | 'move'): Promise<void> {
  409. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  410. if (this.className() !== 'CommonModel' || !objectIds.length) { this.bulkError.set('请先选择内容'); return; }
  411. if (action === 'recycle' && !confirm(`确认将选中的 ${objectIds.length} 条内容移入回收站?`)) return;
  412. const payload: Record<string, unknown> = { className: 'CommonModel', action, objectIds };
  413. if (action === 'status') {
  414. const status = this.selectedContentStatus();
  415. if (![-3, -1, 0, 99].includes(status)) { this.bulkError.set('请选择有效内容状态'); return; }
  416. payload['status'] = status;
  417. }
  418. if (action === 'move') {
  419. const nodeId = this.targetContentNodeId();
  420. if (!Number.isInteger(nodeId) || nodeId < 1) { this.bulkError.set('请输入有效目标节点 ID'); return; }
  421. payload['nodeId'] = nodeId;
  422. }
  423. this.updatingContent.set(true);
  424. try {
  425. const result = await this.functions.admin<{ updated: number }>('contentBatch', payload);
  426. const message = `已处理 ${result.updated} 条内容`; await this.load(); this.bulkMessage.set(message);
  427. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量内容操作失败'); }
  428. finally { this.updatingContent.set(false); }
  429. }
  430. async applyNodeAction(action: 'recycle' | 'recover' | 'move'): Promise<void> {
  431. this.nodeActionError.set(''); this.nodeActionMessage.set('');
  432. if (this.className() !== 'Node' || !this.draftId()) { this.nodeActionError.set('只能管理现有栏目'); return; }
  433. if (action === 'recycle' && !confirm('确认将该栏目移入回收站?')) return;
  434. const payload: Record<string, unknown> = { className: 'Node', action, objectIds: [this.draftId()] };
  435. if (action === 'move') {
  436. const parentId = this.targetNodeParentId();
  437. if (!Number.isInteger(parentId) || parentId < 0) { this.nodeActionError.set('请输入有效父节点 ID,顶级栏目填 0'); return; }
  438. payload['parentId'] = parentId;
  439. }
  440. this.updatingNode.set(true);
  441. try {
  442. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('nodeBatch', payload);
  443. if (result.results?.[0]) { this.draft.set(result.results[0]); this.targetNodeParentId.set(Number(result.results[0]['parentId']) || 0); }
  444. this.nodeActionMessage.set(action === 'recycle' ? '栏目已移入回收站' : action === 'recover' ? '栏目已恢复' : `栏目已移动到父节点 ${this.targetNodeParentId()}`);
  445. await this.load();
  446. } catch (error) { this.nodeActionError.set(error instanceof Error ? error.message : '栏目操作失败'); }
  447. finally { this.updatingNode.set(false); }
  448. }
  449. async applyBulkNodeAction(action: 'recycle' | 'recover' | 'move'): Promise<void> {
  450. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  451. if (this.className() !== 'Node' || !objectIds.length) { this.bulkError.set('请先选择栏目'); return; }
  452. if (action === 'recycle' && !confirm(`确认将选中的 ${objectIds.length} 个栏目移入回收站?`)) return;
  453. const payload: Record<string, unknown> = { className: 'Node', action, objectIds };
  454. if (action === 'move') {
  455. const parentId = this.targetNodeParentId();
  456. if (!Number.isInteger(parentId) || parentId < 0) { this.bulkError.set('请输入有效父节点 ID,顶级栏目填 0'); return; }
  457. payload['parentId'] = parentId;
  458. }
  459. this.updatingNode.set(true);
  460. try {
  461. const result = await this.functions.admin<{ updated: number }>('nodeBatch', payload);
  462. await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 个栏目`);
  463. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量栏目操作失败'); }
  464. finally { this.updatingNode.set(false); }
  465. }
  466. async moveSpecial(): Promise<void> {
  467. this.specialActionError.set(''); this.specialActionMessage.set('');
  468. const pid = this.targetSpecialParentId();
  469. if (this.className() !== 'Special' || !this.draftId() || !Number.isInteger(pid) || pid < 0) { this.specialActionError.set('请输入有效父专题 ID,顶级专题填 0'); return; }
  470. this.updatingSpecial.set(true);
  471. try {
  472. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('specialBatch', { className: 'Special', action: 'move', objectIds: [this.draftId()], pid });
  473. if (result.results?.[0]) { this.draft.set(result.results[0]); this.targetSpecialParentId.set(Number(result.results[0]['pid']) || 0); }
  474. this.specialActionMessage.set(`专题已移动到父专题 ${pid}`); await this.load();
  475. } catch (error) { this.specialActionError.set(error instanceof Error ? error.message : '专题移动失败'); }
  476. finally { this.updatingSpecial.set(false); }
  477. }
  478. async applyBulkSpecialMove(): Promise<void> {
  479. const objectIds = this.selectedIds(); const pid = this.targetSpecialParentId(); this.bulkError.set(''); this.bulkMessage.set('');
  480. if (this.className() !== 'Special' || !objectIds.length) { this.bulkError.set('请先选择专题'); return; }
  481. if (!Number.isInteger(pid) || pid < 0) { this.bulkError.set('请输入有效父专题 ID,顶级专题填 0'); return; }
  482. this.updatingSpecial.set(true);
  483. try {
  484. const result = await this.functions.admin<{ updated: number }>('specialBatch', { className: 'Special', action: 'move', objectIds, pid });
  485. await this.load(); this.bulkMessage.set(`已移动 ${result.updated} 个专题`);
  486. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量专题移动失败'); }
  487. finally { this.updatingSpecial.set(false); }
  488. }
  489. async applyGuestbookAction(action: 'audit' | 'unaudit' | 'recycle' | 'recover'): Promise<void> {
  490. this.guestbookActionError.set(''); this.guestbookActionMessage.set('');
  491. if (this.className() !== 'Guestbook' || !this.draftId()) { this.guestbookActionError.set('只能管理现有留言'); return; }
  492. if (action === 'recycle' && !confirm('确认将该留言移入回收站?')) return;
  493. this.updatingGuestbook.set(true);
  494. try {
  495. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('guestbookBatch', { className: 'Guestbook', action, objectIds: [this.draftId()] });
  496. if (result.results?.[0]) { this.draft.set(result.results[0]); this.selectedGuestbookStatus.set(Number(result.results[0]['status']) || 0); }
  497. this.guestbookActionMessage.set(action === 'audit' ? '留言已审核' : action === 'unaudit' ? '留言已取消审核' : action === 'recycle' ? '留言已移入回收站' : '留言已恢复'); await this.load();
  498. } catch (error) { this.guestbookActionError.set(error instanceof Error ? error.message : '留言状态更新失败'); }
  499. finally { this.updatingGuestbook.set(false); }
  500. }
  501. async replyGuestbook(): Promise<void> {
  502. this.guestbookActionError.set(''); this.guestbookActionMessage.set('');
  503. const content = this.guestbookReplyContent();
  504. if (this.className() !== 'Guestbook' || !this.draftId() || !content.trim()) { this.guestbookActionError.set('请输入回复内容'); return; }
  505. this.updatingGuestbook.set(true);
  506. try {
  507. await this.functions.admin('guestbookReply', { className: 'Guestbook', parentObjectId: this.draftId(), title: this.guestbookReplyTitle().trim(), content });
  508. this.guestbookReplyTitle.set(''); this.guestbookReplyContent.set(''); this.guestbookActionMessage.set('管理员回复已发布');
  509. } catch (error) { this.guestbookActionError.set(error instanceof Error ? error.message : '管理员回复失败'); }
  510. finally { this.updatingGuestbook.set(false); }
  511. }
  512. async applyBulkGuestbookAction(action: 'audit' | 'unaudit' | 'recycle' | 'recover'): Promise<void> {
  513. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  514. if (this.className() !== 'Guestbook' || !objectIds.length) { this.bulkError.set('请先选择留言'); return; }
  515. if (action === 'recycle' && !confirm(`确认将选中的 ${objectIds.length} 条留言移入回收站?`)) return;
  516. this.updatingGuestbook.set(true);
  517. try {
  518. const result = await this.functions.admin<{ updated: number }>('guestbookBatch', { className: 'Guestbook', action, objectIds });
  519. await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条留言`);
  520. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量留言操作失败'); }
  521. finally { this.updatingGuestbook.set(false); }
  522. }
  523. async applyBarAction(action: 'audit' | 'unaudit' | 'recycle' | 'recover' | 'move' | 'top-global' | 'top-section' | 'top-undo' | 'elite' | 'elite-undo' | 'bottom' | 'bottom-undo'): Promise<void> {
  524. this.barActionError.set(''); this.barActionMessage.set('');
  525. if (this.className() !== 'GuestBar' || !this.draftId()) { this.barActionError.set('只能管理现有帖子'); return; }
  526. if (action === 'recycle' && !confirm('确认将该帖子移入回收站?')) return;
  527. const payload: Record<string, unknown> = { className: 'GuestBar', action, objectIds: [this.draftId()] };
  528. if (action === 'move') {
  529. const cateId = this.targetBarCategoryId();
  530. if (!Number.isInteger(cateId) || cateId < 1) { this.barActionError.set('请输入有效目标贴吧分类 ID'); return; }
  531. payload['cateId'] = cateId;
  532. }
  533. this.updatingBar.set(true);
  534. try {
  535. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('barBatch', payload);
  536. if (result.results?.[0]) { this.draft.set(result.results[0]); this.targetBarCategoryId.set(Number(result.results[0]['cateId']) || 0); }
  537. this.barActionMessage.set('帖子状态已更新'); await this.load();
  538. } catch (error) { this.barActionError.set(error instanceof Error ? error.message : '帖子操作失败'); }
  539. finally { this.updatingBar.set(false); }
  540. }
  541. async applyBulkBarAction(action: 'audit' | 'unaudit' | 'recycle' | 'recover' | 'move' | 'top-global' | 'top-section' | 'top-undo' | 'elite' | 'elite-undo' | 'bottom' | 'bottom-undo'): Promise<void> {
  542. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  543. if (this.className() !== 'GuestBar' || !objectIds.length) { this.bulkError.set('请先选择帖子'); return; }
  544. if (action === 'recycle' && !confirm(`确认将选中的 ${objectIds.length} 条帖子移入回收站?`)) return;
  545. const payload: Record<string, unknown> = { className: 'GuestBar', action, objectIds };
  546. if (action === 'move') {
  547. const cateId = this.targetBarCategoryId();
  548. if (!Number.isInteger(cateId) || cateId < 1) { this.bulkError.set('请输入有效目标贴吧分类 ID'); return; }
  549. payload['cateId'] = cateId;
  550. }
  551. this.updatingBar.set(true);
  552. try { const result = await this.functions.admin<{ updated: number }>('barBatch', payload); await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条帖子`); }
  553. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量帖子操作失败'); }
  554. finally { this.updatingBar.set(false); }
  555. }
  556. async applyBulkDictionaryAction(action: 'enable' | 'disable' | 'delete'): Promise<void> {
  557. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  558. if (!['Datadiccategory', 'Datadic'].includes(this.className()) || !objectIds.length) { this.bulkError.set('请先选择字典记录'); return; }
  559. if (action === 'delete' && !confirm(`确认删除选中的 ${objectIds.length} 条字典记录?`)) return;
  560. this.updatingDictionary.set(true);
  561. try {
  562. const result = await this.functions.admin<{ updated: number }>('dictionaryBatch', { className: this.className(), action, objectIds });
  563. await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条字典记录`);
  564. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量字典操作失败'); }
  565. finally { this.updatingDictionary.set(false); }
  566. }
  567. async applyBulkGradeDelete(): Promise<void> {
  568. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  569. if (!['GradeCate', 'Grade'].includes(this.className()) || !objectIds.length) { this.bulkError.set('请先选择多级字典记录'); return; }
  570. if (!confirm(`确认删除选中的 ${objectIds.length} 条多级字典记录?`)) return;
  571. this.updatingGrade.set(true);
  572. try { const result = await this.functions.admin<{ updated: number }>('gradeBatch', { className: this.className(), action: 'delete', objectIds }); await this.load(); this.bulkMessage.set(`已删除 ${result.updated} 条多级字典记录`); }
  573. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量删除多级字典失败'); }
  574. finally { this.updatingGrade.set(false); }
  575. }
  576. async applyBulkCurrencyDelete(): Promise<void> {
  577. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  578. if (this.className() !== 'Currency' || !objectIds.length) { this.bulkError.set('请先选择货币记录'); return; }
  579. if (!confirm(`确认删除选中的 ${objectIds.length} 条货币记录?`)) return;
  580. this.updatingCurrency.set(true);
  581. try { const result = await this.functions.admin<{ updated: number }>('currencyBatch', { className: 'Currency', action: 'delete', objectIds }); await this.load(); this.bulkMessage.set(`已删除 ${result.updated} 条货币记录`); }
  582. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量删除货币失败'); }
  583. finally { this.updatingCurrency.set(false); }
  584. }
  585. async applyBulkHolidayDelete(): Promise<void> {
  586. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  587. if (this.className() !== 'SysHoliday' || !objectIds.length) { this.bulkError.set('请先选择节假日记录'); return; }
  588. if (!confirm(`确认删除选中的 ${objectIds.length} 条节假日记录?`)) return;
  589. this.updatingHoliday.set(true);
  590. try { const result = await this.functions.admin<{ updated: number }>('holidayBatch', { className: 'SysHoliday', action: 'delete', objectIds }); await this.load(); this.bulkMessage.set(`已删除 ${result.updated} 条节假日记录`); }
  591. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量删除节假日失败'); }
  592. finally { this.updatingHoliday.set(false); }
  593. }
  594. async applyBulkSearchNavigationAction(action: 'enable' | 'disable' | 'elite' | 'unelite' | 'order' | 'delete'): Promise<void> {
  595. const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  596. if (this.className() !== 'Search' || !objectIds.length) { this.bulkError.set('请先选择快捷入口'); return; }
  597. if (action === 'delete' && !confirm(`确认删除选中的 ${objectIds.length} 条快捷入口?`)) return;
  598. const payload: Record<string, unknown> = { className: 'Search', action, objectIds };
  599. if (action === 'order') {
  600. const start = this.searchNavigationOrderStart();
  601. if (!Number.isInteger(start) || start < 1 || start + objectIds.length - 1 > 1000000) { this.bulkError.set('请输入有效的起始排序'); return; }
  602. payload['orders'] = objectIds.map((objectId, index) => ({ objectId, orderId: start + index }));
  603. }
  604. this.updatingSearchNavigation.set(true);
  605. try { const result = await this.functions.admin<{ updated: number }>('searchNavigationBatch', payload); await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条快捷入口`); }
  606. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '批量处理快捷入口失败'); }
  607. finally { this.updatingSearchNavigation.set(false); }
  608. }
  609. async applyBulkAdvertisementAction(action: 'active' | 'pause' | 'audit' | 'unaudit' | 'delete'): Promise<void> {
  610. const className = this.className(); const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  611. if (!['AdZone', 'AdInfo'].includes(className) || !objectIds.length) { this.bulkError.set('请先选择广告位或广告内容'); return; }
  612. if (action === 'delete' && !confirm(`确认删除选中的 ${objectIds.length} 条${className === 'AdZone' ? '广告位' : '广告内容'}?`)) return;
  613. if (className === 'AdZone' && !['active', 'pause', 'delete'].includes(action)) { this.bulkError.set('广告位操作无效'); return; }
  614. if (className === 'AdInfo' && !['audit', 'unaudit', 'delete'].includes(action)) { this.bulkError.set('广告内容操作无效'); return; }
  615. this.updatingAdvertisement.set(true);
  616. try {
  617. const result = await this.functions.admin<{ updated: number }>(className === 'AdZone' ? 'adZoneBatch' : 'adInfoBatch', { className, action, objectIds });
  618. await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条${className === 'AdZone' ? '广告位' : '广告内容'}`);
  619. } catch (error) { this.bulkError.set(error instanceof Error ? error.message : '广告批量操作失败'); }
  620. finally { this.updatingAdvertisement.set(false); }
  621. }
  622. async loadAdPreview(): Promise<void> {
  623. this.adPreview.set([]); this.adPreviewError.set('');
  624. if (this.className() !== 'AdZone' || !this.draftId()) return;
  625. this.adPreviewLoading.set(true);
  626. try { const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('adPreview', { zoneObjectId: this.draftId() }); this.adPreview.set(result.results || []); }
  627. catch (error) { this.adPreviewError.set(error instanceof Error ? error.message : '广告位预览加载失败'); }
  628. finally { this.adPreviewLoading.set(false); }
  629. }
  630. async applyBulkFontShapeDelete(): Promise<void> {
  631. const className = this.className(); const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  632. if (!['FontPicShape', 'FontPicShapeType'].includes(className) || !objectIds.length) { this.bulkError.set('请先选择图形素材或分类'); return; }
  633. if (!confirm(`确认删除选中的 ${objectIds.length} 条${className === 'FontPicShape' ? '图形素材' : '图形分类'}?`)) return;
  634. this.updatingFontShape.set(true);
  635. try { const result = await this.functions.admin<{ updated: number }>(className === 'FontPicShape' ? 'fontShapeBatch' : 'fontShapeTypeBatch', { className, action: 'delete', objectIds }); await this.load(); this.bulkMessage.set(`已删除 ${result.updated} 条${className === 'FontPicShape' ? '图形素材' : '图形分类'}`); }
  636. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '图形删除失败'); }
  637. finally { this.updatingFontShape.set(false); }
  638. }
  639. async applyBulkSurveyAction(action: 'start' | 'stop' | 'sort' | 'delete'): Promise<void> {
  640. const className = this.className(); const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  641. const allowed = className === 'DesignAsk' ? ['start', 'stop', 'delete'] : className === 'DesignQuestion' ? ['sort', 'delete'] : className === 'DesignAnswer' ? ['delete'] : [];
  642. if (!allowed.includes(action) || !objectIds.length) { this.bulkError.set('请先选择可执行该操作的问卷记录'); return; }
  643. if (action === 'delete' && !confirm(`确认删除选中的 ${objectIds.length} 条问卷记录?`)) return;
  644. const payload: Record<string, unknown> = { className, action, objectIds };
  645. if (action === 'sort') {
  646. const start = this.surveyOrderStart();
  647. if (!Number.isInteger(start) || start < 1 || start + objectIds.length - 1 > 1000000) { this.bulkError.set('请输入有效的起始排序'); return; }
  648. payload['orders'] = objectIds.map((objectId, index) => ({ objectId, orderId: start + index }));
  649. }
  650. this.updatingSurvey.set(true);
  651. try { const result = await this.functions.admin<{ updated: number }>('surveyBatch', payload); await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条问卷记录`); }
  652. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '问卷批量操作失败'); }
  653. finally { this.updatingSurvey.set(false); }
  654. }
  655. async loadSurveyChart(): Promise<void> {
  656. this.surveyChart.set(null); this.surveyChartError.set('');
  657. if (this.className() !== 'DesignAnswer' || !this.filterSurveyId()) return;
  658. this.surveyChartLoading.set(true);
  659. try { this.surveyChart.set(await this.functions.admin<SurveyChart>('surveyResultChart', { askId: this.filterSurveyId() })); }
  660. catch (error) { this.surveyChartError.set(error instanceof Error ? error.message : '问卷统计加载失败'); }
  661. finally { this.surveyChartLoading.set(false); }
  662. }
  663. async applyBulkServiceDelete(): Promise<void> {
  664. const className = this.className(); const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  665. if (!['ServiceSeat', 'Temp'].includes(className) || !objectIds.length) { this.bulkError.set('请先选择客服席位或欢迎语'); return; }
  666. if (!confirm(`确认删除选中的 ${objectIds.length} 条${className === 'ServiceSeat' ? '客服席位' : '欢迎语'}?`)) return;
  667. this.updatingService.set(true);
  668. try { const result = await this.functions.admin<{ updated: number }>('serviceBatch', { className, action: 'delete', objectIds }); await this.load(); this.bulkMessage.set(`已删除 ${result.updated} 条客服记录`); }
  669. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '客服记录删除失败'); }
  670. finally { this.updatingService.set(false); }
  671. }
  672. async applyBulkStoreAction(action: 'audit' | 'unaudit' | 'elite' | 'unelite' | 'delete'): Promise<void> {
  673. const className = this.className(); const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
  674. const allowed = className === 'StoreApplication' ? ['audit', 'unaudit', 'elite', 'unelite'] : className === 'StoreStyle' ? ['delete'] : [];
  675. if (!allowed.includes(action) || !objectIds.length) { this.bulkError.set(action === 'delete' && className === 'StoreApplication' ? '店铺删除因商品主表缺失而阻塞' : '请先选择可执行该操作的店铺记录'); return; }
  676. if (action === 'delete' && !confirm(`确认删除选中的 ${objectIds.length} 条店铺样式?`)) return;
  677. this.updatingStore.set(true);
  678. try { const result = await this.functions.admin<{ updated: number }>('storeBatch', { className, action, objectIds }); await this.load(); this.bulkMessage.set(`已处理 ${result.updated} 条店铺记录`); }
  679. catch (error) { this.bulkError.set(error instanceof Error ? error.message : '店铺批量操作失败'); }
  680. finally { this.updatingStore.set(false); }
  681. }
  682. async remove(row: Record<string, unknown>): Promise<void> {
  683. const objectId = String(row['objectId'] ?? '');
  684. const verb = ['CommonModel', 'Node', 'Guestbook'].includes(this.className()) ? '移入回收站' : '删除';
  685. if (!objectId || !confirm(`确认${verb} ${this.className()} / ${objectId}?`)) return;
  686. try {
  687. if (this.className() === 'Search') await this.functions.admin('searchNavigationBatch', { className: 'Search', action: 'delete', objectIds: [objectId] });
  688. else if (this.className() === 'AdZone') await this.functions.admin('adZoneBatch', { className: 'AdZone', action: 'delete', objectIds: [objectId] });
  689. else if (this.className() === 'AdInfo') await this.functions.admin('adInfoBatch', { className: 'AdInfo', action: 'delete', objectIds: [objectId] });
  690. else if (this.className() === 'FontPicShape') await this.functions.admin('fontShapeBatch', { className: 'FontPicShape', action: 'delete', objectIds: [objectId] });
  691. else if (this.className() === 'FontPicShapeType') await this.functions.admin('fontShapeTypeBatch', { className: 'FontPicShapeType', action: 'delete', objectIds: [objectId] });
  692. else if (['DesignAsk', 'DesignQuestion', 'DesignAnswer'].includes(this.className())) await this.functions.admin('surveyBatch', { className: this.className(), action: 'delete', objectIds: [objectId] });
  693. else if (['ServiceSeat', 'Temp'].includes(this.className())) await this.functions.admin('serviceBatch', { className: this.className(), action: 'delete', objectIds: [objectId] });
  694. else if (['StoreApplication', 'StoreStyle'].includes(this.className())) await this.functions.admin('storeBatch', { className: this.className(), action: 'delete', objectIds: [objectId] });
  695. else await this.functions.admin('delete', { className: this.className(), objectId });
  696. await this.load();
  697. }
  698. catch (error) { this.error.set(error instanceof Error ? error.message : '删除失败'); }
  699. }
  700. display(value: unknown): string {
  701. if (value == null || value === '') return '—';
  702. if (typeof value === 'object') {
  703. const data = value as Record<string, unknown>;
  704. return String(data['name'] ?? data['title'] ?? data['username'] ?? data['objectId'] ?? JSON.stringify(value));
  705. }
  706. return String(value);
  707. }
  708. groupIdOf(group: Record<string, unknown>): number { return Number(group['groupId']) || 0; }
  709. groupLabel(group: Record<string, unknown>): string { return `${String(group['groupName'] || group['name'] || '未命名组')}(${this.groupIdOf(group)})`; }
  710. dictionaryCategoryIdOf(category: Record<string, unknown>): number { return Number(category['diccateid']) || 0; }
  711. gradeCategoryIdOf(category: Record<string, unknown>): number { return Number(category['cateId']) || 0; }
  712. adZoneIdOf(zone: Record<string, unknown>): string { return String(zone['id'] || ''); }
  713. adZoneLabel(zone: Record<string, unknown>): string { return `${String(zone['name'] || '未命名广告位')}(${this.adZoneIdOf(zone)})`; }
  714. fontShapeTypeIdOf(type: Record<string, unknown>): number { return Number(type['id']) || 0; }
  715. fontShapeTypeLabel(type: Record<string, unknown>): string { return `${String(type['name'] || '未命名分类')}(${this.fontShapeTypeIdOf(type)})`; }
  716. surveyIdOf(survey: Record<string, unknown>): number { return Number(survey['id']) || 0; }
  717. surveyLabel(survey: Record<string, unknown>): string { return `${String(survey['title'] || '未命名问卷')}(${this.surveyIdOf(survey)})`; }
  718. storeStyleIdOf(style: Record<string, unknown>): number { return Number(style['id']) || 0; }
  719. storeStyleLabel(style: Record<string, unknown>): string { return `${String(style['styleName'] || '未命名样式')}(${this.storeStyleIdOf(style)})`; }
  720. contentStatusValue(): number { return Number(this.draft()['status']) || 0; }
  721. contentStatusLabel(status: number): string { return ({ [-3]: '草稿', [-2]: '回收站', [-1]: '未通过', 0: '待审核', 99: '已审核' } as Record<number, string>)[status] || String(status); }
  722. nodeStatusValue(): number { return Number(this.draft()['zstatus'] ?? 99); }
  723. private async loadUserGroups(): Promise<void> {
  724. try {
  725. const groups = await this.functions.admin<ResourcePage>('list', { className: 'Group', page: 1, pageSize: 100, sort: 'orderId', order: 'asc' });
  726. this.userGroups.set(groups.results);
  727. } catch (error) { this.userGroups.set([]); this.userActionError.set(error instanceof Error ? error.message : '用户组加载失败'); }
  728. }
  729. private async loadDictionaryCategories(): Promise<void> {
  730. try {
  731. const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('dictionaryCategories', { enabledOnly: false });
  732. this.dictionaryCategories.set(result.results || []);
  733. } catch (error) { this.dictionaryCategories.set([]); this.error.set(error instanceof Error ? error.message : '字典分类加载失败'); }
  734. }
  735. private async loadGradeCategories(): Promise<void> {
  736. try { const result = await this.functions.admin<{ results: Record<string, unknown>[] }>('gradeCategories', {}); this.gradeCategories.set(result.results || []); }
  737. catch (error) { this.gradeCategories.set([]); this.error.set(error instanceof Error ? error.message : '多级字典分类加载失败'); }
  738. }
  739. private async loadAdZones(): Promise<void> {
  740. try { const result = await this.functions.admin<ResourcePage>('adZones', { className: 'AdZone', page: 1, pageSize: 1000, search: '', type: '', status: -100 }); this.adZones.set(result.results || []); }
  741. catch (error) { this.adZones.set([]); this.error.set(error instanceof Error ? error.message : '广告位选项加载失败'); }
  742. }
  743. private async loadFontShapeTypes(): Promise<void> {
  744. try { const result = await this.functions.admin<ResourcePage>('fontShapeTypes', { className: 'FontPicShapeType', page: 1, pageSize: 1000, search: '' }); this.fontShapeTypes.set(result.results || []); }
  745. catch (error) { this.fontShapeTypes.set([]); this.error.set(error instanceof Error ? error.message : '图形分类选项加载失败'); }
  746. }
  747. private async loadSurveys(): Promise<void> {
  748. try { const result = await this.functions.admin<ResourcePage>('surveys', { className: 'DesignAsk', page: 1, pageSize: 100, search: '', status: -100 }); this.surveys.set(result.results || []); }
  749. catch (error) { this.surveys.set([]); this.error.set(error instanceof Error ? error.message : '问卷选项加载失败'); }
  750. }
  751. private async loadStoreStyles(): Promise<void> {
  752. try { const result = await this.functions.admin<ResourcePage>('storeStyles', { className: 'StoreStyle', page: 1, pageSize: 100, search: '' }); this.storeStyles.set(result.results || []); }
  753. catch (error) { this.storeStyles.set([]); this.error.set(error instanceof Error ? error.message : '店铺样式选项加载失败'); }
  754. }
  755. private resetPasswordFields(): void { this.newPassword.set(''); this.confirmPassword.set(''); this.passwordMessage.set(''); this.passwordError.set(''); }
  756. private resetCreateUserFields(): void { this.createUsername.set(''); this.createPassword.set(''); this.createConfirmPassword.set(''); this.createDisplayName.set(''); this.createMobile.set(''); this.createInviteUsername.set(''); this.createUserError.set(''); }
  757. 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(''); }
  758. 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(''); }
  759. private resetNodeActions(detail: Record<string, unknown> = {}): void { this.targetNodeParentId.set(Number(detail['parentId']) || 0); this.nodeActionError.set(''); this.nodeActionMessage.set(''); }
  760. private resetSpecialActions(detail: Record<string, unknown> = {}): void { this.targetSpecialParentId.set(Number(detail['pid']) || 0); this.specialActionError.set(''); this.specialActionMessage.set(''); }
  761. 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(''); }
  762. private resetGuestCategoryActions(detail: Record<string, unknown> = {}): void { this.guestCategoryType.set(Number(detail['gtype']) || 0); this.targetGuestCategoryParentId.set(Number(detail['parentId']) || 0); }
  763. private resetBarActions(detail: Record<string, unknown> = {}): void { this.targetBarCategoryId.set(Number(detail['cateId']) || 0); this.barActionError.set(''); this.barActionMessage.set(''); }
  764. 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); }
  765. private resetExamPointActions(detail: Record<string, unknown> = {}): void { this.targetExamPointParentId.set(Number(detail['tid']) || 0); this.examPointOrder.set(Number(detail['orderBy']) || 0); }
  766. 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); }
  767. private resetTeacherActions(detail: Record<string, unknown> = {}): void { this.targetTeacherClassId.set(Number(detail['tclsss']) || 0); }
  768. private resetDictionaryActions(detail: Record<string, unknown> = {}): void { this.targetDictionaryCategoryId.set(Number(detail['diccate']) || 0); }
  769. private resetGradeActions(detail: Record<string, unknown> = {}): void { this.targetGradeCategoryId.set(Number(detail['cate']) || this.filterGradeCategoryId()); this.targetGradeParentId.set(Number(detail['parentId']) || this.filterGradeParentId()); }
  770. private resetAdActions(detail: Record<string, unknown> = {}): void { this.targetAdZoneId.set(String(detail['zoneId'] || this.filterAdInfoZoneId() || '')); this.adPreview.set([]); this.adPreviewError.set(''); this.adPreviewLoading.set(false); }
  771. private resetFontShapeActions(detail: Record<string, unknown> = {}): void { this.targetFontShapeTypeId.set(Number(detail['typeId']) || this.filterFontShapeTypeId()); this.fontShapePreview.set(String(detail['shape'] || '')); }
  772. private resetSurveyActions(): void { this.surveyOrderStart.set(1); this.surveyChart.set(null); this.surveyChartError.set(''); this.surveyChartLoading.set(false); }
  773. private resetServiceActions(detail: Record<string, unknown> = {}): void { this.targetServiceSeatUsername.set(String(detail['sRemrk'] || '')); }
  774. private resetStoreActions(detail: Record<string, unknown> = {}): void { this.targetStoreUsername.set(String(detail['userName'] || '')); this.targetStoreStyleId.set(Number(detail['storeStyleId']) || 0); }
  775. private resetTagKeyActions(detail: Record<string, unknown> = {}): void { this.tagKeyContent.set(String(detail['content'] || '')); }
  776. }