rank.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. "use strict";
  2. const common_vendor = require("../../common/vendor.js");
  3. const utils_auth = require("../../utils/auth.js");
  4. const utils_api = require("../../utils/api.js");
  5. const _sfc_main = {
  6. __name: "rank",
  7. setup(__props) {
  8. const isLoggedIn = common_vendor.ref(false);
  9. const myStocks = common_vendor.ref([]);
  10. const viewMode = common_vendor.ref("list");
  11. const isLoading = common_vendor.ref(false);
  12. const lastLoadTime = common_vendor.ref(0);
  13. const CACHE_DURATION = 5e3;
  14. const isPageVisible = common_vendor.ref(false);
  15. const getRandomInterval = () => 2e3 + Math.random() * 1e3;
  16. const SLIDE_WIDTH = 100;
  17. const slideStates = common_vendor.reactive({});
  18. let slideTimers = {};
  19. const AUTO_RESET_DELAY = 2e3;
  20. const initSlideState = (code) => {
  21. if (!slideStates[code]) {
  22. slideStates[code] = { x: 0, currentX: 0 };
  23. }
  24. };
  25. const handleSlideChange = (e, code) => {
  26. initSlideState(code);
  27. slideStates[code].currentX = e.detail.x;
  28. };
  29. const handleSlideEnd = (code) => {
  30. initSlideState(code);
  31. const state = slideStates[code];
  32. if (state.currentX < -20) {
  33. state.x = -SLIDE_WIDTH;
  34. startAutoResetTimer(code);
  35. } else {
  36. resetSlide(code);
  37. }
  38. };
  39. const resetSlide = (code) => {
  40. if (slideStates[code]) {
  41. slideStates[code].x = 0;
  42. slideStates[code].currentX = 0;
  43. }
  44. clearSlideTimer(code);
  45. };
  46. const startAutoResetTimer = (code) => {
  47. clearSlideTimer(code);
  48. slideTimers[code] = setTimeout(() => {
  49. resetSlide(code);
  50. }, AUTO_RESET_DELAY);
  51. };
  52. const clearSlideTimer = (code) => {
  53. if (slideTimers[code]) {
  54. clearTimeout(slideTimers[code]);
  55. delete slideTimers[code];
  56. }
  57. };
  58. const clearAllSlideTimers = () => {
  59. Object.keys(slideTimers).forEach((code) => {
  60. clearSlideTimer(code);
  61. });
  62. };
  63. const setViewMode = (mode) => {
  64. viewMode.value = mode;
  65. if (mode === "list" && myStocks.value.length > 0) {
  66. common_vendor.nextTick$1(() => {
  67. clearAllCanvases();
  68. drawAllTrendCharts();
  69. });
  70. }
  71. };
  72. const indexData = common_vendor.ref({
  73. stockCode: "000001",
  74. stockName: "上证指数",
  75. currentPrice: null,
  76. priceChange: null,
  77. changePercent: null
  78. });
  79. let priceRefreshTimer = null;
  80. let trendRefreshTimer = null;
  81. const fetchIndexData = async () => {
  82. try {
  83. const res = await utils_api.getIndexQuote("000001");
  84. if (res.code === 200 && res.data) {
  85. indexData.value = { ...indexData.value, ...res.data };
  86. }
  87. } catch (e) {
  88. console.error("[上证指数] 获取失败:", e.message);
  89. }
  90. };
  91. const formatIndexPrice = (price) => {
  92. if (!price)
  93. return "--";
  94. return parseFloat(price).toFixed(2);
  95. };
  96. const formatPrice = (price) => {
  97. if (!price)
  98. return "--";
  99. return parseFloat(price).toFixed(2);
  100. };
  101. const getIndexChangeClass = (changePercent) => {
  102. if (!changePercent)
  103. return "";
  104. const str = String(changePercent).replace("%", "").replace("+", "");
  105. const value = parseFloat(str);
  106. if (value > 0)
  107. return "index-up";
  108. if (value < 0)
  109. return "index-down";
  110. return "";
  111. };
  112. const getProfitClass = (profitPercent) => {
  113. if (!profitPercent)
  114. return "";
  115. const str = String(profitPercent).replace("%", "").replace("+", "");
  116. const value = parseFloat(str);
  117. if (value > 0)
  118. return "profit-up";
  119. if (value < 0)
  120. return "profit-down";
  121. return "";
  122. };
  123. const getMarketTag = (code) => {
  124. if (code.startsWith("6"))
  125. return "沪";
  126. if (code.startsWith("0"))
  127. return "深";
  128. if (code.startsWith("3"))
  129. return "创";
  130. return "沪";
  131. };
  132. const getMarketClass = (code) => {
  133. if (code.startsWith("6"))
  134. return "market-sh";
  135. if (code.startsWith("0"))
  136. return "market-sz";
  137. if (code.startsWith("3"))
  138. return "market-cy";
  139. return "market-sh";
  140. };
  141. const getDevicePixelRatio = () => {
  142. try {
  143. const windowInfo = common_vendor.wx$1.getWindowInfo();
  144. return windowInfo.pixelRatio || 2;
  145. } catch (e) {
  146. return 2;
  147. }
  148. };
  149. const clearCanvas = (canvasId) => {
  150. const query = common_vendor.index.createSelectorQuery();
  151. query.select("#" + canvasId).fields({ node: true, size: true }).exec((res) => {
  152. if (!res || !res[0] || !res[0].node)
  153. return;
  154. const canvas = res[0].node;
  155. const ctx = canvas.getContext("2d");
  156. const dpr = getDevicePixelRatio();
  157. const width = res[0].width;
  158. const height = res[0].height;
  159. canvas.width = width * dpr;
  160. canvas.height = height * dpr;
  161. ctx.setTransform(1, 0, 0, 1, 0, 0);
  162. ctx.clearRect(0, 0, width * dpr, height * dpr);
  163. });
  164. };
  165. const clearAllCanvases = () => {
  166. myStocks.value.forEach((stock) => {
  167. clearCanvas("chart-" + stock.code);
  168. });
  169. };
  170. const drawTrendChart = (stock) => {
  171. const canvasId = "chart-" + stock.code;
  172. let trendData = stock.trendData;
  173. if (!trendData || !Array.isArray(trendData) || trendData.length === 0) {
  174. trendData = generateMockTrendData(stock.changePercent);
  175. }
  176. const query = common_vendor.index.createSelectorQuery();
  177. query.select("#" + canvasId).fields({ node: true, size: true }).exec((res) => {
  178. if (!res || !res[0] || !res[0].node) {
  179. console.warn("[趋势图] 获取canvas节点失败:", canvasId);
  180. return;
  181. }
  182. const canvas = res[0].node;
  183. const ctx = canvas.getContext("2d");
  184. const dpr = getDevicePixelRatio();
  185. const width = res[0].width;
  186. const height = res[0].height;
  187. canvas.width = width * dpr;
  188. canvas.height = height * dpr;
  189. ctx.setTransform(1, 0, 0, 1, 0, 0);
  190. ctx.scale(dpr, dpr);
  191. const padding = 1;
  192. const maxValue = Math.max(...trendData);
  193. const minValue = Math.min(...trendData);
  194. const dataRange = maxValue - minValue;
  195. const avgValue = (maxValue + minValue) / 2;
  196. const minRange = avgValue * 0.03 || 1;
  197. const range = Math.max(dataRange, minRange);
  198. const baseValue = trendData[0];
  199. const baseY = height - padding - (baseValue - minValue) / range * (height - padding * 2);
  200. const changePercent = parseFloat(String(stock.changePercent || "0").replace("%", "").replace("+", ""));
  201. const isUp = changePercent >= 0;
  202. const lineColor = isUp ? "#ef4444" : "#22c55e";
  203. const fillColor = isUp ? "rgba(239, 68, 68, 0.15)" : "rgba(34, 197, 94, 0.15)";
  204. ctx.clearRect(0, 0, width, height);
  205. ctx.beginPath();
  206. ctx.strokeStyle = "#e5e7eb";
  207. ctx.lineWidth = 0.5;
  208. ctx.setLineDash([2, 2]);
  209. ctx.moveTo(padding, baseY);
  210. ctx.lineTo(width - padding, baseY);
  211. ctx.stroke();
  212. ctx.setLineDash([]);
  213. ctx.beginPath();
  214. ctx.moveTo(padding, baseY);
  215. trendData.forEach((value, index) => {
  216. const x = padding + index / (trendData.length - 1) * (width - padding * 2);
  217. const y = height - padding - (value - minValue) / range * (height - padding * 2);
  218. ctx.lineTo(x, y);
  219. });
  220. ctx.lineTo(width - padding, baseY);
  221. ctx.closePath();
  222. ctx.fillStyle = fillColor;
  223. ctx.fill();
  224. ctx.beginPath();
  225. trendData.forEach((value, index) => {
  226. const x = padding + index / (trendData.length - 1) * (width - padding * 2);
  227. const y = height - padding - (value - minValue) / range * (height - padding * 2);
  228. if (index === 0) {
  229. ctx.moveTo(x, y);
  230. } else {
  231. ctx.lineTo(x, y);
  232. }
  233. });
  234. ctx.strokeStyle = lineColor;
  235. ctx.lineWidth = 1.5;
  236. ctx.stroke();
  237. });
  238. };
  239. const generateMockTrendData = (changePercent) => {
  240. const change = parseFloat(String(changePercent || "0").replace("%", "").replace("+", ""));
  241. const points = 15;
  242. const data = [];
  243. let baseValue = 100;
  244. const trend = change / 100;
  245. for (let i = 0; i < points; i++) {
  246. const randomChange = (Math.random() - 0.5) * 6;
  247. const trendChange = i / points * trend * 100;
  248. baseValue = baseValue + randomChange + trendChange / points;
  249. data.push(baseValue);
  250. }
  251. return data;
  252. };
  253. const drawAllTrendCharts = () => {
  254. if (myStocks.value.length === 0)
  255. return;
  256. if (!isPageVisible.value)
  257. return;
  258. common_vendor.nextTick$1(() => {
  259. setTimeout(() => {
  260. if (!isPageVisible.value)
  261. return;
  262. myStocks.value.forEach((stock, index) => {
  263. setTimeout(() => {
  264. if (isPageVisible.value) {
  265. drawTrendChart(stock);
  266. }
  267. }, index * 30);
  268. });
  269. }, 350);
  270. });
  271. };
  272. const loadMyStocks = async (forceRefresh = false) => {
  273. console.log("[我的股票] loadMyStocks 开始执行, isLoggedIn=", isLoggedIn.value, "forceRefresh=", forceRefresh);
  274. if (!isLoggedIn.value) {
  275. myStocks.value = [];
  276. stopAutoRefresh();
  277. return;
  278. }
  279. if (isLoading.value) {
  280. console.log("[我的股票] 正在加载中,跳过");
  281. return;
  282. }
  283. const now = Date.now();
  284. if (!forceRefresh && myStocks.value.length > 0 && now - lastLoadTime.value < CACHE_DURATION) {
  285. console.log("[我的股票] 使用缓存数据,只刷新行情");
  286. await fetchIndexData();
  287. await refreshAllQuotes();
  288. drawAllTrendCharts();
  289. startAutoRefresh();
  290. return;
  291. }
  292. try {
  293. isLoading.value = true;
  294. let showedLoading = false;
  295. if (myStocks.value.length === 0 || forceRefresh) {
  296. common_vendor.index.showLoading({ title: "加载中..." });
  297. showedLoading = true;
  298. }
  299. console.log("[我的股票] 调用 getUserStocks 接口");
  300. const res = await utils_api.getUserStocks();
  301. console.log("[我的股票] 服务器返回:", JSON.stringify(res));
  302. if (showedLoading) {
  303. common_vendor.index.hideLoading();
  304. }
  305. if (res.code === 200 && res.data) {
  306. myStocks.value = res.data.map((item) => ({
  307. code: item.stockCode,
  308. name: item.stockName,
  309. addPrice: item.addPrice,
  310. addDate: item.addDate,
  311. currentPrice: item.currentPrice,
  312. profitPercent: item.profitPercent,
  313. priceChange: item.priceChange,
  314. changePercent: item.changePercent,
  315. trendData: item.trendData
  316. }));
  317. lastLoadTime.value = Date.now();
  318. console.log("[我的股票] 加载完成, 股票数量:", myStocks.value.length);
  319. } else {
  320. myStocks.value = [];
  321. console.log("[我的股票] 返回数据为空");
  322. }
  323. await fetchIndexData();
  324. if (myStocks.value.length > 0) {
  325. await refreshAllQuotes();
  326. drawAllTrendCharts();
  327. }
  328. startAutoRefresh();
  329. } catch (e) {
  330. try {
  331. common_vendor.index.hideLoading();
  332. } catch (err) {
  333. }
  334. console.error("[我的股票] 加载失败:", e);
  335. if (myStocks.value.length === 0) {
  336. myStocks.value = [];
  337. }
  338. startAutoRefresh();
  339. } finally {
  340. isLoading.value = false;
  341. }
  342. };
  343. const refreshPriceOnly = async () => {
  344. if (myStocks.value.length === 0)
  345. return;
  346. try {
  347. const codes = myStocks.value.map((stock) => stock.code).join(",");
  348. const quoteRes = await utils_api.getStockQuotes(codes);
  349. if (quoteRes.code === 200 && quoteRes.data && quoteRes.data.length > 0) {
  350. quoteRes.data.forEach((quoteData) => {
  351. const index = myStocks.value.findIndex((stock) => stock.code === quoteData.stockCode);
  352. if (index !== -1) {
  353. const stock = myStocks.value[index];
  354. stock.priceChange = quoteData.priceChange;
  355. stock.changePercent = quoteData.changePercent;
  356. stock.currentPrice = quoteData.currentPrice;
  357. stock.name = quoteData.stockName || stock.name;
  358. if (stock.addPrice && quoteData.currentPrice) {
  359. const addPrice = parseFloat(stock.addPrice);
  360. const currentPrice = parseFloat(quoteData.currentPrice);
  361. if (addPrice > 0) {
  362. const profit = ((currentPrice - addPrice) / addPrice * 100).toFixed(2);
  363. stock.profitPercent = profit >= 0 ? `+${profit}%` : `${profit}%`;
  364. }
  365. }
  366. }
  367. });
  368. }
  369. } catch (e) {
  370. console.error("[我的股票] 价格刷新异常:", e.message);
  371. }
  372. };
  373. const refreshAllQuotes = async () => {
  374. if (myStocks.value.length === 0)
  375. return;
  376. try {
  377. const codes = myStocks.value.map((stock) => stock.code).join(",");
  378. const quoteRes = await utils_api.getStockQuotes(codes);
  379. if (quoteRes.code === 200 && quoteRes.data && quoteRes.data.length > 0) {
  380. quoteRes.data.forEach((quoteData) => {
  381. const index = myStocks.value.findIndex((stock) => stock.code === quoteData.stockCode);
  382. if (index !== -1) {
  383. const stock = myStocks.value[index];
  384. stock.priceChange = quoteData.priceChange;
  385. stock.changePercent = quoteData.changePercent;
  386. stock.currentPrice = quoteData.currentPrice;
  387. stock.name = quoteData.stockName || stock.name;
  388. stock.trendData = quoteData.trendData || null;
  389. if (stock.addPrice && quoteData.currentPrice) {
  390. const addPrice = parseFloat(stock.addPrice);
  391. const currentPrice = parseFloat(quoteData.currentPrice);
  392. if (addPrice > 0) {
  393. const profit = ((currentPrice - addPrice) / addPrice * 100).toFixed(2);
  394. stock.profitPercent = profit >= 0 ? `+${profit}%` : `${profit}%`;
  395. }
  396. }
  397. }
  398. });
  399. }
  400. } catch (e) {
  401. console.error("[我的股票] 刷新异常:", e.message);
  402. }
  403. };
  404. const startAutoRefresh = () => {
  405. if (!isLoggedIn.value || !isPageVisible.value)
  406. return;
  407. stopAutoRefresh();
  408. const schedulePriceRefresh = () => {
  409. if (!isPageVisible.value) {
  410. stopAutoRefresh();
  411. return;
  412. }
  413. priceRefreshTimer = setTimeout(async () => {
  414. if (!isPageVisible.value) {
  415. stopAutoRefresh();
  416. return;
  417. }
  418. await fetchIndexData();
  419. if (myStocks.value.length > 0) {
  420. await refreshPriceOnly();
  421. }
  422. schedulePriceRefresh();
  423. }, getRandomInterval());
  424. };
  425. const scheduleTrendRefresh = () => {
  426. if (!isPageVisible.value) {
  427. stopAutoRefresh();
  428. return;
  429. }
  430. trendRefreshTimer = setTimeout(async () => {
  431. if (!isPageVisible.value) {
  432. stopAutoRefresh();
  433. return;
  434. }
  435. if (myStocks.value.length > 0) {
  436. await refreshAllQuotes();
  437. drawAllTrendCharts();
  438. }
  439. scheduleTrendRefresh();
  440. }, 1e4);
  441. };
  442. schedulePriceRefresh();
  443. scheduleTrendRefresh();
  444. };
  445. const stopAutoRefresh = () => {
  446. if (priceRefreshTimer) {
  447. clearTimeout(priceRefreshTimer);
  448. priceRefreshTimer = null;
  449. }
  450. if (trendRefreshTimer) {
  451. clearTimeout(trendRefreshTimer);
  452. trendRefreshTimer = null;
  453. }
  454. };
  455. const goToLogin = () => {
  456. common_vendor.index.navigateTo({ url: "/pages/login/login" });
  457. };
  458. const removeStock = async (idx) => {
  459. const stock = myStocks.value[idx];
  460. resetSlide(stock.code);
  461. common_vendor.index.showModal({
  462. title: "确认删除",
  463. content: `确定要删除 ${stock.name} 吗?`,
  464. confirmText: "删除",
  465. cancelText: "取消",
  466. success: async (res) => {
  467. if (res.confirm) {
  468. try {
  469. await utils_api.deleteUserStock(stock.code);
  470. delete slideStates[stock.code];
  471. clearSlideTimer(stock.code);
  472. myStocks.value.splice(idx, 1);
  473. common_vendor.index.showToast({ title: "删除成功", icon: "success" });
  474. if (myStocks.value.length === 0) {
  475. stopAutoRefresh();
  476. }
  477. } catch (e) {
  478. console.error("删除失败:", e);
  479. common_vendor.index.showToast({ title: "删除失败", icon: "none" });
  480. }
  481. }
  482. }
  483. });
  484. };
  485. common_vendor.onLoad(() => {
  486. console.log("[我的股票] onLoad 触发");
  487. isLoggedIn.value = utils_auth.isLoggedIn();
  488. isPageVisible.value = true;
  489. loadMyStocks(true);
  490. });
  491. common_vendor.onShow(() => {
  492. console.log("[我的股票] onShow 触发");
  493. isPageVisible.value = true;
  494. if (myStocks.value.length > 0) {
  495. clearAllCanvases();
  496. }
  497. const wasLoggedIn = isLoggedIn.value;
  498. isLoggedIn.value = utils_auth.isLoggedIn();
  499. if (wasLoggedIn !== isLoggedIn.value) {
  500. loadMyStocks(true);
  501. } else {
  502. loadMyStocks(false);
  503. }
  504. common_vendor.index.setNavigationBarTitle({ title: "量化交易大师" });
  505. });
  506. common_vendor.onHide(() => {
  507. console.log("[我的股票] onHide 触发");
  508. isPageVisible.value = false;
  509. stopAutoRefresh();
  510. });
  511. common_vendor.onUnload(() => {
  512. console.log("[我的股票] onUnload 触发");
  513. isPageVisible.value = false;
  514. stopAutoRefresh();
  515. clearAllSlideTimers();
  516. });
  517. return (_ctx, _cache) => {
  518. return common_vendor.e({
  519. a: common_vendor.t(formatIndexPrice(indexData.value.currentPrice)),
  520. b: common_vendor.n(getIndexChangeClass(indexData.value.changePercent)),
  521. c: common_vendor.t(indexData.value.priceChange || "--"),
  522. d: common_vendor.n(getIndexChangeClass(indexData.value.changePercent)),
  523. e: common_vendor.t(indexData.value.stockName || "上证指数"),
  524. f: common_vendor.t(indexData.value.changePercent || "--"),
  525. g: common_vendor.n(getIndexChangeClass(indexData.value.changePercent)),
  526. h: viewMode.value === "table" ? 1 : "",
  527. i: viewMode.value === "list" ? 1 : "",
  528. j: common_vendor.o(($event) => setViewMode("list")),
  529. k: viewMode.value === "table" ? 1 : "",
  530. l: common_vendor.o(($event) => setViewMode("table")),
  531. m: common_vendor.t(myStocks.value.length),
  532. n: common_vendor.f(myStocks.value, (stock, index, i0) => {
  533. var _a;
  534. return {
  535. a: common_vendor.t(stock.name),
  536. b: common_vendor.t(getMarketTag(stock.code)),
  537. c: common_vendor.n(getMarketClass(stock.code)),
  538. d: common_vendor.t(stock.code),
  539. e: "chart-" + stock.code,
  540. f: common_vendor.t(stock.currentPrice || "-"),
  541. g: common_vendor.t(stock.changePercent || "-"),
  542. h: common_vendor.n(getProfitClass(stock.changePercent)),
  543. i: common_vendor.o(($event) => removeStock(index), stock.code),
  544. j: ((_a = slideStates[stock.code]) == null ? void 0 : _a.x) || 0,
  545. k: common_vendor.o((e) => handleSlideChange(e, stock.code), stock.code),
  546. l: common_vendor.o(() => handleSlideEnd(stock.code), stock.code),
  547. m: stock.code
  548. };
  549. }),
  550. o: viewMode.value === "list",
  551. p: myStocks.value.length === 0 ? 1 : "",
  552. q: common_vendor.f(myStocks.value, (stock, index, i0) => {
  553. return {
  554. a: common_vendor.t(stock.name),
  555. b: common_vendor.t(getMarketTag(stock.code)),
  556. c: common_vendor.n(getMarketClass(stock.code)),
  557. d: common_vendor.t(stock.code),
  558. e: common_vendor.t(stock.addDate || "--"),
  559. f: common_vendor.t(formatPrice(stock.addPrice)),
  560. g: common_vendor.t(stock.profitPercent || "--"),
  561. h: common_vendor.n(getProfitClass(stock.profitPercent)),
  562. i: stock.code
  563. };
  564. }),
  565. r: viewMode.value === "table",
  566. s: myStocks.value.length === 0 ? 1 : "",
  567. t: myStocks.value.length === 0
  568. }, myStocks.value.length === 0 ? {} : {}, {
  569. v: !isLoggedIn.value ? 1 : "",
  570. w: !isLoggedIn.value
  571. }, !isLoggedIn.value ? {
  572. x: common_vendor.o(goToLogin)
  573. } : {});
  574. };
  575. }
  576. };
  577. const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__file", "D:/program/gupiao-wx/src/pages/rank/rank.vue"]]);
  578. wx.createPage(MiniProgramPage);