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.

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