pages_know_info.tsx 11 KB

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