pages_alert_notify_config.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import React, { useState, useEffect } from 'react';
  2. import {
  3. Button, Table, Space,
  4. Form, Input, Select, message, Modal, Badge,
  5. Popconfirm, Tag, Card
  6. } from 'antd';
  7. import 'dayjs/locale/zh-cn';
  8. // 从share/types.ts导入所有类型,包括MapMode
  9. import type {
  10. AlertNotifyConfig
  11. } from '../share/monitorTypes.ts';
  12. import {
  13. AlertLevel, NotifyType,
  14. AlertLevelNameMap,
  15. NotifyTypeNameMap,
  16. } from '../share/monitorTypes.ts';
  17. import {
  18. EnableStatus, EnableStatusNameMap,
  19. } from '../share/types.ts';
  20. import { getEnumOptions } from './utils.ts';
  21. import { DeviceInstanceAPI, UserAPI, AlertNotifyConfigAPI } from './api/index.ts';
  22. // 告警通知配置页面
  23. export const AlertNotifyConfigPage = () => {
  24. const [loading, setLoading] = useState(false);
  25. const [configData, setConfigData] = useState<AlertNotifyConfig[]>([]);
  26. const [pagination, setPagination] = useState({
  27. current: 1,
  28. pageSize: 10,
  29. total: 0,
  30. });
  31. const [deviceOptions, setDeviceOptions] = useState<{label: string, value: number}[]>([]);
  32. const [userOptions, setUserOptions] = useState<{label: string, value: number}[]>([]);
  33. const [modalVisible, setModalVisible] = useState(false);
  34. const [modalTitle, setModalTitle] = useState('新增告警通知配置');
  35. const [currentRecord, setCurrentRecord] = useState<AlertNotifyConfig | null>(null);
  36. const [formRef] = Form.useForm();
  37. const [modalForm] = Form.useForm();
  38. useEffect(() => {
  39. fetchDeviceOptions();
  40. fetchUserOptions();
  41. fetchConfigData();
  42. }, [pagination.current, pagination.pageSize]);
  43. const fetchDeviceOptions = async () => {
  44. try {
  45. const response = await DeviceInstanceAPI.getDeviceInstances();
  46. if (response && response.data) {
  47. const options = response.data.map((device) => ({
  48. label: device.asset_name || `设备${device.id}`,
  49. value: device.id
  50. }));
  51. setDeviceOptions(options);
  52. }
  53. } catch (error) {
  54. console.error('获取设备列表失败:', error);
  55. message.error('获取设备列表失败');
  56. }
  57. };
  58. const fetchUserOptions = async () => {
  59. try {
  60. const response = await UserAPI.getUsers();
  61. if (response && response.data) {
  62. const options = response.data.map((user) => ({
  63. label: user.nickname || user.username,
  64. value: user.id
  65. }));
  66. setUserOptions(options);
  67. }
  68. } catch (error) {
  69. console.error('获取用户列表失败:', error);
  70. message.error('获取用户列表失败');
  71. }
  72. };
  73. const fetchConfigData = async () => {
  74. setLoading(true);
  75. try {
  76. const values = formRef.getFieldsValue();
  77. const params = {
  78. page: pagination.current,
  79. pageSize: pagination.pageSize,
  80. device_id: values.device_id,
  81. alert_level: values.alert_level,
  82. notify_type: values.notify_type,
  83. is_enabled: values.is_enabled,
  84. };
  85. const response = await AlertNotifyConfigAPI.getAlertNotifyConfig(params);
  86. if (response) {
  87. setConfigData(response.data || []);
  88. setPagination({
  89. ...pagination,
  90. total: response.total || 0,
  91. });
  92. }
  93. } catch (error) {
  94. console.error('获取告警通知配置失败:', error);
  95. message.error('获取告警通知配置失败');
  96. } finally {
  97. setLoading(false);
  98. }
  99. };
  100. const handleSearch = (values: any) => {
  101. setPagination({
  102. ...pagination,
  103. current: 1,
  104. });
  105. fetchConfigData();
  106. };
  107. const handleTableChange = (newPagination: any) => {
  108. setPagination({
  109. ...pagination,
  110. current: newPagination.current,
  111. pageSize: newPagination.pageSize,
  112. });
  113. };
  114. const handleAdd = () => {
  115. setModalTitle('新增告警通知配置');
  116. setCurrentRecord(null);
  117. modalForm.resetFields();
  118. setModalVisible(true);
  119. };
  120. const handleEdit = (record: AlertNotifyConfig) => {
  121. setModalTitle('编辑告警通知配置');
  122. setCurrentRecord(record);
  123. // 将用户ID列表转为数组
  124. const formData = {
  125. ...record,
  126. notify_users: record.notify_users || [],
  127. };
  128. modalForm.setFieldsValue(formData);
  129. setModalVisible(true);
  130. };
  131. const handleDelete = async (id: number) => {
  132. try {
  133. await AlertNotifyConfigAPI.deleteAlertNotifyConfig(id);
  134. message.success('删除成功');
  135. fetchConfigData();
  136. } catch (error) {
  137. console.error('删除失败:', error);
  138. message.error('删除失败');
  139. }
  140. };
  141. const handleModalSubmit = async () => {
  142. try {
  143. const values = await modalForm.validateFields();
  144. // 根据通知类型处理提交数据
  145. const submitData = {
  146. ...values,
  147. notify_users: values.notify_type === NotifyType.SMS ? [] : values.notify_users,
  148. };
  149. // SMS通知特殊处理
  150. if (values.notify_type === NotifyType.SMS) {
  151. submitData.phone = values.phone_number; // 转换为后端需要的参数名
  152. submitData.content = values.notify_template || '系统告警通知';
  153. }
  154. if (currentRecord) {
  155. // 更新
  156. await AlertNotifyConfigAPI.updateAlertNotifyConfig(currentRecord.id, submitData);
  157. message.success('更新成功');
  158. } else {
  159. // 新增
  160. await AlertNotifyConfigAPI.createAlertNotifyConfig(submitData);
  161. message.success('添加成功');
  162. }
  163. setModalVisible(false);
  164. fetchConfigData();
  165. } catch (error) {
  166. console.error('操作失败:', error);
  167. message.error('操作失败');
  168. }
  169. };
  170. const alertLevelOptions = getEnumOptions(AlertLevel, AlertLevelNameMap);
  171. const notifyTypeOptions = getEnumOptions(NotifyType, NotifyTypeNameMap);
  172. const enableStatusOptions = getEnumOptions(EnableStatus, EnableStatusNameMap);
  173. const getAlertLevelTag = (level: AlertLevel) => {
  174. switch (level) {
  175. case AlertLevel.MINOR:
  176. return <Tag color="blue">次要</Tag>;
  177. case AlertLevel.NORMAL:
  178. return <Tag color="green">一般</Tag>;
  179. case AlertLevel.IMPORTANT:
  180. return <Tag color="orange">重要</Tag>;
  181. case AlertLevel.URGENT:
  182. return <Tag color="red">紧急</Tag>;
  183. default:
  184. return <Tag>未知</Tag>;
  185. }
  186. };
  187. const columns = [
  188. {
  189. title: '配置ID',
  190. dataIndex: 'id',
  191. key: 'id',
  192. width: 80,
  193. },
  194. {
  195. title: '设备',
  196. dataIndex: 'device_id',
  197. key: 'device_id',
  198. render: (id: number) => {
  199. const device = deviceOptions.find(opt => opt.value === id);
  200. return device ? device.label : id;
  201. },
  202. },
  203. {
  204. title: '告警等级',
  205. dataIndex: 'alert_level',
  206. key: 'alert_level',
  207. render: (level: AlertLevel) => getAlertLevelTag(level),
  208. },
  209. {
  210. title: '通知类型',
  211. dataIndex: 'notify_type',
  212. key: 'notify_type',
  213. render: (type: NotifyType) => NotifyTypeNameMap[type] || type,
  214. },
  215. {
  216. title: '通知模板',
  217. dataIndex: 'notify_template',
  218. key: 'notify_template',
  219. ellipsis: true,
  220. },
  221. {
  222. title: '通知用户',
  223. dataIndex: 'notify_users',
  224. key: 'notify_users',
  225. render: (users: number[]) => {
  226. if (!users || users.length === 0) return '无';
  227. return users.map(id => {
  228. const user = userOptions.find(opt => opt.value === id);
  229. return user ? user.label : id;
  230. }).join(', ');
  231. },
  232. },
  233. {
  234. title: '状态',
  235. dataIndex: 'is_enabled',
  236. key: 'is_enabled',
  237. render: (status: EnableStatus) => (
  238. status === EnableStatus.ENABLED ?
  239. <Badge status="success" text="启用" /> :
  240. <Badge status="default" text="禁用" />
  241. ),
  242. },
  243. {
  244. title: '操作',
  245. key: 'action',
  246. render: (_: any, record: AlertNotifyConfig) => (
  247. <Space size="middle">
  248. <Button size="small" type="primary" onClick={() => handleEdit(record)}>
  249. 编辑
  250. </Button>
  251. <Popconfirm
  252. title="确定删除此配置?"
  253. onConfirm={() => handleDelete(record.id)}
  254. okText="确定"
  255. cancelText="取消"
  256. >
  257. <Button size="small" danger>
  258. 删除
  259. </Button>
  260. </Popconfirm>
  261. </Space>
  262. ),
  263. },
  264. ];
  265. return (
  266. <div>
  267. <Card title="告警通知配置" style={{ marginBottom: 16 }}>
  268. <Form
  269. form={formRef}
  270. layout="inline"
  271. onFinish={handleSearch}
  272. style={{ marginBottom: 16 }}
  273. >
  274. <Form.Item name="device_id" label="设备">
  275. <Select
  276. placeholder="选择设备"
  277. style={{ width: 200 }}
  278. allowClear
  279. options={deviceOptions}
  280. />
  281. </Form.Item>
  282. <Form.Item name="alert_level" label="告警等级">
  283. <Select
  284. placeholder="选择告警等级"
  285. style={{ width: 120 }}
  286. allowClear
  287. options={alertLevelOptions}
  288. />
  289. </Form.Item>
  290. <Form.Item name="notify_type" label="通知类型">
  291. <Select
  292. placeholder="选择通知类型"
  293. style={{ width: 120 }}
  294. allowClear
  295. options={notifyTypeOptions}
  296. />
  297. </Form.Item>
  298. <Form.Item name="is_enabled" label="状态">
  299. <Select
  300. placeholder="选择状态"
  301. style={{ width: 100 }}
  302. allowClear
  303. options={enableStatusOptions}
  304. />
  305. </Form.Item>
  306. <Form.Item>
  307. <Button type="primary" htmlType="submit">
  308. 查询
  309. </Button>
  310. </Form.Item>
  311. <Form.Item>
  312. <Button type="primary" onClick={handleAdd}>
  313. 新增
  314. </Button>
  315. </Form.Item>
  316. </Form>
  317. <Table
  318. columns={columns}
  319. dataSource={configData}
  320. rowKey="id"
  321. pagination={pagination}
  322. loading={loading}
  323. onChange={handleTableChange}
  324. />
  325. </Card>
  326. <Modal
  327. title={modalTitle}
  328. open={modalVisible}
  329. onOk={handleModalSubmit}
  330. onCancel={() => setModalVisible(false)}
  331. width={600}
  332. >
  333. <Form
  334. form={modalForm}
  335. layout="vertical"
  336. >
  337. <Form.Item
  338. name="device_id"
  339. label="设备"
  340. rules={[{ required: true, message: '请选择设备' }]}
  341. >
  342. <Select
  343. placeholder="选择设备"
  344. options={deviceOptions}
  345. />
  346. </Form.Item>
  347. <Form.Item
  348. name="alert_level"
  349. label="告警等级"
  350. rules={[{ required: true, message: '请选择告警等级' }]}
  351. >
  352. <Select
  353. placeholder="选择告警等级"
  354. options={alertLevelOptions}
  355. />
  356. </Form.Item>
  357. <Form.Item
  358. name="notify_type"
  359. label="通知类型"
  360. rules={[{ required: true, message: '请选择通知类型' }]}
  361. >
  362. <Select
  363. placeholder="选择通知类型"
  364. options={notifyTypeOptions}
  365. onChange={(value) => {
  366. if (value === NotifyType.SMS) {
  367. modalForm.setFieldsValue({ notify_users: [] });
  368. }
  369. }}
  370. />
  371. </Form.Item>
  372. <Form.Item
  373. name="notify_template"
  374. label="通知模板"
  375. >
  376. <Input.TextArea rows={3} placeholder="输入通知模板,可使用{{变量}}格式插入动态内容" />
  377. </Form.Item>
  378. <Form.Item
  379. noStyle
  380. shouldUpdate={(prevValues, currentValues) => prevValues.notify_type !== currentValues.notify_type}
  381. >
  382. {({ getFieldValue }) =>
  383. getFieldValue('notify_type') === NotifyType.SMS ? (
  384. <Form.Item
  385. name="phone_number"
  386. label="手机号码"
  387. rules={[{ required: true, message: '请输入手机号码' }]}
  388. >
  389. <Input placeholder="请输入接收短信的手机号码" />
  390. </Form.Item>
  391. ) : (
  392. <Form.Item
  393. name="notify_users"
  394. label="通知用户"
  395. rules={[{ required: true, message: '请选择通知用户' }]}
  396. >
  397. <Select
  398. placeholder="选择通知用户"
  399. mode="multiple"
  400. options={userOptions}
  401. />
  402. </Form.Item>
  403. )
  404. }
  405. </Form.Item>
  406. <Form.Item
  407. name="is_enabled"
  408. label="状态"
  409. initialValue={EnableStatus.ENABLED}
  410. >
  411. <Select
  412. placeholder="选择状态"
  413. options={enableStatusOptions}
  414. />
  415. </Form.Item>
  416. </Form>
  417. </Modal>
  418. </div>
  419. );
  420. };