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. console.log('article', article)
  115. if (article) {
  116. setFormMode('edit');
  117. setEditingId(id);
  118. form.setFieldsValue(article);
  119. setModalVisible(true);
  120. }
  121. };
  122. // 处理删除
  123. const handleDelete = async (id: number) => {
  124. try {
  125. await KnowInfoAPI.deleteKnowInfo(id);
  126. message.success('删除知识库文章成功');
  127. refetch();
  128. } catch (error) {
  129. message.error((error as Error).message);
  130. }
  131. };
  132. // 处理搜索
  133. const handleSearch = async (values: any) => {
  134. try {
  135. queryClient.removeQueries({ queryKey: ['knowInfos'] });
  136. setSearchParams({
  137. title: values.title || '',
  138. category: values.category || '',
  139. page: 1,
  140. limit: searchParams.limit,
  141. });
  142. } catch (error) {
  143. message.error('搜索失败');
  144. }
  145. };
  146. // 处理分页
  147. const handlePageChange = (page: number, pageSize?: number) => {
  148. setSearchParams(prev => ({
  149. ...prev,
  150. page,
  151. limit: pageSize || prev.limit,
  152. }));
  153. };
  154. // 处理添加
  155. const handleAdd = () => {
  156. setFormMode('create');
  157. setEditingId(null);
  158. form.resetFields();
  159. setModalVisible(true);
  160. };
  161. // 审核状态映射
  162. const auditStatusOptions = getEnumOptions(AuditStatus, AuditStatusNameMap);
  163. // 表格列定义
  164. const columns = [
  165. {
  166. title: 'ID',
  167. dataIndex: 'id',
  168. key: 'id',
  169. width: 80,
  170. },
  171. {
  172. title: '标题',
  173. dataIndex: 'title',
  174. key: 'title',
  175. },
  176. {
  177. title: '分类',
  178. dataIndex: 'category',
  179. key: 'category',
  180. },
  181. {
  182. title: '标签',
  183. dataIndex: 'tags',
  184. key: 'tags',
  185. render: (tags: string) => tags ? tags.split(',').map(tag => (
  186. <Tag key={tag}>{tag}</Tag>
  187. )) : null,
  188. },
  189. {
  190. title: '作者',
  191. dataIndex: 'author',
  192. key: 'author',
  193. },
  194. {
  195. title: '审核状态',
  196. dataIndex: 'audit_status',
  197. key: 'audit_status',
  198. render: (status: AuditStatus) => {
  199. let color = '';
  200. let text = '';
  201. switch(status) {
  202. case AuditStatus.PENDING:
  203. color = 'orange';
  204. text = '待审核';
  205. break;
  206. case AuditStatus.APPROVED:
  207. color = 'green';
  208. text = '已通过';
  209. break;
  210. case AuditStatus.REJECTED:
  211. color = 'red';
  212. text = '已拒绝';
  213. break;
  214. default:
  215. color = 'default';
  216. text = '未知';
  217. }
  218. return <Tag color={color}>{text}</Tag>;
  219. },
  220. },
  221. {
  222. title: '创建时间',
  223. dataIndex: 'created_at',
  224. key: 'created_at',
  225. render: (date: string) => new Date(date).toLocaleString(),
  226. },
  227. {
  228. title: '操作',
  229. key: 'action',
  230. render: (_: any, record: KnowInfo) => (
  231. <Space size="middle">
  232. <Button type="link" onClick={() => handleEdit(record.id)}>编辑</Button>
  233. <Popconfirm
  234. title="确定要删除这篇文章吗?"
  235. onConfirm={() => handleDelete(record.id)}
  236. okText="确定"
  237. cancelText="取消"
  238. >
  239. <Button type="link" danger>删除</Button>
  240. </Popconfirm>
  241. </Space>
  242. ),
  243. },
  244. ];
  245. return (
  246. <div>
  247. <Card title="知识库管理" className="mb-4">
  248. <Form
  249. form={searchForm}
  250. layout="inline"
  251. onFinish={handleSearch}
  252. style={{ marginBottom: '16px' }}
  253. >
  254. <Form.Item name="title" label="标题">
  255. <Input placeholder="请输入文章标题" />
  256. </Form.Item>
  257. <Form.Item name="category" label="分类">
  258. <Input placeholder="请输入文章分类" />
  259. </Form.Item>
  260. <Form.Item>
  261. <Space>
  262. <Button type="primary" htmlType="submit">
  263. 搜索
  264. </Button>
  265. <Button htmlType="reset" onClick={() => {
  266. searchForm.resetFields();
  267. setSearchParams({
  268. title: '',
  269. category: '',
  270. page: 1,
  271. limit: 10,
  272. });
  273. }}>
  274. 重置
  275. </Button>
  276. <Button type="primary" onClick={handleAdd}>
  277. 添加文章
  278. </Button>
  279. </Space>
  280. </Form.Item>
  281. </Form>
  282. <Table
  283. columns={columns}
  284. dataSource={articles}
  285. rowKey="id"
  286. loading={{
  287. spinning: isListLoading,
  288. tip: '正在加载数据...',
  289. }}
  290. pagination={{
  291. current: pagination.current,
  292. pageSize: pagination.pageSize,
  293. total: pagination.total,
  294. onChange: handlePageChange,
  295. showSizeChanger: true,
  296. showTotal: (total) => `共 ${total} 条`,
  297. }}
  298. />
  299. </Card>
  300. <Modal
  301. title={formMode === 'create' ? '添加知识库文章' : '编辑知识库文章'}
  302. open={modalVisible}
  303. onOk={() => {
  304. form.validateFields()
  305. .then(values => {
  306. handleSubmit(values);
  307. })
  308. .catch(info => {
  309. console.log('表单验证失败:', info);
  310. });
  311. }}
  312. onCancel={() => setModalVisible(false)}
  313. width={800}
  314. okText="确定"
  315. cancelText="取消"
  316. destroyOnClose
  317. >
  318. <Form
  319. form={form}
  320. layout="vertical"
  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>
  383. </Modal>
  384. </div>
  385. );
  386. };