pages_settings.tsx 8.9 KB

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