pages_know.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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
  9. } from 'antd';
  10. import {
  11. UploadOutlined,
  12. FileImageOutlined,
  13. FileExcelOutlined,
  14. FileWordOutlined,
  15. FilePdfOutlined,
  16. FileOutlined,
  17. } from '@ant-design/icons';
  18. import {
  19. useQuery,
  20. } from '@tanstack/react-query';
  21. import dayjs from 'dayjs';
  22. import weekday from 'dayjs/plugin/weekday';
  23. import localeData from 'dayjs/plugin/localeData';
  24. import 'dayjs/locale/zh-cn';
  25. import type {
  26. FileLibrary, FileCategory, KnowInfo
  27. } from '../share/types.ts';
  28. import {
  29. AuditStatus,AuditStatusNameMap,
  30. OssType,
  31. } from '../share/types.ts';
  32. import { getEnumOptions } from './utils.ts';
  33. import {
  34. FileAPI,
  35. UserAPI,
  36. } from './api.ts';
  37. // 配置 dayjs 插件
  38. dayjs.extend(weekday);
  39. dayjs.extend(localeData);
  40. // 设置 dayjs 语言
  41. dayjs.locale('zh-cn');
  42. const { Title } = Typography;
  43. // 知识库管理页面组件
  44. export const KnowInfoPage = () => {
  45. const [modalVisible, setModalVisible] = useState(false);
  46. const [formMode, setFormMode] = useState<'create' | 'edit'>('create');
  47. const [editingId, setEditingId] = useState<number | null>(null);
  48. const [form] = Form.useForm();
  49. const [isLoading, setIsLoading] = useState(false);
  50. const [searchParams, setSearchParams] = useState({
  51. title: '',
  52. category: '',
  53. page: 1,
  54. limit: 10,
  55. });
  56. // 使用React Query获取知识库文章列表
  57. const { data: articlesData, isLoading: isListLoading, refetch } = useQuery({
  58. queryKey: ['articles', searchParams],
  59. queryFn: async () => {
  60. const { title, category, page, limit } = searchParams;
  61. const params = new URLSearchParams();
  62. if (title) params.append('title', title);
  63. if (category) params.append('category', category);
  64. params.append('page', String(page));
  65. params.append('limit', String(limit));
  66. const response = await fetch(`/api/know-info?${params.toString()}`, {
  67. headers: {
  68. 'Authorization': `Bearer ${localStorage.getItem('token')}`,
  69. },
  70. });
  71. if (!response.ok) {
  72. throw new Error('获取知识库文章列表失败');
  73. }
  74. return await response.json();
  75. }
  76. });
  77. const articles = articlesData?.data || [];
  78. const pagination = articlesData?.pagination || { current: 1, pageSize: 10, total: 0 };
  79. // 获取单个知识库文章
  80. const fetchArticle = async (id: number) => {
  81. try {
  82. const response = await fetch(`/api/know-info/${id}`, {
  83. headers: {
  84. 'Authorization': `Bearer ${localStorage.getItem('token')}`,
  85. },
  86. });
  87. if (!response.ok) {
  88. throw new Error('获取知识库文章详情失败');
  89. }
  90. return await response.json();
  91. } catch (error) {
  92. message.error('获取知识库文章详情失败');
  93. return null;
  94. }
  95. };
  96. // 处理表单提交
  97. const handleSubmit = async (values: Partial<KnowInfo>) => {
  98. setIsLoading(true);
  99. try {
  100. const url = formMode === 'create'
  101. ? '/api/know-info'
  102. : `/api/know-info/${editingId}`;
  103. const method = formMode === 'create' ? 'POST' : 'PUT';
  104. const response = await fetch(url, {
  105. method,
  106. headers: {
  107. 'Content-Type': 'application/json',
  108. 'Authorization': `Bearer ${localStorage.getItem('token')}`,
  109. },
  110. body: JSON.stringify(values),
  111. });
  112. if (!response.ok) {
  113. throw new Error(formMode === 'create' ? '创建知识库文章失败' : '更新知识库文章失败');
  114. }
  115. message.success(formMode === 'create' ? '创建知识库文章成功' : '更新知识库文章成功');
  116. setModalVisible(false);
  117. form.resetFields();
  118. refetch();
  119. } catch (error) {
  120. message.error((error as Error).message);
  121. } finally {
  122. setIsLoading(false);
  123. }
  124. };
  125. // 处理编辑
  126. const handleEdit = async (id: number) => {
  127. const article = await fetchArticle(id);
  128. if (article) {
  129. setFormMode('edit');
  130. setEditingId(id);
  131. form.setFieldsValue(article);
  132. setModalVisible(true);
  133. }
  134. };
  135. // 处理删除
  136. const handleDelete = async (id: number) => {
  137. try {
  138. const response = await fetch(`/api/know-info/${id}`, {
  139. method: 'DELETE',
  140. headers: {
  141. 'Authorization': `Bearer ${localStorage.getItem('token')}`,
  142. },
  143. });
  144. if (!response.ok) {
  145. throw new Error('删除知识库文章失败');
  146. }
  147. message.success('删除知识库文章成功');
  148. refetch();
  149. } catch (error) {
  150. message.error((error as Error).message);
  151. }
  152. };
  153. // 处理搜索
  154. const handleSearch = (values: any) => {
  155. setSearchParams(prev => ({
  156. ...prev,
  157. title: values.title || '',
  158. category: values.category || '',
  159. page: 1,
  160. }));
  161. };
  162. // 处理分页
  163. const handlePageChange = (page: number, pageSize?: number) => {
  164. setSearchParams(prev => ({
  165. ...prev,
  166. page,
  167. limit: pageSize || prev.limit,
  168. }));
  169. };
  170. // 处理添加
  171. const handleAdd = () => {
  172. setFormMode('create');
  173. setEditingId(null);
  174. form.resetFields();
  175. setModalVisible(true);
  176. };
  177. // 审核状态映射
  178. const auditStatusOptions = getEnumOptions(AuditStatus, AuditStatusNameMap);
  179. // 表格列定义
  180. const columns = [
  181. {
  182. title: 'ID',
  183. dataIndex: 'id',
  184. key: 'id',
  185. width: 80,
  186. },
  187. {
  188. title: '标题',
  189. dataIndex: 'title',
  190. key: 'title',
  191. },
  192. {
  193. title: '分类',
  194. dataIndex: 'category',
  195. key: 'category',
  196. },
  197. {
  198. title: '标签',
  199. dataIndex: 'tags',
  200. key: 'tags',
  201. render: (tags: string) => tags ? tags.split(',').map(tag => (
  202. <Tag key={tag}>{tag}</Tag>
  203. )) : null,
  204. },
  205. {
  206. title: '作者',
  207. dataIndex: 'author',
  208. key: 'author',
  209. },
  210. {
  211. title: '审核状态',
  212. dataIndex: 'audit_status',
  213. key: 'audit_status',
  214. render: (status: AuditStatus) => {
  215. let color = '';
  216. let text = '';
  217. switch(status) {
  218. case AuditStatus.PENDING:
  219. color = 'orange';
  220. text = '待审核';
  221. break;
  222. case AuditStatus.APPROVED:
  223. color = 'green';
  224. text = '已通过';
  225. break;
  226. case AuditStatus.REJECTED:
  227. color = 'red';
  228. text = '已拒绝';
  229. break;
  230. default:
  231. color = 'default';
  232. text = '未知';
  233. }
  234. return <Tag color={color}>{text}</Tag>;
  235. },
  236. },
  237. {
  238. title: '创建时间',
  239. dataIndex: 'created_at',
  240. key: 'created_at',
  241. render: (date: string) => new Date(date).toLocaleString(),
  242. },
  243. {
  244. title: '操作',
  245. key: 'action',
  246. render: (_: any, record: KnowInfo) => (
  247. <Space size="middle">
  248. <Button type="link" onClick={() => handleEdit(record.id)}>编辑</Button>
  249. <Popconfirm
  250. title="确定要删除这篇文章吗?"
  251. onConfirm={() => handleDelete(record.id)}
  252. okText="确定"
  253. cancelText="取消"
  254. >
  255. <Button type="link" danger>删除</Button>
  256. </Popconfirm>
  257. </Space>
  258. ),
  259. },
  260. ];
  261. return (
  262. <div>
  263. <Card title="知识库管理" className="mb-4">
  264. <Form
  265. layout="inline"
  266. onFinish={handleSearch}
  267. style={{ marginBottom: '16px' }}
  268. >
  269. <Form.Item name="title" label="标题">
  270. <Input placeholder="请输入文章标题" />
  271. </Form.Item>
  272. <Form.Item name="category" label="分类">
  273. <Input placeholder="请输入文章分类" />
  274. </Form.Item>
  275. <Form.Item>
  276. <Space>
  277. <Button type="primary" htmlType="submit">
  278. 搜索
  279. </Button>
  280. <Button onClick={() => {
  281. setSearchParams({
  282. title: '',
  283. category: '',
  284. page: 1,
  285. limit: 10,
  286. });
  287. }}>
  288. 重置
  289. </Button>
  290. <Button type="primary" onClick={handleAdd}>
  291. 添加文章
  292. </Button>
  293. </Space>
  294. </Form.Item>
  295. </Form>
  296. <Table
  297. columns={columns}
  298. dataSource={articles}
  299. rowKey="id"
  300. loading={isListLoading}
  301. pagination={{
  302. current: pagination.current,
  303. pageSize: pagination.pageSize,
  304. total: pagination.total,
  305. onChange: handlePageChange,
  306. showSizeChanger: true,
  307. }}
  308. />
  309. </Card>
  310. <Modal
  311. title={formMode === 'create' ? '添加知识库文章' : '编辑知识库文章'}
  312. open={modalVisible}
  313. onOk={() => form.submit()}
  314. onCancel={() => setModalVisible(false)}
  315. width={800}
  316. >
  317. <Form
  318. form={form}
  319. layout="vertical"
  320. onFinish={handleSubmit}
  321. initialValues={{
  322. audit_status: AuditStatus.PENDING,
  323. }}
  324. >
  325. <Row gutter={16}>
  326. <Col span={12}>
  327. <Form.Item
  328. name="title"
  329. label="文章标题"
  330. rules={[{ required: true, message: '请输入文章标题' }]}
  331. >
  332. <Input placeholder="请输入文章标题" />
  333. </Form.Item>
  334. </Col>
  335. <Col span={12}>
  336. <Form.Item
  337. name="category"
  338. label="文章分类"
  339. >
  340. <Input placeholder="请输入文章分类" />
  341. </Form.Item>
  342. </Col>
  343. </Row>
  344. <Form.Item
  345. name="tags"
  346. label="文章标签"
  347. help="多个标签请用英文逗号分隔,如: 服务器,网络,故障"
  348. >
  349. <Input placeholder="请输入文章标签,多个标签请用英文逗号分隔" />
  350. </Form.Item>
  351. <Form.Item
  352. name="content"
  353. label="文章内容"
  354. rules={[{ required: true, message: '请输入文章内容' }]}
  355. >
  356. <Input.TextArea rows={15} placeholder="请输入文章内容,支持Markdown格式" />
  357. </Form.Item>
  358. <Row gutter={16}>
  359. <Col span={12}>
  360. <Form.Item
  361. name="author"
  362. label="文章作者"
  363. >
  364. <Input placeholder="请输入文章作者" />
  365. </Form.Item>
  366. </Col>
  367. <Col span={12}>
  368. <Form.Item
  369. name="cover_url"
  370. label="封面图片URL"
  371. >
  372. <Input placeholder="请输入封面图片URL" />
  373. </Form.Item>
  374. </Col>
  375. </Row>
  376. <Form.Item
  377. name="audit_status"
  378. label="审核状态"
  379. >
  380. <Select options={auditStatusOptions} />
  381. </Form.Item>
  382. <Form.Item>
  383. <Space>
  384. <Button type="primary" htmlType="submit" loading={isLoading}>
  385. {formMode === 'create' ? '创建' : '保存'}
  386. </Button>
  387. <Button onClick={() => setModalVisible(false)}>取消</Button>
  388. </Space>
  389. </Form.Item>
  390. </Form>
  391. </Modal>
  392. </div>
  393. );
  394. };