pages_know_info.tsx 11 KB

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