rank.js 19 KB

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