rank.js 16 KB

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