ChannelsTable.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. import React, { useEffect, useState } from 'react';
  2. import { Button, Form, Label, Pagination, Popup, Table } from 'semantic-ui-react';
  3. import { Link } from 'react-router-dom';
  4. import { API, showError, showInfo, showSuccess, timestamp2string } from '../helpers';
  5. import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../constants';
  6. import { renderGroup } from '../helpers/render';
  7. function renderTimestamp(timestamp) {
  8. return (
  9. <>
  10. {timestamp2string(timestamp)}
  11. </>
  12. );
  13. }
  14. let type2label = undefined;
  15. function renderType(type) {
  16. if (!type2label) {
  17. type2label = new Map;
  18. for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
  19. type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
  20. }
  21. type2label[0] = { value: 0, text: '未知类型', color: 'grey' };
  22. }
  23. return <Label basic color={type2label[type].color}>{type2label[type].text}</Label>;
  24. }
  25. const ChannelsTable = () => {
  26. const [channels, setChannels] = useState([]);
  27. const [loading, setLoading] = useState(true);
  28. const [activePage, setActivePage] = useState(1);
  29. const [searchKeyword, setSearchKeyword] = useState('');
  30. const [searching, setSearching] = useState(false);
  31. const [updatingBalance, setUpdatingBalance] = useState(false);
  32. const loadChannels = async (startIdx) => {
  33. const res = await API.get(`/api/channel/?p=${startIdx}`);
  34. const { success, message, data } = res.data;
  35. if (success) {
  36. if (startIdx === 0) {
  37. setChannels(data);
  38. } else {
  39. let newChannels = channels;
  40. newChannels.push(...data);
  41. setChannels(newChannels);
  42. }
  43. } else {
  44. showError(message);
  45. }
  46. setLoading(false);
  47. };
  48. const onPaginationChange = (e, { activePage }) => {
  49. (async () => {
  50. if (activePage === Math.ceil(channels.length / ITEMS_PER_PAGE) + 1) {
  51. // In this case we have to load more data and then append them.
  52. await loadChannels(activePage - 1);
  53. }
  54. setActivePage(activePage);
  55. })();
  56. };
  57. const refresh = async () => {
  58. setLoading(true);
  59. await loadChannels(0);
  60. };
  61. useEffect(() => {
  62. loadChannels(0)
  63. .then()
  64. .catch((reason) => {
  65. showError(reason);
  66. });
  67. }, []);
  68. const manageChannel = async (id, action, idx) => {
  69. let data = { id };
  70. let res;
  71. switch (action) {
  72. case 'delete':
  73. res = await API.delete(`/api/channel/${id}/`);
  74. break;
  75. case 'enable':
  76. data.status = 1;
  77. res = await API.put('/api/channel/', data);
  78. break;
  79. case 'disable':
  80. data.status = 2;
  81. res = await API.put('/api/channel/', data);
  82. break;
  83. }
  84. const { success, message } = res.data;
  85. if (success) {
  86. showSuccess('操作成功完成!');
  87. let channel = res.data.data;
  88. let newChannels = [...channels];
  89. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  90. if (action === 'delete') {
  91. newChannels[realIdx].deleted = true;
  92. } else {
  93. newChannels[realIdx].status = channel.status;
  94. }
  95. setChannels(newChannels);
  96. } else {
  97. showError(message);
  98. }
  99. };
  100. const renderStatus = (status) => {
  101. switch (status) {
  102. case 1:
  103. return <Label basic color='green'>已启用</Label>;
  104. case 2:
  105. return (
  106. <Label basic color='red'>
  107. 已禁用
  108. </Label>
  109. );
  110. default:
  111. return (
  112. <Label basic color='grey'>
  113. 未知状态
  114. </Label>
  115. );
  116. }
  117. };
  118. const renderResponseTime = (responseTime) => {
  119. let time = responseTime / 1000;
  120. time = time.toFixed(2) + ' 秒';
  121. if (responseTime === 0) {
  122. return <Label basic color='grey'>未测试</Label>;
  123. } else if (responseTime <= 1000) {
  124. return <Label basic color='green'>{time}</Label>;
  125. } else if (responseTime <= 3000) {
  126. return <Label basic color='olive'>{time}</Label>;
  127. } else if (responseTime <= 5000) {
  128. return <Label basic color='yellow'>{time}</Label>;
  129. } else {
  130. return <Label basic color='red'>{time}</Label>;
  131. }
  132. };
  133. const searchChannels = async () => {
  134. if (searchKeyword === '') {
  135. // if keyword is blank, load files instead.
  136. await loadChannels(0);
  137. setActivePage(1);
  138. return;
  139. }
  140. setSearching(true);
  141. const res = await API.get(`/api/channel/search?keyword=${searchKeyword}`);
  142. const { success, message, data } = res.data;
  143. if (success) {
  144. setChannels(data);
  145. setActivePage(1);
  146. } else {
  147. showError(message);
  148. }
  149. setSearching(false);
  150. };
  151. const testChannel = async (id, name, idx) => {
  152. const res = await API.get(`/api/channel/test/${id}/`);
  153. const { success, message, time } = res.data;
  154. if (success) {
  155. let newChannels = [...channels];
  156. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  157. newChannels[realIdx].response_time = time * 1000;
  158. newChannels[realIdx].test_time = Date.now() / 1000;
  159. setChannels(newChannels);
  160. showInfo(`通道 ${name} 测试成功,耗时 ${time.toFixed(2)} 秒。`);
  161. } else {
  162. showError(message);
  163. }
  164. };
  165. const testAllChannels = async () => {
  166. const res = await API.get(`/api/channel/test`);
  167. const { success, message } = res.data;
  168. if (success) {
  169. showInfo('已成功开始测试所有已启用通道,请刷新页面查看结果。');
  170. } else {
  171. showError(message);
  172. }
  173. };
  174. const updateChannelBalance = async (id, name, idx) => {
  175. const res = await API.get(`/api/channel/update_balance/${id}/`);
  176. const { success, message, balance } = res.data;
  177. if (success) {
  178. let newChannels = [...channels];
  179. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  180. newChannels[realIdx].balance = balance;
  181. newChannels[realIdx].balance_updated_time = Date.now() / 1000;
  182. setChannels(newChannels);
  183. showInfo(`通道 ${name} 余额更新成功!`);
  184. } else {
  185. showError(message);
  186. }
  187. };
  188. const updateAllChannelsBalance = async () => {
  189. setUpdatingBalance(true);
  190. const res = await API.get(`/api/channel/update_balance`);
  191. const { success, message } = res.data;
  192. if (success) {
  193. showInfo('已更新完毕所有已启用通道余额!');
  194. } else {
  195. showError(message);
  196. }
  197. setUpdatingBalance(false);
  198. };
  199. const handleKeywordChange = async (e, { value }) => {
  200. setSearchKeyword(value.trim());
  201. };
  202. const sortChannel = (key) => {
  203. if (channels.length === 0) return;
  204. setLoading(true);
  205. let sortedChannels = [...channels];
  206. sortedChannels.sort((a, b) => {
  207. return ('' + a[key]).localeCompare(b[key]);
  208. });
  209. if (sortedChannels[0].id === channels[0].id) {
  210. sortedChannels.reverse();
  211. }
  212. setChannels(sortedChannels);
  213. setLoading(false);
  214. };
  215. return (
  216. <>
  217. <Form onSubmit={searchChannels}>
  218. <Form.Input
  219. icon='search'
  220. fluid
  221. iconPosition='left'
  222. placeholder='搜索渠道的 ID 和名称 ...'
  223. value={searchKeyword}
  224. loading={searching}
  225. onChange={handleKeywordChange}
  226. />
  227. </Form>
  228. <Table basic>
  229. <Table.Header>
  230. <Table.Row>
  231. <Table.HeaderCell
  232. style={{ cursor: 'pointer' }}
  233. onClick={() => {
  234. sortChannel('id');
  235. }}
  236. >
  237. ID
  238. </Table.HeaderCell>
  239. <Table.HeaderCell
  240. style={{ cursor: 'pointer' }}
  241. onClick={() => {
  242. sortChannel('name');
  243. }}
  244. >
  245. 名称
  246. </Table.HeaderCell>
  247. <Table.HeaderCell
  248. style={{ cursor: 'pointer' }}
  249. onClick={() => {
  250. sortChannel('group');
  251. }}
  252. >
  253. 分组
  254. </Table.HeaderCell>
  255. <Table.HeaderCell
  256. style={{ cursor: 'pointer' }}
  257. onClick={() => {
  258. sortChannel('type');
  259. }}
  260. >
  261. 类型
  262. </Table.HeaderCell>
  263. <Table.HeaderCell
  264. style={{ cursor: 'pointer' }}
  265. onClick={() => {
  266. sortChannel('status');
  267. }}
  268. >
  269. 状态
  270. </Table.HeaderCell>
  271. <Table.HeaderCell
  272. style={{ cursor: 'pointer' }}
  273. onClick={() => {
  274. sortChannel('response_time');
  275. }}
  276. >
  277. 响应时间
  278. </Table.HeaderCell>
  279. <Table.HeaderCell
  280. style={{ cursor: 'pointer' }}
  281. onClick={() => {
  282. sortChannel('balance');
  283. }}
  284. >
  285. 余额
  286. </Table.HeaderCell>
  287. <Table.HeaderCell>操作</Table.HeaderCell>
  288. </Table.Row>
  289. </Table.Header>
  290. <Table.Body>
  291. {channels
  292. .slice(
  293. (activePage - 1) * ITEMS_PER_PAGE,
  294. activePage * ITEMS_PER_PAGE
  295. )
  296. .map((channel, idx) => {
  297. if (channel.deleted) return <></>;
  298. return (
  299. <Table.Row key={channel.id}>
  300. <Table.Cell>{channel.id}</Table.Cell>
  301. <Table.Cell>{channel.name ? channel.name : '无'}</Table.Cell>
  302. <Table.Cell>{renderGroup(channel.group)}</Table.Cell>
  303. <Table.Cell>{renderType(channel.type)}</Table.Cell>
  304. <Table.Cell>{renderStatus(channel.status)}</Table.Cell>
  305. <Table.Cell>
  306. <Popup
  307. content={channel.test_time ? renderTimestamp(channel.test_time) : '未测试'}
  308. key={channel.id}
  309. trigger={renderResponseTime(channel.response_time)}
  310. basic
  311. />
  312. </Table.Cell>
  313. <Table.Cell>
  314. <Popup
  315. content={channel.balance_updated_time ? renderTimestamp(channel.balance_updated_time) : '未更新'}
  316. key={channel.id}
  317. trigger={<span>${channel.balance.toFixed(2)}</span>}
  318. basic
  319. />
  320. </Table.Cell>
  321. <Table.Cell>
  322. <div>
  323. <Button
  324. size={'small'}
  325. positive
  326. onClick={() => {
  327. testChannel(channel.id, channel.name, idx);
  328. }}
  329. >
  330. 测试
  331. </Button>
  332. <Button
  333. size={'small'}
  334. positive
  335. loading={updatingBalance}
  336. onClick={() => {
  337. updateChannelBalance(channel.id, channel.name, idx);
  338. }}
  339. >
  340. 更新余额
  341. </Button>
  342. <Popup
  343. trigger={
  344. <Button size='small' negative>
  345. 删除
  346. </Button>
  347. }
  348. on='click'
  349. flowing
  350. hoverable
  351. >
  352. <Button
  353. negative
  354. onClick={() => {
  355. manageChannel(channel.id, 'delete', idx);
  356. }}
  357. >
  358. 删除渠道 {channel.name}
  359. </Button>
  360. </Popup>
  361. <Button
  362. size={'small'}
  363. onClick={() => {
  364. manageChannel(
  365. channel.id,
  366. channel.status === 1 ? 'disable' : 'enable',
  367. idx
  368. );
  369. }}
  370. >
  371. {channel.status === 1 ? '禁用' : '启用'}
  372. </Button>
  373. <Button
  374. size={'small'}
  375. as={Link}
  376. to={'/channel/edit/' + channel.id}
  377. >
  378. 编辑
  379. </Button>
  380. </div>
  381. </Table.Cell>
  382. </Table.Row>
  383. );
  384. })}
  385. </Table.Body>
  386. <Table.Footer>
  387. <Table.Row>
  388. <Table.HeaderCell colSpan='8'>
  389. <Button size='small' as={Link} to='/channel/add' loading={loading}>
  390. 添加新的渠道
  391. </Button>
  392. <Button size='small' loading={loading} onClick={testAllChannels}>
  393. 测试所有已启用通道
  394. </Button>
  395. <Button size='small' onClick={updateAllChannelsBalance} loading={loading || updatingBalance}>更新所有已启用通道余额</Button>
  396. <Pagination
  397. floated='right'
  398. activePage={activePage}
  399. onPageChange={onPaginationChange}
  400. size='small'
  401. siblingRange={1}
  402. totalPages={
  403. Math.ceil(channels.length / ITEMS_PER_PAGE) +
  404. (channels.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
  405. }
  406. />
  407. <Button size='small' onClick={refresh} loading={loading}>刷新</Button>
  408. </Table.HeaderCell>
  409. </Table.Row>
  410. </Table.Footer>
  411. </Table>
  412. </>
  413. );
  414. };
  415. export default ChannelsTable;