You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2081 lines
58 KiB

1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
  1. <template>
  2. <view class="main">
  3. <!-- 顶部状态栏占位 -->
  4. <view class="top" :style="{height:iSMT+'px'}"></view>
  5. <!-- 登录的提示 -->
  6. <LoginPrompt ref="loginPrompt"></LoginPrompt>
  7. <!-- 头部导航 -->
  8. <view class="header">
  9. <view class="headphone-icon">
  10. <image src="https://d31zlh4on95l9h.cloudfront.net/images/bef2edba6cc0c85671fde07cfab5270d.png" class="header-icon-image"></image>
  11. </view>
  12. <view class="title">DeepChart</view>
  13. <view class="notification-icon">
  14. <image src="https://d31zlh4on95l9h.cloudfront.net/images/2554c84b91712d2a6cb6b00380e63bac.png" class="header-icon-image"></image>
  15. </view>
  16. </view>
  17. <!-- 内容区域 - 使用滚动视图 -->
  18. <scroll-view scroll-y class="content-container">
  19. <!-- 1. 今日市场概览 -->
  20. <market-overview :stock-info-list="currentStockInfoList"></market-overview>
  21. <!-- 间隔 -->
  22. <view class="section-gap"></view>
  23. <!-- 新增欢迎部分 -->
  24. <view class="section welcome-section">
  25. <!-- 轮播图 -->
  26. <swiper class="welcome-swiper" circular autoplay interval="3000" duration="500" indicator-dots indicator-active-color="#4080ff">
  27. <swiper-item v-for="(item, index) in 5" :key="index">
  28. <image class="swiper-image" src="https://d31zlh4on95l9h.cloudfront.net/images/e4272cc034fa2a3d1ca588ef84e51ab0.png" mode="aspectFill"></image>
  29. </swiper-item>
  30. </swiper>
  31. </view>
  32. <!-- 2. DeepMate -->
  33. <view class="section deepmate-section">
  34. <DeepMate />
  35. </view>
  36. <!-- 3. 深度探索 -->
  37. <view class="section deep-exploration">
  38. <!-- 上部分标题和查看更多按钮 -->
  39. <view class="section-header-container">
  40. <view class="section-header">
  41. <view class="header-left">
  42. <text class="section-title">深度探索</text>
  43. </view>
  44. <view class="header-right">
  45. <text class="more-btn">查看更多</text>
  46. </view>
  47. </view>
  48. </view>
  49. <!-- 下部分四个图标 -->
  50. <view class="exploration-container">
  51. <view class="exploration-content">
  52. <view class="exploration-item">
  53. <image class="exploration-icon" src="https://d31zlh4on95l9h.cloudfront.net/images/199472b0ee90a1c897f7c87b85accd84.png" mode="aspectFit" lazy-load="true"></image>
  54. <text class="exploration-text">主力追踪</text>
  55. </view>
  56. <view class="exploration-item">
  57. <image class="exploration-icon" src="https://d31zlh4on95l9h.cloudfront.net/images/c25ca5e176efc961dabfa5d0d1b486b0.png" mode="aspectFit" lazy-load="true"></image>
  58. <text class="exploration-text">主力资达</text>
  59. </view>
  60. <view class="exploration-item">
  61. <image class="exploration-icon" src="https://d31zlh4on95l9h.cloudfront.net/images/c064d7066dc8129a7df7b052762f82cf.png" mode="aspectFit" lazy-load="true"></image>
  62. <text class="exploration-text">主力解码</text>
  63. </view>
  64. <view class="exploration-item">
  65. <image class="exploration-icon" src="https://d31zlh4on95l9h.cloudfront.net/images/9d69cceee9c515911477078af6f68d88.png" mode="aspectFit" lazy-load="true"></image>
  66. <text class="exploration-text">主力资金流</text>
  67. </view>
  68. </view>
  69. </view>
  70. </view>
  71. <!-- 4. 我的自选 -->
  72. <view class="section my-selection">
  73. <!-- 上部分标题和查看更多按钮 -->
  74. <view class="section-header-container">
  75. <view class="section-header">
  76. <text class="section-title">我的自选</text>
  77. <text class="more-btn">添加自选股</text>
  78. </view>
  79. <!-- 我的自选TCP连接状态和控制 -->
  80. <!-- <view class="my-stocks-tcp-control">
  81. <view class="tcp-status" :class="{'connected': myStocksTcpConnected, 'disconnected': !myStocksTcpConnected}">
  82. <text class="status-text">{{myStocksTcpConnected ? '自选已连接' : '自选未连接'}}</text>
  83. </view>
  84. <view class="tcp-buttons">
  85. <button class="tcp-btn connect-btn" @click="connectMyStocksTcp" :disabled="myStocksTcpConnected">连接</button>
  86. <button class="tcp-btn disconnect-btn" @click="disconnectMyStocksTcp" :disabled="!myStocksTcpConnected">断开</button>
  87. </view>
  88. </view> -->
  89. </view>
  90. <!-- 下部分股票列表 -->
  91. <view class="stock-container">
  92. <view class="stock-list">
  93. <!-- 如果有TCP数据显示实时数据否则显示静态数据 -->
  94. <view class="stock-item" v-for="(item, index) in (myStocksInfoList.length > 0 ? myStocksInfoList : myStocks)" :key="item.code || item.stock_code">
  95. <view class="stock-info">
  96. <view class="name-container">
  97. <text class="stock-name">{{item.name || item.stock_name}}</text>
  98. <text class="stock-code-label">{{item.code || item.stock_code}}</text>
  99. </view>
  100. <view class="price-container">
  101. <text class="stock-price">{{item.price || item.current_price}}</text>
  102. <text class="stock-change" :class="{'stock-up': (item.change_percent || item.change || item.change_amount || 0) > 0, 'stock-down': (item.change_percent || item.change || item.change_amount || 0) < 0}">
  103. {{(item.change_percent || item.change || item.change_amount || 0) > 0 ? '+' : ''}}{{(parseFloat(item.change_percent || item.change || item.change_amount || 0)).toFixed(2)}}%
  104. </text>
  105. </view>
  106. </view>
  107. <view class="stock-chart">
  108. <image :src="item.chartImg || '/static/c5.png'" mode="aspectFit" class="chart-image"></image>
  109. </view>
  110. </view>
  111. </view>
  112. <!-- 机构动向简报数据 -->
  113. <view class="institutional-reports">
  114. <view class="section-title-container">
  115. <text class="section-title-text">机构动向简报</text>
  116. </view>
  117. <view class="text-gap"></view>
  118. <view class="report-item" v-for="(report, index) in institutionalReports" :key="index">
  119. <view class="report-stock">{{report.stock}}</view>
  120. <view class="report-status">{{report.status}}</view>
  121. </view>
  122. <view class="view-more">
  123. <text>查看更多 >></text>
  124. </view>
  125. </view>
  126. </view>
  127. </view>
  128. <!-- 5. TCP连接测试 -->
  129. <!-- <view class="section tcp-test-section">
  130. <view class="section-header">
  131. <text class="section-title">TCP连接测试</text>
  132. <view class="tcp-status" :class="{'connected': tcpConnected, 'disconnected': !tcpConnected}">
  133. <text class="status-text">{{tcpConnected ? '已连接' : '未连接'}}</text>
  134. </view>
  135. </view> -->
  136. <!-- TCP控制按钮 -->
  137. <!-- <view class="tcp-controls">
  138. <button class="tcp-btn connect-btn" @click="connectTcp" :disabled="tcpConnected">连接</button>
  139. <button class="tcp-btn disconnect-btn" @click="disconnectTcp" :disabled="!tcpConnected">断开</button>
  140. <button class="tcp-btn send-btn" @click="sendTcpMessage" :disabled="!tcpConnected">发送测试消息</button>
  141. <button class="tcp-btn status-btn" @click="getTcpStatus">查看状态</button>
  142. </view> -->
  143. <!-- 消息记录 -->
  144. <!-- <view class="tcp-messages" v-if="tcpMessages.length > 0">
  145. <view class="messages-header">
  146. <text class="messages-title">消息记录 ({{tcpMessages.length}})</text>
  147. <button class="clear-btn" @click="clearTcpMessages">清空</button>
  148. </view>
  149. <scroll-view scroll-y class="messages-list" scroll-top="{{tcpMessages.length * 50}}">
  150. <view class="message-item" v-for="(msg, index) in tcpMessages" :key="index"
  151. :class="{'sent': msg.direction === 'sent', 'received': msg.direction === 'received'}">
  152. <view class="message-info">
  153. <text class="message-direction">{{msg.direction === 'sent' ? '发送' : '接收'}}</text>
  154. <text class="message-time">{{msg.timestamp}}</text>
  155. </view>
  156. <text class="message-content">{{msg.content}}</text>
  157. </view>
  158. </scroll-view>
  159. </view>
  160. </view> -->
  161. <!-- 6. 今日市场看点 -->
  162. <view class="section-header highlights-title-container">
  163. <text class="section-title">今日市场核心看点</text>
  164. </view>
  165. <view class="highlights-image-container">
  166. <image src="https://d31zlh4on95l9h.cloudfront.net/images/8d5365af968402a18cedb120c09460b0.png" mode="aspectFit" class="highlights-image"></image>
  167. </view>
  168. <!-- 底部空间 - 为底部导航腾出空间 -->
  169. <view class="bottom-space"></view>
  170. </scroll-view>
  171. <!-- 底部导航 -->
  172. <footerBar class="static-footer" :type="type"></footerBar>
  173. </view>
  174. </template>
  175. <script>
  176. import footerBar from '../../components/footerBar.vue'
  177. import MarketOverview from '../../components/MarketOverview.vue'
  178. import DeepMate from '../../components/DeepMate.vue'
  179. import tcpConnection from '../../api/tcpConnection.js'
  180. import th from '../../static/language/th'
  181. import MySelectionsAPI from '../../api/home/mySelections.js'
  182. import { useUserStore } from '../../stores/modules/userInfo'
  183. export default {
  184. components: {
  185. footerBar,
  186. MarketOverview,
  187. DeepMate
  188. },
  189. data() {
  190. return {
  191. type: 'home',
  192. iSMT: 0,
  193. // 用户信息 store
  194. userStore: null,
  195. // 深度探索数据
  196. explorationItems: [
  197. { title: '主力追踪', icon: '/static/c1.png' },
  198. { title: '主力资金', icon: '/static/c2.png' },
  199. { title: '主力解码', icon: '/static/c3.png' },
  200. { title: '主力资金流', icon: '/static/c4.png' }
  201. ],
  202. // 我的自选股票数据
  203. myStocks: [
  204. { name: '特斯拉', code: 'TSLA', price: '482.00', change: 2.80, chartImg: '/static/c5.png' },
  205. { name: '英伟达', code: 'NVDA', price: '189.800', change: -2.92, chartImg: '/static/c6.png' },
  206. { name: '苹果', code: 'AAPL', price: '256.430', change: 2.60, chartImg: '/static/c7.png' }
  207. ],
  208. // 机构动向简报数据
  209. institutionalReports: [
  210. { stock: '特斯拉', status: '当前市场多头资金占比,且多头资金持续流入。' },
  211. { stock: '英伟达', status: '当前市场多头资金占比,且多头资金持续流入。' },
  212. { stock: '苹果', status: '当前市场多头资金占比,且多头资金持续流入。' }
  213. ],
  214. // 防抖定时器
  215. debounceTimer: null,
  216. // TCP连接相关状态
  217. tcpConnected: false,
  218. tcpMessages: [],
  219. lastSentMessage: '',
  220. // 我的自选TCP连接状态
  221. myStocksTcpConnected: false,
  222. // TCP监听器引用,用于移除监听器
  223. connectionListener: null,
  224. messageListener: null,
  225. // TCP股票数据存储
  226. tcpStockData: {
  227. count: 0,
  228. data: {},
  229. stock_count: 0,
  230. timestamp: '',
  231. type: ''
  232. },
  233. // 当前TCP使用的股票代码
  234. currentStockCodes: ['SH.000001', 'SH.000002', 'SH.000003'],
  235. // 我的自选TCP股票数据存储
  236. myStocksTcpData: {
  237. count: 0,
  238. data: {},
  239. stock_count: 0,
  240. timestamp: '',
  241. type: ''
  242. },
  243. // TCP数据缓存机制,用于处理分片数据
  244. tcpDataCache: {
  245. isCollecting: false, // 是否正在收集数据片段
  246. expectedCount: 0, // 期望的数据总数
  247. collectedData: {}, // 已收集的数据对象(用于对象级拼接)
  248. timestamp: '', // 数据时间戳
  249. type: '', // 数据类型
  250. // 新增:字符串片段缓存
  251. firstPartData: '', // 前半部分数据字符串
  252. isWaitingSecondPart: false // 是否正在等待后半部分数据
  253. },
  254. // 我的自选TCP数据缓存机制,用于处理分片数据
  255. myStocksTcpDataCache: {
  256. isCollecting: false, // 是否正在收集数据片段
  257. expectedCount: 0, // 期望的数据总数
  258. collectedData: {}, // 已收集的数据对象(用于对象级拼接)
  259. timestamp: '', // 数据时间戳
  260. type: '', // 数据类型
  261. // 字符串片段缓存
  262. firstPartData: '', // 前半部分数据字符串
  263. isWaitingSecondPart: false // 是否正在等待后半部分数据
  264. },
  265. // 当前显示的3个股票数据(用于MarketOverview组件)
  266. currentStockInfoList: [
  267. {
  268. stock_name: '美元/日元',
  269. current_price: '151.13',
  270. change: '+1.62%',
  271. change_value: 0,
  272. change_percent: 0
  273. },
  274. {
  275. stock_name: '美元/韩元',
  276. current_price: '1424.900',
  277. change: '-2.92%',
  278. change_value: 0,
  279. change_percent: 0
  280. },
  281. {
  282. stock_name: '美元/英镑',
  283. current_price: '0.730',
  284. change: '+2.92%',
  285. change_value: 0,
  286. change_percent: 0
  287. }
  288. ],
  289. // 我的自选处理后的股票信息列表
  290. myStocksInfoList: []
  291. }
  292. },
  293. // Vue 2生命周期方法
  294. mounted() {
  295. // 状态栏高度
  296. this.iSMT = uni.getSystemInfoSync().statusBarHeight;
  297. // 初始化用户信息 store
  298. this.userStore = useUserStore();
  299. // 预加载图片资源
  300. this.myStocks.forEach(stock => {
  301. // 使用uni.getImageInfo替代Image对象
  302. uni.getImageInfo({
  303. src: stock.chartImg,
  304. success: function(res) {
  305. // 图片加载成功
  306. console.log('图片预加载成功:', stock.name)
  307. },
  308. fail: function(err) {
  309. console.log('图片预加载失败:', err)
  310. }
  311. })
  312. })
  313. // 检查用户登录状态,只有已登录并且不是游客才加载自选股数据
  314. if (this.userStore.userInfo && !this.userStore.userInfo.isVisitor) {
  315. console.log('是用户登录,加载自选股数据', this.userStore.userInfo)
  316. this.loadMySelectionsData()
  317. } else if (this.userStore.userInfo && this.userStore.userInfo.isVisitor){
  318. console.log('是游客登录,加载默认自选股',this.userStore.userInfo)
  319. this.loadGuestDefaultStocks()
  320. }else {
  321. console.log('用户未登录',this.userStore.userInfo)
  322. }
  323. // 初始化TCP连接监听器
  324. this.initTcpListeners()
  325. // 页面渲染完成后自动连接两个TCP连接
  326. this.$nextTick(() => {
  327. console.log('页面渲染完成,开始自动连接TCP服务器...')
  328. // 延迟一小段时间确保页面完全加载后再连接
  329. setTimeout(() => {
  330. // 连接今日市场概览TCP(channel 1)
  331. console.log('连接今日市场概览TCP(channel 1)...')
  332. this.connectTcp()
  333. // 稍微延迟后连接我的自选TCP(channel 2)
  334. setTimeout(() => {
  335. console.log('连接我的自选TCP(channel 2)...')
  336. this.connectMyStocksTcp()
  337. }, 500)
  338. }, 1000)
  339. })
  340. },
  341. // 页面销毁前的清理工作
  342. onUnload() {
  343. // 自动关闭主TCP连接
  344. if (this.tcpConnected) {
  345. console.log('页面销毁,自动关闭主TCP连接')
  346. tcpConnection.disconnect({
  347. ip: '192.168.1.9',
  348. port: '8080',
  349. channel: '1',
  350. charsetname: 'UTF-8'
  351. })
  352. this.tcpConnected = false
  353. }
  354. // 自动关闭我的自选TCP连接
  355. if (this.myStocksTcpConnected) {
  356. console.log('页面销毁,自动关闭我的自选TCP连接')
  357. tcpConnection.disconnect({
  358. ip: '192.168.1.9',
  359. port: '8080',
  360. channel: '2',
  361. charsetname: 'UTF-8'
  362. })
  363. this.myStocksTcpConnected = false
  364. }
  365. // 清理防抖定时器
  366. if (this.debounceTimer) {
  367. clearTimeout(this.debounceTimer)
  368. this.debounceTimer = null
  369. }
  370. // 移除TCP监听器,防止内存泄漏
  371. this.removeTcpListeners()
  372. },
  373. methods: {
  374. // 防抖函数
  375. debounce(fn, delay = 300) {
  376. if (this.debounceTimer) clearTimeout(this.debounceTimer)
  377. this.debounceTimer = setTimeout(() => {
  378. fn()
  379. this.debounceTimer = null
  380. }, delay)
  381. },
  382. // 自选股数据加载相关方法
  383. // 加载自选股数据的主方法
  384. async loadMySelectionsData() {
  385. try {
  386. console.log('开始加载自选股数据...')
  387. // 调用checkExist判断用户是否存在自选股
  388. const checkResult = await MySelectionsAPI.checkExist()
  389. console.log('检查用户自选股存在性结果:', checkResult)
  390. if (checkResult.code === 200) {
  391. const isHave = checkResult.data.is_have
  392. if (isHave === 1) {
  393. // 用户有自选股,查询所有分组
  394. console.log('用户存在自选股,查询所有分组...')
  395. await this.loadUserStockGroups()
  396. } else {
  397. // 用户没有自选股,查询默认自选股
  398. console.log('用户不存在自选股,查询默认自选股...')
  399. await this.loadDefaultStocks()
  400. }
  401. } else {
  402. console.error('检查用户自选股存在性失败:', checkResult.message)
  403. // 失败时也尝试加载默认自选股
  404. // await this.loadDefaultStocks()
  405. }
  406. } catch (error) {
  407. console.error('加载自选股数据失败:', error)
  408. // 出错时尝试加载默认自选股
  409. await this.loadDefaultStocks()
  410. }
  411. },
  412. // 加载用户自选股分组
  413. async loadUserStockGroups() {
  414. try {
  415. const groupResult = await MySelectionsAPI.getUserStockGroupList()
  416. console.log('查询用户自选股分组结果:', groupResult)
  417. if (groupResult.code === 200 && groupResult.data && groupResult.data.length > 0) {
  418. // 找到id最小的分组
  419. const minIdGroup = groupResult.data.reduce((min, current) => {
  420. return current.id < min.id ? current : min
  421. })
  422. console.log('找到最小id分组:', minIdGroup)
  423. // 查询该分组下的股票
  424. await this.loadGroupStocks(minIdGroup.id)
  425. } else {
  426. console.log('没有找到用户自选股分组,加载默认自选股')
  427. await this.loadDefaultStocks()
  428. }
  429. } catch (error) {
  430. console.error('加载用户自选股分组失败:', error)
  431. await this.loadDefaultStocks()
  432. }
  433. },
  434. // 加载指定分组下的股票
  435. async loadGroupStocks(groupId) {
  436. try {
  437. const stockResult = await MySelectionsAPI.getUserStockList(null, null, {
  438. groupId: groupId,
  439. pageNum: 1,
  440. pageSize: 20
  441. })
  442. console.log('查询分组自选股结果:', stockResult)
  443. if (stockResult.code === 200 && stockResult.data) {
  444. this.processStockData(stockResult.data)
  445. } else {
  446. console.log('分组下没有股票数据,加载默认自选股')
  447. await this.loadDefaultStocks()
  448. }
  449. } catch (error) {
  450. console.error('加载分组股票失败:', error)
  451. await this.loadDefaultStocks()
  452. }
  453. },
  454. // 加载默认自选股
  455. async loadDefaultStocks() {
  456. try {
  457. const defaultResult = await MySelectionsAPI.getUserOrDefault()
  458. console.log('查询默认自选股结果:', defaultResult)
  459. if (defaultResult.code === 200 && defaultResult.data) {
  460. this.processStockData(defaultResult.data)
  461. } else {
  462. console.log('没有默认自选股数据')
  463. }
  464. } catch (error) {
  465. console.error('加载默认自选股失败:', error)
  466. }
  467. },
  468. // 游客加载默认自选股
  469. async loadGuestDefaultStocks() {
  470. try {
  471. console.log('游客开始加载默认自选股...')
  472. const guestResult = await MySelectionsAPI.getDefaultStocks()
  473. console.log('游客查询默认自选股结果:', guestResult)
  474. if (guestResult.code === 200 && guestResult.data) {
  475. this.processStockData(guestResult.data)
  476. } else {
  477. console.log('游客没有默认自选股数据')
  478. }
  479. } catch (error) {
  480. console.error('游客加载默认自选股失败:', error)
  481. }
  482. },
  483. // 处理股票数据
  484. processStockData(stockData) {
  485. console.log('处理股票数据:', stockData)
  486. // 根据返回的数据结构更新myStocks数组
  487. // 这里需要根据实际API返回的数据结构进行调整
  488. if (Array.isArray(stockData)) {
  489. // 如果是数组格式
  490. this.myStocks = stockData.map(stock => ({
  491. name: stock.name || stock.stock_name || '',
  492. code: stock.code || stock.stock_code || '',
  493. // price: stock.price || stock.current_price || '0.00',
  494. // change: stock.change || stock.change_percent || 0,
  495. chartImg: stock.chartImg || '/static/c5.png' // 默认图片
  496. }))
  497. //重新赋值机构动向简报
  498. this.institutionalReports = stockData.map(stock => ({
  499. stock: stock.name || stock.stock_name || '',
  500. status: stock.code || stock.stock_code || '',
  501. }))
  502. } else if (stockData.list && Array.isArray(stockData.list)) {
  503. // 如果是分页格式
  504. this.myStocks = stockData.list.map(stock => ({
  505. name: stock.name || stock.stock_name || '',
  506. code: stock.code || stock.stock_code || '',
  507. // price: stock.price || stock.current_price || '0.00',
  508. // change: stock.change || stock.change_percent || 0,
  509. chartImg: stock.chartImg || '/static/c5.png' // 默认图片
  510. }))
  511. //重新赋值机构动向简报
  512. //重新赋值机构动向简报
  513. this.institutionalReports = stockData.map(stock => ({
  514. stock: stock.name || stock.stock_name || '',
  515. status: stock.code || stock.stock_code || '',
  516. }))
  517. }
  518. console.log('更新后的自选股数据:', this.myStocks)
  519. // 更新TCP消息中的股票代码
  520. this.updateTcpStockCodes()
  521. },
  522. // 更新TCP消息中的股票代码
  523. updateTcpStockCodes() {
  524. // 从myStocks中提取前3个股票代码
  525. const stockCodes = this.myStocks.slice(0, 3).map(stock => stock.code).filter(code => code)
  526. console.log('更新TCP消息股票代码:', stockCodes)
  527. // 如果有股票代码,更新TCP消息
  528. if (stockCodes.length > 0) {
  529. // 补充到3个代码(如果不足3个,用默认代码补充)
  530. while (stockCodes.length < 3) {
  531. stockCodes.push('SH.000001') // 默认代码
  532. }
  533. // 保存到组件数据中,供TCP方法使用
  534. this.currentStockCodes = stockCodes
  535. console.log('当前TCP使用的股票代码:', this.currentStockCodes)
  536. }
  537. },
  538. // TCP连接相关方法
  539. // 初始化TCP监听器
  540. initTcpListeners() {
  541. // 创建连接状态监听器并保存引用
  542. this.connectionListener = (status, result, channel) => {
  543. console.log('TCP连接状态变化:', status, 'channel:', channel)
  544. // 根据channel更新对应的连接状态
  545. if (channel === '1') {
  546. // 主TCP连接
  547. this.tcpConnected = (status === 'connected')
  548. console.log('主TCP连接状态:', this.tcpConnected)
  549. // 显示连接状态提示
  550. uni.showToast({
  551. title: status === 'connected' ? '主连接服务器成功' : '主服务器连接断开',
  552. icon: status === 'connected' ? 'success' : 'none',
  553. duration: 1000
  554. })
  555. // 连接成功后自动发送股票数据请求命令
  556. if (status === 'connected') {
  557. console.log('主TCP连接成功,自动发送股票数据请求...')
  558. // 延迟一小段时间确保连接稳定后再发送命令
  559. setTimeout(() => {
  560. this.sendTcpMessage()
  561. }, 500)
  562. }
  563. } else if (channel === '2') {
  564. // 我的自选TCP连接
  565. this.myStocksTcpConnected = (status === 'connected')
  566. console.log('我的自选TCP连接状态:', this.myStocksTcpConnected)
  567. // 显示连接状态提示
  568. uni.showToast({
  569. title: status === 'connected' ? '我的自选连接成功' : '我的自选连接断开',
  570. icon: status === 'connected' ? 'success' : 'none',
  571. duration: 1000
  572. })
  573. // 连接成功后自动发送我的自选股票数据请求
  574. if (status === 'connected') {
  575. console.log('我的自选TCP连接成功,自动发送自选股票数据请求...')
  576. // 延迟一小段时间确保连接稳定后再发送命令
  577. setTimeout(() => {
  578. this.sendMyStocksTcpMessage()
  579. }, 500)
  580. }
  581. }
  582. }
  583. // 创建消息监听器并保存引用
  584. this.messageListener = (type, message, parsedArray, channel) => {
  585. const messageObj = {
  586. type: type,
  587. content: message,
  588. parsedArray: parsedArray,
  589. channel: channel,
  590. timestamp: new Date().toLocaleTimeString(),
  591. direction: 'received'
  592. }
  593. this.tcpMessages.push(messageObj)
  594. console.log('收到TCP消息:', messageObj)
  595. console.log('消息来源channel:', channel)
  596. // 根据channel调用相应的数据处理方法
  597. if (channel === '1') {
  598. // 主TCP连接 - 今日市场概览数据
  599. // console.log('处理今日市场概览数据')
  600. this.parseStockData(message)
  601. } else if (channel === '2') {
  602. // 我的自选TCP连接 - 我的自选数据
  603. console.log('处理我的自选数据')
  604. this.parseMyStocksData(message)
  605. } else {
  606. console.warn('未知的channel:', channel)
  607. }
  608. }
  609. // 注册监听器
  610. tcpConnection.onConnectionChange(this.connectionListener)
  611. tcpConnection.onMessage(this.messageListener)
  612. },
  613. // 连接TCP服务器
  614. connectTcp() {
  615. // console.log('开始连接TCP服务器...')
  616. // 先断开现有连接(如果存在)
  617. if (this.tcpConnected) {
  618. // console.log('检测到现有连接,先断开...')
  619. this.disconnectTcp()
  620. // 等待断开完成后再连接
  621. setTimeout(() => {
  622. this.performTcpConnect()
  623. }, 500)
  624. } else {
  625. // 直接连接
  626. this.performTcpConnect()
  627. }
  628. },
  629. // 执行TCP连接
  630. performTcpConnect() {
  631. // console.log('执行TCP连接...')
  632. tcpConnection.connect(
  633. {
  634. ip: '192.168.1.9',
  635. port: '8080',
  636. channel: '1', // 可选 1~20
  637. charsetname: 'UTF-8' // 默认UTF-8,可选GBK
  638. }
  639. )
  640. },
  641. // 断开TCP连接
  642. disconnectTcp() {
  643. // console.log('断开TCP连接...')
  644. tcpConnection.disconnect(
  645. {
  646. ip: '192.168.1.9',
  647. port: '8080',
  648. channel: '1', // 可选 1~20
  649. charsetname: 'UTF-8' // 默认UTF-8,可选GBK
  650. }
  651. )
  652. this.tcpConnected = false
  653. },
  654. // 连接我的自选TCP服务器
  655. connectMyStocksTcp() {
  656. console.log('开始连接我的自选TCP服务器...')
  657. // 先断开现有连接(如果存在)
  658. if (this.myStocksTcpConnected) {
  659. console.log('检测到我的自选现有连接,先断开...')
  660. this.disconnectMyStocksTcp()
  661. // 等待断开完成后再连接
  662. setTimeout(() => {
  663. this.performMyStocksTcpConnect()
  664. }, 500)
  665. } else {
  666. // 直接连接
  667. this.performMyStocksTcpConnect()
  668. }
  669. },
  670. // 执行我的自选TCP连接
  671. performMyStocksTcpConnect() {
  672. console.log('执行我的自选TCP连接...')
  673. tcpConnection.connect(
  674. {
  675. ip: '192.168.1.9',
  676. port: '8080',
  677. channel: '2', // 我的自选使用channel 2
  678. charsetname: 'UTF-8' // 默认UTF-8,可选GBK
  679. }
  680. )
  681. },
  682. // 断开我的自选TCP连接
  683. disconnectMyStocksTcp() {
  684. console.log('断开我的自选TCP连接...')
  685. tcpConnection.disconnect(
  686. {
  687. ip: '192.168.1.9',
  688. port: '8080',
  689. channel: '2', // 我的自选使用channel 2
  690. charsetname: 'UTF-8' // 默认UTF-8,可选GBK
  691. }
  692. )
  693. this.myStocksTcpConnected = false
  694. },
  695. // 解析我的自选TCP股票数据
  696. parseMyStocksData(message) {
  697. try {
  698. console.log('进入parseMyStocksData, message类型:', typeof message, '长度:', message.length)
  699. // 第一步:检查数据状态(完整、前半部分、后半部分)
  700. const dataStatus = this.getMyStocksDataStatus(message)
  701. let completeMessage = ''
  702. switch (dataStatus) {
  703. case 'complete':
  704. // 完整数据,直接处理
  705. console.log('我的自选:检测到完整数据,直接处理')
  706. completeMessage = message
  707. break
  708. case 'first_part':
  709. // 前半部分数据,缓存并等待后半部分
  710. console.log('我的自选:检测到前半部分数据,开始缓存')
  711. this.cacheMyStocksFirstPartData(message)
  712. return // 等待后半部分数据
  713. case 'second_part':
  714. // 后半部分数据,检查是否有缓存的前半部分
  715. if (this.myStocksTcpDataCache.isWaitingSecondPart) {
  716. console.log('我的自选:检测到后半部分数据,开始拼接')
  717. completeMessage = this.concatenateMyStocksDataParts(message)
  718. } else {
  719. console.log('我的自选:收到后半部分数据,但没有缓存的前半部分,跳过处理')
  720. return
  721. }
  722. break
  723. case 'invalid':
  724. default:
  725. console.log('我的自选:数据格式无效,跳过处理')
  726. return
  727. }
  728. // 第二步:解析完整的JSON数据
  729. let parsedMessage
  730. try {
  731. console.log('我的自选:开始解析完整JSON数据,长度:', completeMessage.length)
  732. parsedMessage = JSON.parse(completeMessage)
  733. console.log('我的自选:JSON解析成功,解析后类型:', typeof parsedMessage, parsedMessage)
  734. } catch (parseError) {
  735. console.error('我的自选:JSON解析失败:', parseError.message)
  736. // 清空字符串片段缓存
  737. this.clearMyStocksStringFragmentCache()
  738. return
  739. }
  740. // 第三步:检查是否是股票数据类型
  741. if (!((parsedMessage.type === 'batch_data_chunk' || parsedMessage.type === 'batch_realtime_data') && parsedMessage.data)) {
  742. console.log('我的自选:不是batch_data_chunk或batch_realtime_data类型的消息,跳过处理')
  743. return
  744. }
  745. console.log('我的自选:开始处理股票数据')
  746. // 第四步:验证数据完整性(对象级别的完整性检查)
  747. // 注意:batch_data_chunk类型的数据不需要验证完整性,直接处理
  748. if (parsedMessage.type === 'batch_data_chunk') {
  749. console.log('我的自选:batch_data_chunk类型数据,跳过完整性验证,直接处理')
  750. this.processCompleteMyStocksData(parsedMessage)
  751. } else {
  752. const isDataComplete = this.validateMyStocksDataIntegrity(parsedMessage)
  753. if (isDataComplete) {
  754. // 数据完整,直接处理
  755. console.log('我的自选:对象级数据完整,直接处理')
  756. this.processCompleteMyStocksData(parsedMessage)
  757. } else {
  758. // 数据不完整,需要拼接(对象级别的拼接)
  759. console.log('我的自选:对象级数据不完整,开始拼接处理')
  760. // 将当前数据合并到缓存中
  761. this.mergeMyStocksDataToCache(parsedMessage)
  762. // 检查缓存中的数据是否已经完整
  763. if (this.isMyStocksCacheDataComplete()) {
  764. console.log('我的自选:缓存数据已完整,开始处理')
  765. const completeData = this.getCompleteMyStocksDataFromCache()
  766. this.processCompleteMyStocksData(completeData)
  767. } else {
  768. console.log('我的自选:缓存数据仍不完整,等待更多数据片段')
  769. }
  770. }
  771. }
  772. } catch (error) {
  773. console.error('我的自选:解析TCP股票数据失败:', error.message)
  774. console.error('我的自选:错误详情:', error)
  775. // 发生错误时清空所有缓存
  776. this.clearMyStocksStringFragmentCache()
  777. if (this.myStocksTcpDataCache.isCollecting) {
  778. console.log('我的自选:发生错误,清空对象级数据缓存')
  779. this.myStocksTcpDataCache.isCollecting = false
  780. this.myStocksTcpDataCache.expectedCount = 0
  781. this.myStocksTcpDataCache.collectedData = {}
  782. this.myStocksTcpDataCache.timestamp = ''
  783. this.myStocksTcpDataCache.type = ''
  784. }
  785. }
  786. },
  787. // 验证我的自选数据完整性
  788. validateMyStocksDataIntegrity(parsedMessage) {
  789. if (!parsedMessage.count || !parsedMessage.data) {
  790. return false
  791. }
  792. const dataObjectCount = Object.keys(parsedMessage.data).length
  793. const expectedCount = parsedMessage.count
  794. console.log(`我的自选数据完整性验证: 期望${expectedCount}个对象,实际${dataObjectCount}个对象`)
  795. return dataObjectCount === expectedCount
  796. },
  797. // 检查我的自选数据状态(完整数据、前半部分数据、后半部分数据)
  798. getMyStocksDataStatus(message) {
  799. if (typeof message !== 'string') {
  800. return 'invalid'
  801. }
  802. const trimmedMessage = message.trim()
  803. const startsWithBrace = trimmedMessage.startsWith('{')
  804. const endsWithBrace = trimmedMessage.endsWith('}')
  805. if (startsWithBrace && endsWithBrace) {
  806. // 以{开头,以}结尾 - 完整数据
  807. console.log('我的自选:检测到完整数据格式')
  808. return 'complete'
  809. } else if (startsWithBrace && !endsWithBrace) {
  810. // 以{开头,不以}结尾 - 前半部分数据
  811. console.log('我的自选:检测到前半部分数据')
  812. return 'first_part'
  813. } else if (!startsWithBrace && endsWithBrace) {
  814. // 不以{开头,以}结尾 - 后半部分数据
  815. console.log('我的自选:检测到后半部分数据')
  816. return 'second_part'
  817. } else {
  818. // 其他情况 - 无效数据
  819. console.log('我的自选:检测到无效数据格式')
  820. return 'invalid'
  821. }
  822. },
  823. // 缓存我的自选前半部分数据
  824. cacheMyStocksFirstPartData(message) {
  825. this.myStocksTcpDataCache.firstPartData = message.trim()
  826. this.myStocksTcpDataCache.isWaitingSecondPart = true
  827. console.log('我的自选:已缓存前半部分数据,长度:', this.myStocksTcpDataCache.firstPartData.length)
  828. },
  829. // 拼接我的自选前后两部分数据
  830. concatenateMyStocksDataParts(secondPartMessage) {
  831. const completeMessage = this.myStocksTcpDataCache.firstPartData + secondPartMessage.trim()
  832. console.log('我的自选:数据拼接完成,完整数据长度:', completeMessage.length)
  833. // 清空缓存
  834. this.clearMyStocksStringFragmentCache()
  835. return completeMessage
  836. },
  837. // 清空我的自选字符串片段缓存
  838. clearMyStocksStringFragmentCache() {
  839. this.myStocksTcpDataCache.firstPartData = ''
  840. this.myStocksTcpDataCache.isWaitingSecondPart = false
  841. console.log('我的自选:字符串片段缓存已清空')
  842. },
  843. // 合并我的自选数据到缓存中
  844. mergeMyStocksDataToCache(parsedMessage) {
  845. // 如果是第一次收集数据,初始化缓存
  846. if (!this.myStocksTcpDataCache.isCollecting) {
  847. this.myStocksTcpDataCache.isCollecting = true
  848. this.myStocksTcpDataCache.expectedCount = parsedMessage.count
  849. this.myStocksTcpDataCache.collectedData = {}
  850. this.myStocksTcpDataCache.timestamp = parsedMessage.timestamp
  851. this.myStocksTcpDataCache.type = parsedMessage.type
  852. console.log('我的自选:开始收集数据片段,期望总数:', parsedMessage.count)
  853. }
  854. // 合并新数据到缓存中
  855. if (parsedMessage.data) {
  856. Object.assign(this.myStocksTcpDataCache.collectedData, parsedMessage.data)
  857. console.log('我的自选:数据片段已合并,当前已收集:', Object.keys(this.myStocksTcpDataCache.collectedData).length, '个对象')
  858. }
  859. },
  860. // 检查我的自选缓存数据是否完整
  861. isMyStocksCacheDataComplete() {
  862. const collectedCount = Object.keys(this.myStocksTcpDataCache.collectedData).length
  863. const expectedCount = this.myStocksTcpDataCache.expectedCount
  864. console.log(`我的自选缓存数据检查: 已收集${collectedCount}个,期望${expectedCount}`)
  865. return collectedCount === expectedCount && collectedCount > 0
  866. },
  867. // 获取我的自选完整的缓存数据并清空缓存
  868. getCompleteMyStocksDataFromCache() {
  869. const completeData = {
  870. count: this.myStocksTcpDataCache.expectedCount,
  871. data: { ...this.myStocksTcpDataCache.collectedData },
  872. stock_count: this.myStocksTcpDataCache.expectedCount,
  873. timestamp: this.myStocksTcpDataCache.timestamp,
  874. type: this.myStocksTcpDataCache.type
  875. }
  876. // 清空缓存
  877. this.myStocksTcpDataCache.isCollecting = false
  878. this.myStocksTcpDataCache.expectedCount = 0
  879. this.myStocksTcpDataCache.collectedData = {}
  880. this.myStocksTcpDataCache.timestamp = ''
  881. this.myStocksTcpDataCache.type = ''
  882. console.log('我的自选:获取完整数据并清空缓存,数据对象数:', Object.keys(completeData.data).length)
  883. return completeData
  884. },
  885. // 处理我的自选完整的股票数据
  886. processCompleteMyStocksData(completeData) {
  887. console.log("我的自选:开始更新我的自选TCP股票数据存储")
  888. // 更新我的自选TCP股票数据存储
  889. this.myStocksTcpData = {
  890. count: completeData.count || 0,
  891. data: completeData.data || {},
  892. stock_count: completeData.stock_count || 0,
  893. timestamp: completeData.timestamp || '',
  894. type: completeData.type || ''
  895. }
  896. // 获取所有股票的数据用于显示
  897. const stockCodes = Object.keys(completeData.data)
  898. const newMyStocksInfoList = []
  899. // 只处理前3条股票数据
  900. const maxStocks = Math.min(3, stockCodes.length)
  901. for (let i = 0; i < maxStocks; i++) {
  902. const stockCode = stockCodes[i]
  903. // 检查数据结构
  904. if (completeData.data[stockCode] && Array.isArray(completeData.data[stockCode]) && completeData.data[stockCode].length > 0) {
  905. const stockData = completeData.data[stockCode][0] // 取第一条数据
  906. console.log('遍历的数据:', stockCode, stockData)
  907. if (stockData && stockData.current_price !== undefined) {
  908. // 直接使用返回的数据,不重新计算
  909. newMyStocksInfoList.push({
  910. stock_code: stockCode,
  911. stock_name: stockData.stock_name || '未知股票',
  912. current_price: parseFloat(stockData.current_price).toFixed(2),
  913. change: stockData.change || '0.00%',
  914. change_value: stockData.change_value || 0,
  915. change_percent: parseFloat(stockData.change) || 0
  916. })
  917. }
  918. }
  919. }
  920. // 更新我的自选股票信息列表
  921. if (newMyStocksInfoList.length > 0) {
  922. this.myStocksInfoList = newMyStocksInfoList
  923. console.log('我的自选:股票数据更新成功,共', newMyStocksInfoList.length, '个股票:', this.myStocksInfoList)
  924. }
  925. },
  926. // 发送TCP消息
  927. sendTcpMessage() {
  928. // 构造要发送的消息对象
  929. const messageData =
  930. // {
  931. // command: "real_time",
  932. // stock_code: "SH.000001"
  933. // }
  934. // {"command": "stock_list"}
  935. // {"command": "batch_real_time", "stock_codes": ["SH.000001"]}
  936. {"command": "batch_real_time", "stock_codes": this.currentStockCodes}
  937. // 发送消息
  938. const success = tcpConnection.send(messageData)
  939. if (success) {
  940. // console.log('home发送TCP消息:', messageData)
  941. uni.showToast({
  942. title: '服务器连接成功',
  943. icon: 'success',
  944. duration: 1500
  945. })
  946. }
  947. },
  948. // 发送我的自选TCP消息
  949. sendMyStocksTcpMessage() {
  950. // 构造要发送的消息对象 - 我的自选股票数据请求
  951. const messageData = {"command": "batch_real_time", "stock_codes": this.currentStockCodes}
  952. // 发送消息到channel 2(我的自选TCP连接)
  953. const success = tcpConnection.send(messageData, { channel: '2' })
  954. if (success) {
  955. console.log('我的自选:发送TCP消息成功:', messageData)
  956. uni.showToast({
  957. title: '我的自选数据请求已发送',
  958. icon: 'success',
  959. duration: 1500
  960. })
  961. } else {
  962. console.error('我的自选:发送TCP消息失败')
  963. uni.showToast({
  964. title: '我的自选连接失败',
  965. icon: 'error',
  966. duration: 1500
  967. })
  968. }
  969. },
  970. // 清空消息记录
  971. clearTcpMessages() {
  972. this.tcpMessages = []
  973. uni.showToast({
  974. title: '消息记录已清空',
  975. icon: 'success',
  976. duration: 1500
  977. })
  978. },
  979. // 获取TCP连接状态
  980. getTcpStatus() {
  981. const status = tcpConnection.getConnectionStatus()
  982. uni.showModal({
  983. title: 'TCP连接状态',
  984. content: `当前状态: ${status ? '已连接' : '未连接'}\n消息数量: ${this.tcpMessages.length}`,
  985. showCancel: false
  986. })
  987. },
  988. // 验证数据完整性(检查count值与data对象个数是否相等)
  989. validateDataIntegrity(parsedMessage) {
  990. if (!parsedMessage.count || !parsedMessage.data) {
  991. return false
  992. }
  993. const dataObjectCount = Object.keys(parsedMessage.data).length
  994. const expectedCount = parsedMessage.count
  995. // console.log(`数据完整性验证: 期望${expectedCount}个对象,实际${dataObjectCount}个对象`)
  996. return dataObjectCount === expectedCount
  997. },
  998. // 检查数据状态(完整数据、前半部分数据、后半部分数据)
  999. getDataStatus(message) {
  1000. if (typeof message !== 'string') {
  1001. return 'invalid'
  1002. }
  1003. const trimmedMessage = message.trim()
  1004. const startsWithBrace = trimmedMessage.startsWith('{')
  1005. const endsWithBrace = trimmedMessage.endsWith('}')
  1006. if (startsWithBrace && endsWithBrace) {
  1007. // 以{开头,以}结尾 - 完整数据
  1008. // console.log('检测到完整数据格式')
  1009. return 'complete'
  1010. } else if (startsWithBrace && !endsWithBrace) {
  1011. // 以{开头,不以}结尾 - 前半部分数据
  1012. // console.log('检测到前半部分数据')
  1013. return 'first_part'
  1014. } else if (!startsWithBrace && endsWithBrace) {
  1015. // 不以{开头,以}结尾 - 后半部分数据
  1016. // console.log('检测到后半部分数据')
  1017. return 'second_part'
  1018. } else {
  1019. // 其他情况 - 无效数据
  1020. // console.log('检测到无效数据格式')
  1021. return 'invalid'
  1022. }
  1023. },
  1024. // 缓存前半部分数据
  1025. cacheFirstPartData(message) {
  1026. this.tcpDataCache.firstPartData = message.trim()
  1027. this.tcpDataCache.isWaitingSecondPart = true
  1028. // console.log('已缓存前半部分数据,长度:', this.tcpDataCache.firstPartData.length)
  1029. },
  1030. // 拼接前后两部分数据
  1031. concatenateDataParts(secondPartMessage) {
  1032. const completeMessage = this.tcpDataCache.firstPartData + secondPartMessage.trim()
  1033. // console.log('数据拼接完成,完整数据长度:', completeMessage.length)
  1034. // 清空缓存
  1035. this.clearStringFragmentCache()
  1036. return completeMessage
  1037. },
  1038. // 清空字符串片段缓存
  1039. clearStringFragmentCache() {
  1040. this.tcpDataCache.firstPartData = ''
  1041. this.tcpDataCache.isWaitingSecondPart = false
  1042. // console.log('字符串片段缓存已清空')
  1043. },
  1044. // 合并数据到缓存中
  1045. mergeDataToCache(parsedMessage) {
  1046. // 如果是第一次收集数据,初始化缓存
  1047. if (!this.tcpDataCache.isCollecting) {
  1048. this.tcpDataCache.isCollecting = true
  1049. this.tcpDataCache.expectedCount = parsedMessage.count
  1050. this.tcpDataCache.collectedData = {}
  1051. this.tcpDataCache.timestamp = parsedMessage.timestamp
  1052. this.tcpDataCache.type = parsedMessage.type
  1053. // console.log('开始收集数据片段,期望总数:', parsedMessage.count)
  1054. }
  1055. // 合并新数据到缓存中
  1056. if (parsedMessage.data) {
  1057. Object.assign(this.tcpDataCache.collectedData, parsedMessage.data)
  1058. // console.log('数据片段已合并,当前已收集:', Object.keys(this.tcpDataCache.collectedData).length, '个对象')
  1059. }
  1060. },
  1061. // 检查缓存数据是否完整
  1062. isCacheDataComplete() {
  1063. const collectedCount = Object.keys(this.tcpDataCache.collectedData).length
  1064. const expectedCount = this.tcpDataCache.expectedCount
  1065. // console.log(`缓存数据检查: 已收集${collectedCount}个,期望${expectedCount}个`)
  1066. return collectedCount === expectedCount && collectedCount > 0
  1067. },
  1068. // 获取完整的缓存数据并清空缓存
  1069. getCompleteDataFromCache() {
  1070. const completeData = {
  1071. count: this.tcpDataCache.expectedCount,
  1072. data: { ...this.tcpDataCache.collectedData },
  1073. stock_count: this.tcpDataCache.expectedCount,
  1074. timestamp: this.tcpDataCache.timestamp,
  1075. type: this.tcpDataCache.type
  1076. }
  1077. // 清空缓存
  1078. this.tcpDataCache.isCollecting = false
  1079. this.tcpDataCache.expectedCount = 0
  1080. this.tcpDataCache.collectedData = {}
  1081. this.tcpDataCache.timestamp = ''
  1082. this.tcpDataCache.type = ''
  1083. // console.log('获取完整数据并清空缓存,数据对象数:', Object.keys(completeData.data).length)
  1084. return completeData
  1085. },
  1086. // 解析TCP股票数据
  1087. parseStockData(message) {
  1088. try {
  1089. // console.log('进入parseStockData, message类型:', typeof message, '长度:', message.length)
  1090. // 第一步:检查数据状态(完整、前半部分、后半部分)
  1091. const dataStatus = this.getDataStatus(message)
  1092. let completeMessage = ''
  1093. switch (dataStatus) {
  1094. case 'complete':
  1095. // 完整数据,直接处理
  1096. // console.log('检测到完整数据,直接处理')
  1097. completeMessage = message
  1098. break
  1099. case 'first_part':
  1100. // 前半部分数据,缓存并等待后半部分
  1101. // console.log('检测到前半部分数据,开始缓存')
  1102. this.cacheFirstPartData(message)
  1103. return // 等待后半部分数据
  1104. case 'second_part':
  1105. // 后半部分数据,检查是否有缓存的前半部分
  1106. if (this.tcpDataCache.isWaitingSecondPart) {
  1107. // console.log('检测到后半部分数据,开始拼接')
  1108. completeMessage = this.concatenateDataParts(message)
  1109. } else {
  1110. // console.log('收到后半部分数据,但没有缓存的前半部分,跳过处理')
  1111. return
  1112. }
  1113. break
  1114. case 'invalid':
  1115. default:
  1116. // console.log('数据格式无效,跳过处理')
  1117. return
  1118. }
  1119. // 第二步:解析完整的JSON数据
  1120. let parsedMessage
  1121. try {
  1122. // console.log('开始解析完整JSON数据,长度:', completeMessage.length)
  1123. parsedMessage = JSON.parse(completeMessage)
  1124. // console.log('JSON解析成功,解析后类型:', typeof parsedMessage, parsedMessage)
  1125. } catch (parseError) {
  1126. // console.error('JSON解析失败:', parseError.message)
  1127. // 清空字符串片段缓存
  1128. this.clearStringFragmentCache()
  1129. return
  1130. }
  1131. // 第三步:检查是否是股票数据类型
  1132. if (!((parsedMessage.type === 'batch_data_chunk' || parsedMessage.type === 'batch_realtime_data') && parsedMessage.data)) {
  1133. // console.log('不是batch_data_chunk或batch_realtime_data类型的消息,跳过处理')
  1134. return
  1135. }
  1136. // console.log('开始处理股票数据')
  1137. // 第四步:验证数据完整性(对象级别的完整性检查)
  1138. // 注意:batch_data_chunk类型的数据不需要验证完整性,直接处理
  1139. if (parsedMessage.type === 'batch_data_chunk') {
  1140. // console.log('batch_data_chunk类型数据,跳过完整性验证,直接处理')
  1141. this.processCompleteStockData(parsedMessage)
  1142. } else {
  1143. const isDataComplete = this.validateDataIntegrity(parsedMessage)
  1144. if (isDataComplete) {
  1145. // 数据完整,直接处理
  1146. // console.log('对象级数据完整,直接处理')
  1147. this.processCompleteStockData(parsedMessage)
  1148. } else {
  1149. // 数据不完整,需要拼接(对象级别的拼接)
  1150. // console.log('对象级数据不完整,开始拼接处理')
  1151. // 将当前数据合并到缓存中
  1152. this.mergeDataToCache(parsedMessage)
  1153. // 检查缓存中的数据是否已经完整
  1154. if (this.isCacheDataComplete()) {
  1155. // console.log('缓存数据已完整,开始处理')
  1156. const completeData = this.getCompleteDataFromCache()
  1157. this.processCompleteStockData(completeData)
  1158. } else {
  1159. // console.log('缓存数据仍不完整,等待更多数据片段')
  1160. }
  1161. }
  1162. }
  1163. } catch (error) {
  1164. // console.error('解析TCP股票数据失败:', error.message)
  1165. // console.error('错误详情:', error)
  1166. // 发生错误时清空所有缓存
  1167. this.clearStringFragmentCache()
  1168. if (this.tcpDataCache.isCollecting) {
  1169. // console.log('发生错误,清空对象级数据缓存')
  1170. this.tcpDataCache.isCollecting = false
  1171. this.tcpDataCache.expectedCount = 0
  1172. this.tcpDataCache.collectedData = {}
  1173. this.tcpDataCache.timestamp = ''
  1174. this.tcpDataCache.type = ''
  1175. }
  1176. }
  1177. },
  1178. // 处理完整的股票数据
  1179. processCompleteStockData(completeData) {
  1180. // console.log("开始更新TCP股票数据存储")
  1181. // 更新TCP股票数据存储
  1182. this.tcpStockData = {
  1183. count: completeData.count || 0,
  1184. data: completeData.data || {},
  1185. stock_count: completeData.stock_count || 0,
  1186. timestamp: completeData.timestamp || '',
  1187. type: completeData.type || ''
  1188. }
  1189. // 获取所有股票的数据用于显示(最多3个)
  1190. const stockCodes = Object.keys(completeData.data)
  1191. const newStockInfoList = []
  1192. // 处理最多3个股票数据
  1193. for (let i = 0; i < Math.min(stockCodes.length, 3); i++) {
  1194. const stockCode = stockCodes[i]
  1195. // 检查数据结构
  1196. if (completeData.data[stockCode] && Array.isArray(completeData.data[stockCode]) && completeData.data[stockCode].length > 0) {
  1197. const stockData = completeData.data[stockCode][0] // 取第一条数据
  1198. if (stockData && stockData.current_price !== undefined && stockData.pre_close !== undefined) {
  1199. // 计算涨跌幅
  1200. const changeValue = stockData.current_price - stockData.pre_close
  1201. const changePercent = ((changeValue / stockData.pre_close) * 100).toFixed(2)
  1202. const changeSign = changeValue >= 0 ? '+' : ''
  1203. // 添加到股票信息列表
  1204. newStockInfoList.push({
  1205. stock_name: stockData.stock_name || '未知股票',
  1206. current_price: stockData.current_price ? stockData.current_price.toFixed(2) : '0.00',
  1207. change: `${changeSign}${changePercent}%`,
  1208. change_value: changeValue,
  1209. change_percent: parseFloat(changePercent)
  1210. })
  1211. }
  1212. }
  1213. }
  1214. // 更新当前显示的股票信息列表
  1215. if (newStockInfoList.length > 0) {
  1216. this.currentStockInfoList = newStockInfoList
  1217. // console.log('股票数据更新成功,共', newStockInfoList.length, '个股票:', this.currentStockInfoList)
  1218. }
  1219. },
  1220. // 移除TCP监听器
  1221. removeTcpListeners() {
  1222. if (this.connectionListener) {
  1223. tcpConnection.removeConnectionListener(this.connectionListener)
  1224. this.connectionListener = null
  1225. // console.log('已移除TCP连接状态监听器')
  1226. }
  1227. if (this.messageListener) {
  1228. tcpConnection.removeMessageListener(this.messageListener)
  1229. this.messageListener = null
  1230. // console.log('已移除TCP消息监听器')
  1231. }
  1232. }
  1233. }
  1234. }
  1235. </script>
  1236. <style scoped>
  1237. .main {
  1238. display: flex;
  1239. flex-direction: column;
  1240. height: 100vh;
  1241. background-color: #ffffff;
  1242. }
  1243. .header {
  1244. display: flex;
  1245. justify-content: space-between;
  1246. align-items: center;
  1247. padding: 10px 15px;
  1248. background-color: #ffffff;
  1249. }
  1250. .title {
  1251. font-size: 22px;
  1252. font-weight: bold;
  1253. text-align: center;
  1254. flex: 1;
  1255. }
  1256. .headphone-icon, .notification-icon {
  1257. width: 40px;
  1258. display: flex;
  1259. align-items: center;
  1260. justify-content: center;
  1261. }
  1262. .header-icon-image {
  1263. width: 24px;
  1264. height: 24px;
  1265. object-fit: contain;
  1266. }
  1267. .content-container {
  1268. flex: 1;
  1269. padding: 10px;
  1270. width: 100%;
  1271. box-sizing: border-box;
  1272. overflow-x: hidden;
  1273. }
  1274. .section {
  1275. margin-bottom: 15px;
  1276. /* background-color: #f5f5f5; */
  1277. background-color: #ffffff;
  1278. border-radius: 8px;
  1279. padding: 15px;
  1280. }
  1281. .section-header {
  1282. display: flex;
  1283. justify-content: space-between;
  1284. align-items: center;
  1285. margin-bottom: 15px;
  1286. padding-bottom: 10px;
  1287. }
  1288. .section-title {
  1289. font-size: 18px;
  1290. font-weight: bold;
  1291. color: #000000;
  1292. }
  1293. .section-title-text{
  1294. font-size: 14px;
  1295. }
  1296. .text-gap{
  1297. height: 10px;
  1298. }
  1299. .more-btn {
  1300. font-size: 12px;
  1301. font-weight: bold;
  1302. color: #ffffff;
  1303. background-color: #000000;
  1304. padding: 4px 8px;
  1305. border-radius: 4px;
  1306. }
  1307. /* 市场概览样式 */
  1308. .market-header {
  1309. display: flex;
  1310. justify-content: space-between;
  1311. align-items: center;
  1312. padding: 10px 15px;
  1313. background-color: #ffffff;
  1314. margin-bottom: 10px;
  1315. }
  1316. .market-content {
  1317. background-color: #f5f5f5;
  1318. border-radius: 8px;
  1319. padding: 15px;
  1320. margin: 0 15px;
  1321. }
  1322. .market-image {
  1323. margin-bottom: 15px;
  1324. display: flex;
  1325. justify-content: center;
  1326. }
  1327. .overview-image {
  1328. width: 100%;
  1329. border-radius: 8px;
  1330. }
  1331. .market-data {
  1332. display: flex;
  1333. flex-direction: column;
  1334. gap: 10px;
  1335. }
  1336. /* 间隔样式 */
  1337. .section-gap {
  1338. height: 20px;
  1339. }
  1340. .market-item {
  1341. display: flex;
  1342. justify-content: space-between;
  1343. padding: 8px 0;
  1344. border-bottom: 1px solid #f0f0f0;
  1345. }
  1346. .down {
  1347. color: #ff4d4f;
  1348. }
  1349. .up {
  1350. color: #52c41a;
  1351. }
  1352. /* DeepMate样式 */
  1353. .deepmate-container {
  1354. background-color: #ffe6e6;
  1355. border-radius: 10px;
  1356. padding: 15px;
  1357. margin: 0 15px;
  1358. }
  1359. .deepmate-header {
  1360. margin-bottom: 10px;
  1361. }
  1362. .title-container {
  1363. display: flex;
  1364. align-items: center;
  1365. justify-content: space-between;
  1366. width: 100%;
  1367. }
  1368. .title-left {
  1369. width: 50%;
  1370. }
  1371. .title-right {
  1372. width: 50%;
  1373. display: flex;
  1374. justify-content: flex-end;
  1375. }
  1376. .deepmate-title {
  1377. font-size: 18px;
  1378. font-weight: bold;
  1379. color: #ff4d4f;
  1380. }
  1381. .deepmate-icon {
  1382. width: 60px;
  1383. height: 60px;
  1384. margin-left: 0;
  1385. }
  1386. .deepmate-subtitle {
  1387. font-size: 12px;
  1388. color: #666;
  1389. margin-left: 5px;
  1390. }
  1391. .deepmate-hotspots {
  1392. margin: 10px 0;
  1393. }
  1394. .hotspot-item {
  1395. background-color: #f5f5f5;
  1396. padding: 8px 12px;
  1397. border-radius: 6px;
  1398. margin-bottom: 8px;
  1399. }
  1400. .hotspot-item text {
  1401. font-size: 14px;
  1402. color: #333;
  1403. }
  1404. .deepmate-action {
  1405. display: flex;
  1406. justify-content: center;
  1407. align-items: center;
  1408. background-color: #ffffff;
  1409. border-radius: 20px;
  1410. padding: 10px;
  1411. margin-top: 10px;
  1412. }
  1413. /* 欢迎部分样式 */
  1414. .welcome-section {
  1415. margin-bottom: 15px;
  1416. padding: 0;
  1417. }
  1418. .welcome-swiper {
  1419. width: 100%;
  1420. height: 150px;
  1421. border-radius: 0;
  1422. overflow: hidden;
  1423. }
  1424. .deepmate-section {
  1425. padding: 0;
  1426. }
  1427. .swiper-image {
  1428. width: 100%;
  1429. height: 100%;
  1430. border-radius: 8px;
  1431. object-fit: contain;
  1432. }
  1433. /* 深度探索样式 */
  1434. .deep-exploration {
  1435. margin-top: 15px;
  1436. padding: 0; /* 移除内边距,让子容器自己控制 */
  1437. }
  1438. .section-header-container {
  1439. margin-bottom: 10px;
  1440. }
  1441. .section-header {
  1442. display: flex;
  1443. justify-content: space-between;
  1444. align-items: center;
  1445. padding: 10px 15px;
  1446. background-color: #ffffff;
  1447. }
  1448. .header-left {
  1449. display: flex;
  1450. align-items: center;
  1451. }
  1452. .header-right {
  1453. display: flex;
  1454. align-items: center;
  1455. }
  1456. .section-title {
  1457. font-size: 16px;
  1458. font-weight: bold;
  1459. color: #333;
  1460. }
  1461. .more-btn {
  1462. font-size: 12px;
  1463. color: #ffffff;
  1464. }
  1465. .exploration-container {
  1466. border-radius: 8px;
  1467. overflow: hidden;
  1468. }
  1469. .exploration-content {
  1470. display: flex;
  1471. justify-content: space-between;
  1472. padding: 15px;
  1473. background-color: #f5f5f5;
  1474. border-radius: 8px;
  1475. }
  1476. .exploration-item {
  1477. display: flex;
  1478. flex-direction: column;
  1479. align-items: center;
  1480. width: 22%;
  1481. background-color: #ffffff;
  1482. border-radius: 8px;
  1483. padding: 10px 0;
  1484. }
  1485. .exploration-icon {
  1486. width: 50px;
  1487. height: 50px;
  1488. margin-bottom: 8px;
  1489. }
  1490. .exploration-text {
  1491. font-size: 12px;
  1492. color: #333;
  1493. }
  1494. .icon-text {
  1495. font-size: 12px;
  1496. }
  1497. /* 我的自选样式 */
  1498. .my-selection {
  1499. padding: 0; /* 移除内边距,让子容器自己控制 */
  1500. }
  1501. .stock-container {
  1502. border-radius: 8px;
  1503. overflow: hidden;
  1504. background-color: #f5f5f5;
  1505. padding: 15px;
  1506. box-sizing: border-box;
  1507. }
  1508. .stock-list {
  1509. display: flex;
  1510. flex-direction: row;
  1511. justify-content: center;
  1512. background-color: #f8f8f8;
  1513. border-radius: 8px;
  1514. padding: 15px;
  1515. gap: 10px; /* 添加卡片之间的间距 */
  1516. }
  1517. .stock-item {
  1518. display: flex;
  1519. flex-direction: column;
  1520. justify-content: space-between;
  1521. padding: 3px;
  1522. background-color: #ffffff;
  1523. border-radius: 8px;
  1524. width: 30%;
  1525. box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  1526. will-change: transform;
  1527. transform: translateZ(0);
  1528. }
  1529. .stock-info {
  1530. display: flex;
  1531. flex-direction: column;
  1532. align-items: center;
  1533. margin-bottom: 5px;
  1534. }
  1535. .stock-chart {
  1536. display: flex;
  1537. align-items: center;
  1538. justify-content: center;
  1539. }
  1540. .name-container {
  1541. display: flex;
  1542. align-items: center;
  1543. gap: 5px;
  1544. }
  1545. .stock-name {
  1546. font-size: 12px;
  1547. font-weight: bold;
  1548. color: #333;
  1549. }
  1550. .stock-code-label {
  1551. font-size: 12px;
  1552. color: #666;
  1553. background-color: #f5f5f5;
  1554. padding: 0 4px;
  1555. border-radius: 3px;
  1556. }
  1557. .stock-price {
  1558. font-size: 12px;
  1559. color: #666;
  1560. }
  1561. .price-container {
  1562. display: flex;
  1563. align-items: center;
  1564. gap: 5px;
  1565. }
  1566. .stock-change {
  1567. font-size: 12px;
  1568. }
  1569. .stock-up {
  1570. color: #4cd964;
  1571. }
  1572. .stock-down {
  1573. color: #ff3b30;
  1574. }
  1575. .chart-image {
  1576. width: 100px;
  1577. height: 40px;
  1578. }
  1579. /* 市场看点样式 */
  1580. .highlights-title-container {
  1581. background-color: #ffffff;
  1582. margin-bottom: 10px;
  1583. }
  1584. .highlights-image-container {
  1585. background-color: #f5f5f5;
  1586. border-radius: 8px;
  1587. padding: 10px;
  1588. margin-bottom: 15px;
  1589. }
  1590. .highlights-image {
  1591. width: 100%;
  1592. height: 150px;
  1593. border-radius: 4px;
  1594. }
  1595. /* 机构动向简报样式 */
  1596. .institutional-reports {
  1597. margin-top: 15px;
  1598. background-color: #f8f8f8;
  1599. border-radius: 8px;
  1600. padding: 10px;
  1601. }
  1602. .section-title-container {
  1603. position: relative;
  1604. padding-left: 10px;
  1605. margin-bottom: 5px;
  1606. }
  1607. .section-title-container:before {
  1608. content: "";
  1609. position: absolute;
  1610. left: 0;
  1611. top: 0;
  1612. bottom: 0;
  1613. width: 4px;
  1614. background-color: #ff4d4f;
  1615. border-radius: 2px;
  1616. }
  1617. .report-item {
  1618. background-color: #ffffff;
  1619. border-radius: 8px;
  1620. padding: 10px;
  1621. margin-bottom: 8px;
  1622. }
  1623. .report-stock {
  1624. font-size: 14px;
  1625. font-weight: bold;
  1626. color: #e74c3c;
  1627. margin-bottom: 5px;
  1628. }
  1629. .report-status {
  1630. font-size: 12px;
  1631. color: #333;
  1632. }
  1633. .view-more {
  1634. text-align: center;
  1635. color: #1890ff;
  1636. font-size: 12px;
  1637. padding: 5px;
  1638. }
  1639. /* 底部空间 */
  1640. .bottom-space {
  1641. height: 60px;
  1642. }
  1643. /* 底部导航 */
  1644. .static-footer {
  1645. position: fixed;
  1646. bottom: 0;
  1647. width: 100%;
  1648. }
  1649. /* TCP测试区域样式 */
  1650. .tcp-test-section {
  1651. border: 1px solid #e0e0e0;
  1652. background-color: #f9f9f9;
  1653. }
  1654. .tcp-status {
  1655. padding: 4px 12px;
  1656. border-radius: 12px;
  1657. font-size: 12px;
  1658. }
  1659. .tcp-status.connected {
  1660. background-color: #e8f5e8;
  1661. color: #4caf50;
  1662. border: 1px solid #4caf50;
  1663. }
  1664. .tcp-status.disconnected {
  1665. background-color: #ffeaea;
  1666. color: #f44336;
  1667. border: 1px solid #f44336;
  1668. }
  1669. .status-text {
  1670. font-size: 12px;
  1671. font-weight: bold;
  1672. }
  1673. .tcp-controls {
  1674. display: flex;
  1675. flex-wrap: wrap;
  1676. gap: 8px;
  1677. margin-bottom: 15px;
  1678. }
  1679. .tcp-btn {
  1680. flex: 1;
  1681. min-width: 80px;
  1682. height: 36px;
  1683. border-radius: 6px;
  1684. font-size: 12px;
  1685. border: none;
  1686. color: white;
  1687. font-weight: bold;
  1688. }
  1689. .connect-btn {
  1690. background-color: #4caf50;
  1691. }
  1692. .connect-btn:disabled {
  1693. background-color: #cccccc;
  1694. }
  1695. .disconnect-btn {
  1696. background-color: #f44336;
  1697. }
  1698. .disconnect-btn:disabled {
  1699. background-color: #cccccc;
  1700. }
  1701. .send-btn {
  1702. background-color: #2196f3;
  1703. }
  1704. .send-btn:disabled {
  1705. background-color: #cccccc;
  1706. }
  1707. .status-btn {
  1708. background-color: #ff9800;
  1709. }
  1710. .tcp-messages {
  1711. margin-top: 15px;
  1712. border-top: 1px solid #e0e0e0;
  1713. padding-top: 15px;
  1714. }
  1715. .messages-header {
  1716. display: flex;
  1717. justify-content: space-between;
  1718. align-items: center;
  1719. margin-bottom: 10px;
  1720. }
  1721. .messages-title {
  1722. font-size: 14px;
  1723. font-weight: bold;
  1724. color: #333;
  1725. }
  1726. .clear-btn {
  1727. padding: 4px 8px;
  1728. background-color: #f44336;
  1729. color: white;
  1730. border: none;
  1731. border-radius: 4px;
  1732. font-size: 10px;
  1733. }
  1734. .messages-list {
  1735. max-height: 200px;
  1736. border: 1px solid #e0e0e0;
  1737. border-radius: 6px;
  1738. padding: 8px;
  1739. background-color: white;
  1740. }
  1741. .message-item {
  1742. margin-bottom: 8px;
  1743. padding: 8px;
  1744. border-radius: 6px;
  1745. border-left: 3px solid #ccc;
  1746. }
  1747. .message-item.sent {
  1748. background-color: #e3f2fd;
  1749. border-left-color: #2196f3;
  1750. }
  1751. .message-item.received {
  1752. background-color: #f1f8e9;
  1753. border-left-color: #4caf50;
  1754. }
  1755. .message-info {
  1756. display: flex;
  1757. justify-content: space-between;
  1758. margin-bottom: 4px;
  1759. }
  1760. .message-direction {
  1761. font-size: 10px;
  1762. font-weight: bold;
  1763. color: #666;
  1764. }
  1765. .message-time {
  1766. font-size: 10px;
  1767. color: #999;
  1768. }
  1769. .message-content {
  1770. font-size: 12px;
  1771. color: #333;
  1772. word-break: break-all;
  1773. }
  1774. /* 我的自选TCP控制样式 */
  1775. .my-stocks-tcp-control {
  1776. display: flex;
  1777. align-items: center;
  1778. justify-content: space-between;
  1779. margin-top: 8px;
  1780. padding: 8px 12px;
  1781. background-color: #f8f9fa;
  1782. border-radius: 8px;
  1783. border: 1px solid #e9ecef;
  1784. }
  1785. .tcp-buttons {
  1786. display: flex;
  1787. gap: 6px;
  1788. }
  1789. .my-stocks-tcp-control .tcp-btn {
  1790. flex: none;
  1791. min-width: 50px;
  1792. height: 28px;
  1793. border-radius: 4px;
  1794. font-size: 11px;
  1795. border: none;
  1796. color: white;
  1797. font-weight: bold;
  1798. }
  1799. </style>