index.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. <script setup lang="ts">
  2. import { Page } from '@vben/common-ui';
  3. import { computed, h, onMounted, onUnmounted, ref } from 'vue';
  4. import { DesktopOutlined } from '@ant-design/icons-vue';
  5. import { Button, Form, InputNumber, message, Modal, Space, Switch, Table, Tag, Tooltip } from 'ant-design-vue';
  6. import dayjs from 'dayjs';
  7. import { requestClient } from '#/api/request';
  8. type SyncClient = {
  9. dataType?: string;
  10. device?: string;
  11. deviceId?: number;
  12. firstRequestTime?: number;
  13. groupSequence?: string;
  14. ip?: string;
  15. key: string;
  16. lastRequestTime?: number;
  17. marketType?: string;
  18. platform?: string;
  19. requestCount?: number;
  20. route?: string;
  21. version?: string;
  22. };
  23. type SyncClientRow = SyncClient & {
  24. children?: SyncClientRow[];
  25. count?: number;
  26. onlineCount?: number;
  27. rowKey: string;
  28. rowType: 'client' | 'dataType' | 'marketType' | 'platform';
  29. title: string;
  30. };
  31. const CHAR_MAP: Record<string, Record<string, string>> = {
  32. dataType: {
  33. 1: '列表',
  34. 2: '让球/大小',
  35. 3: '特别投注',
  36. },
  37. marketType: {
  38. 0: '早盘',
  39. 1: '今日',
  40. 2: '滚球',
  41. },
  42. platform: {
  43. ay: 'IM',
  44. hg: '皇冠',
  45. im: 'IM',
  46. ob: 'OB',
  47. ps: '平博',
  48. tq: 'OB',
  49. },
  50. };
  51. const MARKET_TYPE_ORDER = ['2', '1', '0'];
  52. const clients = ref<SyncClient[]>([]);
  53. const loading = ref(false);
  54. const autoRefresh = ref(true);
  55. const editClient = ref<SyncClient>();
  56. const editDeviceId = ref<number>();
  57. const editVisible = ref(false);
  58. const refreshTimer = ref<ReturnType<typeof setTimeout>>();
  59. const deviceWindows = new Map<number, Window>();
  60. const columns = [
  61. {
  62. dataIndex: 'title',
  63. key: 'title',
  64. title: '分类',
  65. width: 180,
  66. },
  67. {
  68. align: 'center',
  69. dataIndex: 'groupSequence',
  70. key: 'groupSequence',
  71. title: '分组序列',
  72. width: 80,
  73. },
  74. {
  75. align: 'center',
  76. dataIndex: 'requestCount',
  77. key: 'requestCount',
  78. title: '请求次数',
  79. width: 100,
  80. },
  81. {
  82. align: 'center',
  83. dataIndex: 'lastRequestTime',
  84. key: 'lastRequestTime',
  85. title: '最后请求时间',
  86. width: 180,
  87. },
  88. {
  89. align: 'center',
  90. dataIndex: 'firstRequestTime',
  91. key: 'firstRequestTime',
  92. title: '初次请求时间',
  93. width: 180,
  94. },
  95. {
  96. align: 'center',
  97. dataIndex: 'route',
  98. key: 'route',
  99. title: '请求接口',
  100. width: 180,
  101. },
  102. {
  103. align: 'left',
  104. dataIndex: 'deviceId',
  105. key: 'deviceId',
  106. title: '设备',
  107. width: 160,
  108. },
  109. {
  110. key: 'action',
  111. title: '操作',
  112. width: 120,
  113. },
  114. ];
  115. const onlineThreshold = 5 * 60 * 1000;
  116. const onlineCount = computed(() => {
  117. const now = Date.now();
  118. return clients.value.filter(item => now - (item.lastRequestTime ?? 0) <= onlineThreshold).length;
  119. });
  120. const formatTime = (time?: number) => {
  121. return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-';
  122. };
  123. const displayValue = (value?: number | string) => {
  124. return value === undefined || value === '' ? '-' : value;
  125. };
  126. const displayMappedValue = (
  127. type: keyof typeof CHAR_MAP,
  128. value?: number | string,
  129. ) => {
  130. if (value === undefined || value === '') {
  131. return '-';
  132. }
  133. return CHAR_MAP[type]?.[String(value)] ?? value;
  134. };
  135. const getDeviceUrl = (deviceId?: number) => {
  136. if (!Number.isInteger(deviceId)) {
  137. return '';
  138. }
  139. const payload = btoa(`${deviceId}\x00c\x00mysql`);
  140. return `https://rdp.long.bid/#/client/${payload}`;
  141. };
  142. const openDevice = (deviceId?: number) => {
  143. if (!Number.isInteger(deviceId)) {
  144. return;
  145. }
  146. const existingWindow = deviceWindows.get(deviceId);
  147. if (existingWindow && !existingWindow.closed) {
  148. existingWindow.focus();
  149. return;
  150. }
  151. const deviceWindow = window.open(getDeviceUrl(deviceId), `rdp-device-${deviceId}`);
  152. if (deviceWindow) {
  153. deviceWindows.set(deviceId, deviceWindow);
  154. deviceWindow.focus();
  155. }
  156. };
  157. const isOnline = (time?: number) => {
  158. return !!time && Date.now() - time <= onlineThreshold;
  159. };
  160. const getGroupKey = (value?: string) => {
  161. return value === undefined || value === '' ? '__empty__' : String(value);
  162. };
  163. const getGroupTitle = (type: keyof typeof CHAR_MAP, value?: string) => {
  164. return displayMappedValue(type, value);
  165. };
  166. const getLatestTime = (items: SyncClient[]) => {
  167. return Math.max(...items.map(item => item.lastRequestTime ?? 0));
  168. };
  169. const getRequestCount = (items: SyncClient[]) => {
  170. return items.reduce((total, item) => total + (item.requestCount ?? 0), 0);
  171. };
  172. const getOnlineCount = (items: SyncClient[]) => {
  173. return items.filter(item => isOnline(item.lastRequestTime)).length;
  174. };
  175. const createClientRow = (client: SyncClient): SyncClientRow => ({
  176. ...client,
  177. rowKey: `client:${client.key}`,
  178. rowType: 'client',
  179. title: client.device || '客户端',
  180. });
  181. const createGroupRow = (
  182. rowType: SyncClientRow['rowType'],
  183. rowKey: string,
  184. title: string,
  185. items: SyncClient[],
  186. children: SyncClientRow[],
  187. ): SyncClientRow => ({
  188. rowKey,
  189. key: rowKey,
  190. rowType,
  191. title,
  192. children,
  193. count: items.length,
  194. lastRequestTime: getLatestTime(items),
  195. onlineCount: getOnlineCount(items),
  196. requestCount: getRequestCount(items),
  197. });
  198. const groupByField = (items: SyncClient[], field: keyof SyncClient) => {
  199. return items.reduce<Record<string, SyncClient[]>>((groups, item) => {
  200. const key = getGroupKey(item[field] as string | undefined);
  201. if (!groups[key]) {
  202. groups[key] = [];
  203. }
  204. groups[key].push(item);
  205. return groups;
  206. }, {});
  207. };
  208. const sortGroupEntries = (entries: Array<[string, SyncClient[]]>) => {
  209. return entries.sort(([keyA], [keyB]) => {
  210. if (keyA === '__empty__') {
  211. return 1;
  212. }
  213. if (keyB === '__empty__') {
  214. return -1;
  215. }
  216. return keyA.localeCompare(keyB, 'zh-CN', { numeric: true });
  217. });
  218. };
  219. const sortMarketEntries = (entries: Array<[string, SyncClient[]]>) => {
  220. return entries.sort(([keyA], [keyB]) => {
  221. const indexA = MARKET_TYPE_ORDER.indexOf(keyA);
  222. const indexB = MARKET_TYPE_ORDER.indexOf(keyB);
  223. if (indexA >= 0 && indexB >= 0) {
  224. return indexA - indexB;
  225. }
  226. if (indexA >= 0) {
  227. return -1;
  228. }
  229. if (indexB >= 0) {
  230. return 1;
  231. }
  232. return keyA.localeCompare(keyB, 'zh-CN', { numeric: true });
  233. });
  234. };
  235. const sortClientsByGroupSequence = (items: SyncClient[]) => {
  236. return [...items].sort((a, b) => {
  237. const sequenceA = getGroupKey(a.groupSequence);
  238. const sequenceB = getGroupKey(b.groupSequence);
  239. if (sequenceA === '__empty__') {
  240. return 1;
  241. }
  242. if (sequenceB === '__empty__') {
  243. return -1;
  244. }
  245. return sequenceA.localeCompare(sequenceB, 'zh-CN', { numeric: true });
  246. });
  247. };
  248. const createPlatformRows = (items: SyncClient[], keyPrefix: string) => {
  249. const platformGroups = groupByField(items, 'platform');
  250. return sortGroupEntries(Object.entries(platformGroups)).map(([platform, platformItems]) => {
  251. return createGroupRow(
  252. 'platform',
  253. `${keyPrefix}:platform:${platform}`,
  254. getGroupTitle('platform', platform === '__empty__' ? undefined : platform),
  255. platformItems,
  256. sortClientsByGroupSequence(platformItems).map(createClientRow),
  257. );
  258. });
  259. };
  260. const groupedClients = computed<SyncClientRow[]>(() => {
  261. const listClients = clients.value.filter(item => String(item.dataType) === '1');
  262. const marketClients = clients.value.filter(item => String(item.dataType) !== '1');
  263. const rows: SyncClientRow[] = [];
  264. if (listClients.length) {
  265. rows.push(createGroupRow(
  266. 'dataType',
  267. 'data:1',
  268. getGroupTitle('dataType', '1'),
  269. listClients,
  270. createPlatformRows(listClients, 'data:1'),
  271. ));
  272. }
  273. const marketGroups = groupByField(marketClients, 'marketType');
  274. const marketRows = sortMarketEntries(Object.entries(marketGroups)).map(([marketType, marketItems]) => {
  275. const dataGroups = groupByField(marketItems, 'dataType');
  276. const dataChildren = sortGroupEntries(Object.entries(dataGroups)).map(([dataType, dataItems]) => {
  277. return createGroupRow(
  278. 'dataType',
  279. `market:${marketType}:data:${dataType}`,
  280. getGroupTitle('dataType', dataType === '__empty__' ? undefined : dataType),
  281. dataItems,
  282. createPlatformRows(dataItems, `market:${marketType}:data:${dataType}`),
  283. );
  284. });
  285. return createGroupRow(
  286. 'marketType',
  287. `market:${marketType}`,
  288. getGroupTitle('marketType', marketType === '__empty__' ? undefined : marketType),
  289. marketItems,
  290. dataChildren,
  291. );
  292. });
  293. return [...rows, ...marketRows];
  294. });
  295. const expandedRowKeys = computed(() => {
  296. const keys: string[] = [];
  297. const collectKeys = (rows: SyncClientRow[]) => {
  298. rows.forEach((row) => {
  299. if (row.children?.length) {
  300. keys.push(row.rowKey);
  301. collectKeys(row.children);
  302. }
  303. });
  304. };
  305. collectKeys(groupedClients.value);
  306. return keys;
  307. });
  308. const renderExpandIcon = () => h('span', { class: 'hidden-expand-icon' });
  309. const clearRefreshTimer = () => {
  310. if (refreshTimer.value) {
  311. clearTimeout(refreshTimer.value);
  312. refreshTimer.value = undefined;
  313. }
  314. };
  315. const scheduleRefresh = () => {
  316. clearRefreshTimer();
  317. if (!autoRefresh.value) {
  318. return;
  319. }
  320. refreshTimer.value = setTimeout(fetchClients, 30 * 1000);
  321. };
  322. const fetchClients = async () => {
  323. loading.value = true;
  324. try {
  325. const data = await requestClient.get<SyncClient[]>('/pstery/get_clients');
  326. clients.value = data ?? [];
  327. }
  328. catch (error) {
  329. console.error('Failed to fetch sync clients:', error);
  330. message.error('获取数据同步客户端失败');
  331. }
  332. finally {
  333. loading.value = false;
  334. scheduleRefresh();
  335. }
  336. };
  337. const openEditClient = (client: SyncClientRow) => {
  338. editClient.value = client;
  339. editDeviceId.value = client.deviceId;
  340. editVisible.value = true;
  341. };
  342. const saveClient = async () => {
  343. if (!editClient.value?.key) {
  344. return;
  345. }
  346. try {
  347. await requestClient.post('/pstery/update_client', {
  348. deviceId: editDeviceId.value,
  349. key: editClient.value.key,
  350. });
  351. message.success('保存成功');
  352. editVisible.value = false;
  353. await fetchClients();
  354. }
  355. catch (error) {
  356. console.error('Failed to save sync client:', error);
  357. message.error('保存客户端信息失败');
  358. }
  359. };
  360. const deleteClient = (client: SyncClientRow) => {
  361. Modal.confirm({
  362. cancelText: '取消',
  363. content: `确定删除客户端 ${client.title} 吗?`,
  364. okText: '删除',
  365. okType: 'danger',
  366. title: '删除客户端',
  367. onOk: async () => {
  368. try {
  369. await requestClient.post('/pstery/delete_client', { key: client.key });
  370. message.success('删除成功');
  371. await fetchClients();
  372. }
  373. catch (error) {
  374. console.error('Failed to delete sync client:', error);
  375. message.error('删除客户端失败');
  376. }
  377. },
  378. });
  379. };
  380. const handleAutoRefreshChange = () => {
  381. scheduleRefresh();
  382. };
  383. onMounted(() => {
  384. fetchClients();
  385. });
  386. onUnmounted(() => {
  387. clearRefreshTimer();
  388. });
  389. </script>
  390. <template>
  391. <Page title="数据同步">
  392. <div class="data-sync-toolbar">
  393. <Space>
  394. <Button type="primary" :loading="loading" @click="fetchClients">刷新</Button>
  395. <span class="summary">
  396. 在线 {{ onlineCount }} / 总计 {{ clients.length }}
  397. </span>
  398. </Space>
  399. <Space>
  400. <span class="auto-label">自动刷新</span>
  401. <Switch v-model:checked="autoRefresh" @change="handleAutoRefreshChange" />
  402. </Space>
  403. </div>
  404. <Table
  405. :columns="columns"
  406. :data-source="groupedClients"
  407. :expanded-row-keys="expandedRowKeys"
  408. :expand-icon="renderExpandIcon"
  409. :loading="loading"
  410. :pagination="false"
  411. :row-key="record => record.rowKey"
  412. bordered
  413. size="small"
  414. :scroll="{ x: 900 }"
  415. >
  416. <template #bodyCell="{ column, record, text }">
  417. <template v-if="column.key === 'title'">
  418. <Space>
  419. <Tag v-if="record.rowType === 'client'" :color="isOnline(record.lastRequestTime) ? 'green' : 'red'">
  420. {{ isOnline(record.lastRequestTime) ? '在线' : '离线' }}
  421. </Tag>
  422. <span>{{ record.title }}</span>
  423. <span v-if="record.rowType === 'client' && record.version" class="version-text">
  424. {{ record.version }}
  425. </span>
  426. <span v-if="record.rowType !== 'client'" class="group-count">
  427. {{ record.onlineCount ?? 0 }} / {{ record.count ?? 0 }}
  428. </span>
  429. </Space>
  430. </template>
  431. <template v-else-if="column.key === 'lastRequestTime'">
  432. <span v-if="record.rowType === 'client'">{{ formatTime(record.lastRequestTime) }}</span>
  433. <span v-else>-</span>
  434. </template>
  435. <template v-else-if="column.key === 'firstRequestTime'">
  436. <span v-if="record.rowType === 'client'">{{ formatTime(record.firstRequestTime) }}</span>
  437. <span v-else>-</span>
  438. </template>
  439. <template v-else-if="record.rowType !== 'client'">
  440. -
  441. </template>
  442. <template v-else-if="column.key === 'action'">
  443. <Space>
  444. <Button size="small" type="link" @click="openEditClient(record)">编辑</Button>
  445. <Button danger size="small" type="link" @click="deleteClient(record)">删除</Button>
  446. </Space>
  447. </template>
  448. <template v-else-if="column.key === 'requestCount'">
  449. {{ record.requestCount ?? 0 }}
  450. </template>
  451. <template v-else-if="column.key === 'deviceId'">
  452. <Space>
  453. <Tooltip v-if="Number.isInteger(record.deviceId)" title="打开设备">
  454. <Button
  455. class="device-link"
  456. size="small"
  457. type="link"
  458. @click="openDevice(record.deviceId)"
  459. >
  460. <DesktopOutlined />
  461. </Button>
  462. </Tooltip>
  463. <span v-else class="device-placeholder"></span>
  464. <span>{{ displayValue(record.ip) }}</span>
  465. </Space>
  466. </template>
  467. <template v-else>
  468. {{ displayValue(text) }}
  469. </template>
  470. </template>
  471. </Table>
  472. <Modal
  473. v-model:visible="editVisible"
  474. title="编辑客户端"
  475. ok-text="保存"
  476. cancel-text="取消"
  477. @ok="saveClient"
  478. >
  479. <Form layout="vertical">
  480. <Form.Item label="设备ID">
  481. <InputNumber
  482. v-model:value="editDeviceId"
  483. :min="0"
  484. :precision="0"
  485. style="width: 100%"
  486. />
  487. </Form.Item>
  488. </Form>
  489. </Modal>
  490. </Page>
  491. </template>
  492. <style scoped>
  493. .data-sync-toolbar {
  494. display: flex;
  495. align-items: center;
  496. justify-content: space-between;
  497. gap: 12px;
  498. margin-bottom: 12px;
  499. }
  500. .summary,
  501. .auto-label {
  502. color: hsl(var(--muted-foreground));
  503. }
  504. .group-count {
  505. color: hsl(var(--muted-foreground));
  506. font-size: 12px;
  507. }
  508. .version-text {
  509. color: hsl(var(--muted-foreground));
  510. font-size: 12px;
  511. }
  512. .device-link {
  513. display: inline-flex;
  514. align-items: center;
  515. justify-content: center;
  516. width: 24px;
  517. height: 24px;
  518. font-size: 16px;
  519. padding: 0;
  520. }
  521. .device-placeholder {
  522. display: inline-block;
  523. width: 24px;
  524. }
  525. :deep(.hidden-expand-icon) {
  526. display: none;
  527. }
  528. </style>