pages_settings.tsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import React, { useState, useEffect } from 'react';
  2. import {
  3. Layout, Menu, Button, Table, Space,
  4. Form, Input, Select, message, Modal,
  5. Card, Spin, Row, Col, Breadcrumb, Avatar,
  6. Dropdown, ConfigProvider, theme, Typography,
  7. Switch, Badge, Image, Upload, Divider, Descriptions,
  8. Popconfirm, Tag, Statistic, DatePicker, Radio, Progress, Tabs, List, Alert, Collapse, Empty, Drawer, InputNumber,ColorPicker,
  9. Popover
  10. } from 'antd';
  11. import {
  12. UploadOutlined,
  13. ReloadOutlined,
  14. SaveOutlined,
  15. BgColorsOutlined
  16. } from '@ant-design/icons';
  17. import { debounce } from 'lodash';
  18. import {
  19. useQuery,
  20. useMutation,
  21. useQueryClient,
  22. } from '@tanstack/react-query';
  23. import dayjs from 'dayjs';
  24. import weekday from 'dayjs/plugin/weekday';
  25. import localeData from 'dayjs/plugin/localeData';
  26. import 'dayjs/locale/zh-cn';
  27. import type {
  28. FileLibrary, FileCategory, KnowInfo, SystemSetting, SystemSettingValue,
  29. ColorScheme
  30. } from '../share/types.ts';
  31. import { ThemeMode } from '../share/types.ts';
  32. import {
  33. SystemSettingGroup,
  34. SystemSettingKey,
  35. FontSize,
  36. CompactMode,
  37. AllowedFileType
  38. } from '../share/types.ts';
  39. import { getEnumOptions } from './utils.ts';
  40. import {
  41. SystemAPI,
  42. } from './api.ts';
  43. import { useTheme } from './hooks_sys.tsx';
  44. import { Uploader } from './components_uploader.tsx';
  45. // 配置 dayjs 插件
  46. dayjs.extend(weekday);
  47. dayjs.extend(localeData);
  48. // 设置 dayjs 语言
  49. dayjs.locale('zh-cn');
  50. const { Title } = Typography;
  51. // 分组标题映射
  52. const GROUP_TITLES: Record<typeof SystemSettingGroup[keyof typeof SystemSettingGroup], string> = {
  53. [SystemSettingGroup.BASIC]: '基础设置',
  54. [SystemSettingGroup.FEATURE]: '功能设置',
  55. [SystemSettingGroup.UPLOAD]: '上传设置',
  56. [SystemSettingGroup.NOTIFICATION]: '通知设置'
  57. };
  58. // 分组描述映射
  59. const GROUP_DESCRIPTIONS: Record<typeof SystemSettingGroup[keyof typeof SystemSettingGroup], string> = {
  60. [SystemSettingGroup.BASIC]: '配置站点的基本信息',
  61. [SystemSettingGroup.FEATURE]: '配置系统功能的开启状态',
  62. [SystemSettingGroup.UPLOAD]: '配置文件上传相关的参数',
  63. [SystemSettingGroup.NOTIFICATION]: '配置系统通知的触发条件'
  64. };
  65. export const SettingsPage = () => {
  66. const [form] = Form.useForm();
  67. const queryClient = useQueryClient();
  68. const { isDark } = useTheme();
  69. // 获取系统设置
  70. const { data: settingsData, isLoading: isLoadingSettings } = useQuery({
  71. queryKey: ['systemSettings'],
  72. queryFn: SystemAPI.getSettings,
  73. });
  74. // 更新系统设置
  75. const updateSettingsMutation = useMutation({
  76. mutationFn: (values: Partial<SystemSetting>[]) => SystemAPI.updateSettings(values),
  77. onSuccess: () => {
  78. message.success('基础设置已更新');
  79. queryClient.invalidateQueries({ queryKey: ['systemSettings'] });
  80. },
  81. onError: (error) => {
  82. message.error('更新基础设置失败');
  83. console.error('更新基础设置失败:', error);
  84. },
  85. });
  86. // 重置系统设置
  87. const resetSettingsMutation = useMutation({
  88. mutationFn: SystemAPI.resetSettings,
  89. onSuccess: () => {
  90. message.success('基础设置已重置');
  91. queryClient.invalidateQueries({ queryKey: ['systemSettings'] });
  92. },
  93. onError: (error) => {
  94. message.error('重置基础设置失败');
  95. console.error('重置基础设置失败:', error);
  96. },
  97. });
  98. // 初始化表单数据
  99. useEffect(() => {
  100. if (settingsData) {
  101. const formValues = settingsData.reduce((acc: Record<string, any>, group) => {
  102. group.settings.forEach(setting => {
  103. // 根据值的类型进行转换
  104. let value = setting.value;
  105. if (typeof value === 'string') {
  106. if (value === 'true' || value === 'false') {
  107. value = value === 'true';
  108. } else if (!isNaN(Number(value)) && !value.includes('.')) {
  109. value = parseInt(value, 10);
  110. } else if (setting.key === SystemSettingKey.ALLOWED_FILE_TYPES) {
  111. value = (value ? (value as string).split(',') : []) as unknown as string;
  112. }
  113. }
  114. acc[setting.key] = value;
  115. });
  116. return acc;
  117. }, {});
  118. form.setFieldsValue(formValues);
  119. }
  120. }, [settingsData, form]);
  121. // 处理表单提交
  122. const handleSubmit = async (values: Record<string, SystemSettingValue>) => {
  123. const settings = Object.entries(values).map(([key, value]) => ({
  124. key: key as typeof SystemSettingKey[keyof typeof SystemSettingKey],
  125. value: String(value),
  126. group: key.startsWith('SITE_') ? SystemSettingGroup.BASIC :
  127. key.startsWith('ENABLE_') || key.includes('LOGIN_') || key.includes('SESSION_') ? SystemSettingGroup.FEATURE :
  128. key.includes('UPLOAD_') || key.includes('FILE_') || key.includes('IMAGE_') ? SystemSettingGroup.UPLOAD :
  129. SystemSettingGroup.NOTIFICATION
  130. }));
  131. updateSettingsMutation.mutate(settings);
  132. };
  133. // 处理重置
  134. const handleReset = () => {
  135. Modal.confirm({
  136. title: '确认重置',
  137. content: '确定要将所有设置重置为默认值吗?此操作不可恢复。',
  138. okText: '确认',
  139. cancelText: '取消',
  140. onOk: () => {
  141. resetSettingsMutation.mutate();
  142. },
  143. });
  144. };
  145. // 根据设置类型渲染不同的输入控件
  146. const renderSettingInput = (setting: SystemSetting) => {
  147. const value = setting.value;
  148. if (typeof value === 'boolean' || value === 'true' || value === 'false') {
  149. return <Switch checkedChildren="开启" unCheckedChildren="关闭" />;
  150. }
  151. if (setting.key === SystemSettingKey.ALLOWED_FILE_TYPES) {
  152. return <Select
  153. mode="tags"
  154. placeholder="请输入允许的文件类型"
  155. tokenSeparators={[',']}
  156. options={Object.values(AllowedFileType).map(type => ({
  157. label: type.toUpperCase(),
  158. value: type
  159. }))}
  160. />;
  161. }
  162. if (setting.key.includes('MAX_SIZE') || setting.key.includes('ATTEMPTS') ||
  163. setting.key.includes('TIMEOUT') || setting.key.includes('MAX_WIDTH')) {
  164. return <InputNumber min={1} style={{ width: '100%' }} />;
  165. }
  166. if (setting.key === SystemSettingKey.SITE_LOGO || setting.key === SystemSettingKey.SITE_FAVICON) {
  167. return (
  168. <div>
  169. {value && <img src={String(value)} alt="图片" style={{ width: 100, height: 100, objectFit: 'contain', marginBottom: 8 }} />}
  170. <div style={{ width: 100 }}>
  171. <Uploader
  172. maxSize={2 * 1024 * 1024}
  173. prefix={setting.key === SystemSettingKey.SITE_LOGO ? 'logo/' : 'favicon/'}
  174. allowedTypes={['image/jpeg', 'image/png', 'image/svg+xml', 'image/x-icon']}
  175. onSuccess={(fileUrl) => {
  176. form.setFieldValue(setting.key, fileUrl);
  177. updateSettingsMutation.mutate([{
  178. key: setting.key,
  179. value: fileUrl,
  180. group: SystemSettingGroup.BASIC
  181. }]);
  182. }}
  183. onError={(error) => {
  184. message.error(`上传失败:${error.message}`);
  185. }}
  186. />
  187. </div>
  188. </div>
  189. );
  190. }
  191. return <Input placeholder={`请输入${setting.description || setting.key}`} />;
  192. };
  193. return (
  194. <div>
  195. <Card
  196. title={
  197. <Space>
  198. <Title level={2} style={{ margin: 0 }}>系统设置</Title>
  199. </Space>
  200. }
  201. extra={
  202. <Space>
  203. <Button
  204. icon={<ReloadOutlined />}
  205. onClick={handleReset}
  206. loading={resetSettingsMutation.isPending}
  207. >
  208. 重置默认
  209. </Button>
  210. </Space>
  211. }
  212. >
  213. <Spin spinning={isLoadingSettings || updateSettingsMutation.isPending}>
  214. <Tabs
  215. type="card"
  216. items={Object.values(SystemSettingGroup).map(group => ({
  217. key: group,
  218. label: String(GROUP_TITLES[group]),
  219. children: (
  220. <div>
  221. <Alert
  222. message={GROUP_DESCRIPTIONS[group]}
  223. type="info"
  224. showIcon
  225. style={{ marginBottom: 24 }}
  226. />
  227. <Form
  228. form={form}
  229. layout="vertical"
  230. onFinish={handleSubmit}
  231. >
  232. {settingsData
  233. ?.find(g => g.name === group)
  234. ?.settings.map(setting => (
  235. <Form.Item
  236. key={setting.key}
  237. label={setting.description || setting.key}
  238. name={setting.key}
  239. rules={[{ required: true, message: `请输入${setting.description || setting.key}` }]}
  240. >
  241. {renderSettingInput(setting)}
  242. </Form.Item>
  243. ))}
  244. <Form.Item>
  245. <Button
  246. type="primary"
  247. htmlType="submit"
  248. icon={<SaveOutlined />}
  249. loading={updateSettingsMutation.isPending}
  250. >
  251. 保存设置
  252. </Button>
  253. </Form.Item>
  254. </Form>
  255. </div>
  256. )
  257. }))}
  258. />
  259. </Spin>
  260. </Card>
  261. </div>
  262. );
  263. };