TrendChart.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <template>
  2. <view class="trend-chart-wrap" :style="{ '--font-scale': fontScale }">
  3. <!-- 参考范围背景带说明(refLow/refHigh 均存在时显示) -->
  4. <view class="ref-band-hint" v-if="hasRefBand">
  5. <text class="ref-band-label">参考范围 {{ refLow }}–{{ refHigh }} {{ refUnit || '' }}</text>
  6. </view>
  7. <view class="trend-container" :style="containerStyle">
  8. <canvas :id="canvasId" type="2d" class="trend-canvas" :style="canvasStyle"></canvas>
  9. <view class="trend-tap-layer" @click="onCanvasTap"></view>
  10. </view>
  11. <view class="trend-legend" v-if="series.length > 1 && mode !== 'pair'">
  12. <view class="legend-item" v-for="(s, i) in series" :key="getItemKey(s, i)">
  13. <view class="legend-line" :style="'border-color:' + s.color"></view>
  14. <text class="legend-text">{{ s.name }}</text>
  15. </view>
  16. </view>
  17. </view>
  18. </template>
  19. <script>
  20. import { BrandColors } from '../../../utils/brand-colors.js'
  21. import { chartRenderConfig } from '@/utils/indicator-change.js'
  22. import { axisLabelIndices, normalizeDate, dateWithSourceMark, unitMismatchMark } from '@/utils/indicator-timeline.js'
  23. /**
  24. * TrendChart - 多序列折线图 Canvas 组件(改造版)
  25. * 用法:<TrendChart :series="[{name,color,points:[{reportDate,value,unit,dateSource}]}]"
  26. * :mode="mode" :refLow="refLow" :refHigh="refHigh" :allPeriodDates="allPeriodDates" :showAxisLabels="true"
  27. * @pointTap="onPointTap" />
  28. * 新增 props:mode / refLow / refHigh / allPeriodDates / showAxisLabels;新增 emit pointTap
  29. * 渲染规则(design §6.2):
  30. * 参考范围背景带:refLow/refHigh 非 null 时画浅色横条 + 上下界虚线,Y 轴范围必须包含边界
  31. * 缺失期断线:遍历 allPeriodDates,当前日期在 points 中无对应点 → 不 lineTo,下一个有效点 moveTo 重新起笔
  32. * 上传日标记:dateSource 非 real/unknown 的点,日期标签后加 *
  33. * 单位不一致标记:点的 unit !== latest.unit → 值标签后加 *
  34. * X 轴抽稀:按 axisLabelIndices(allPeriodDates.length) 决定
  35. */
  36. import fontScaleMixin from '@/mixins/font-scale.js'
  37. export default {
  38. mixins: [fontScaleMixin],
  39. props: {
  40. /** 序列数组 [{ name, color, points:[{reportDate,value,unit,dateSource}] }] */
  41. series: { type: Array, default: function() { return [] } },
  42. /** 'line' 折线 | 'spark' 迷你 | 'compare' 双期对比条(由 IndicatorChangeRow 承担) */
  43. mode: { type: String, default: 'line' },
  44. /** 参考范围下界,非 null 时画浅色横条背景带 */
  45. refLow: { type: Number, default: null },
  46. /** 参考范围上界,非 null 时画浅色横条背景带 */
  47. refHigh: { type: Number, default: null },
  48. /** X 轴日期全集(含缺失期),用于等距布局与断线。不传则从 series 推导 */
  49. allPeriodDates: { type: Array, default: function() { return [] } },
  50. /** n ≤ 8 时每点标值;n ≥ 9 默认关闭(由 chartRenderConfig 综合决定,此处仅做兜底) */
  51. showValues: { type: Boolean, default: true },
  52. /** X 轴日期标签,抽稀由组件内部按 allPeriodDates.length 决定 */
  53. showAxisLabels: { type: Boolean, default: true },
  54. width: { type: Number, default: 690 },
  55. height: { type: Number, default: 420 },
  56. /** 最新一期单位,用于单位不一致 * 标记 */
  57. latestUnit: { type: String, default: '' }
  58. },
  59. data: function() {
  60. return {
  61. canvasReady: false, canvasWidth: 0, canvasHeight: 0, ctx: null, dpr: 1,
  62. _canvasNode: null, _canvasLeft: 0, _canvasTop: 0,
  63. _destroyed: false, _initTimer: null,
  64. canvasId: 'trendCanvas_' + (this._uid || 0)
  65. }
  66. },
  67. computed: {
  68. containerStyle: function() { return 'width:' + this.width + 'rpx;height:' + this.height + 'rpx' },
  69. canvasStyle: function() { return 'width:' + this.width + 'rpx;height:' + this.height + 'rpx' },
  70. hasRefBand: function() {
  71. return this.refLow !== null && this.refLow !== undefined &&
  72. this.refHigh !== null && this.refHigh !== undefined
  73. },
  74. refUnit: function() { return this.latestUnit || '' },
  75. /**
  76. * 有效 chartMode:mode 允许直接传后端 chartMode('empty'|'single'|'pair'|'line'|'line_aggregated'),
  77. * 也允许传语义值('compare' → 'pair',其余按 'line' 处理)。
  78. */
  79. effectiveChartMode: function() {
  80. var m = this.mode
  81. if (m === 'empty' || m === 'single' || m === 'pair' || m === 'line' || m === 'line_aggregated') return m
  82. if (m === 'compare') return 'pair'
  83. return 'line'
  84. },
  85. /** 图表形态消费结果(消费后端 chartMode,不自行判断) */
  86. renderConfig: function() {
  87. var n = this._allDatesLength()
  88. var cfg = chartRenderConfig(this.effectiveChartMode, n)
  89. // showValues prop 作为额外开关(false 时强制不标值)
  90. if (!this.showValues) cfg.showValues = false
  91. return cfg
  92. }
  93. },
  94. watch: {
  95. series: { handler: function() { if (this.canvasReady) this._doRender() }, deep: true }
  96. },
  97. mounted: function() {
  98. var self = this
  99. var retryCount = 0
  100. var maxRetry = 5
  101. function tryInit() {
  102. if (self._destroyed) return
  103. self.initCanvas(function(success) {
  104. if (self._destroyed) return
  105. if (!success && retryCount < maxRetry) {
  106. retryCount++
  107. self._initTimer = setTimeout(tryInit, 60)
  108. } else if (!success) {
  109. console.log('[TrendChart] 初始化失败,重试 ' + maxRetry + ' 次后放弃', self.canvasId)
  110. }
  111. })
  112. }
  113. self._initTimer = setTimeout(tryInit, 100)
  114. },
  115. beforeDestroy: function() {
  116. this._destroyed = true
  117. if (this._initTimer) { clearTimeout(this._initTimer); this._initTimer = null }
  118. },
  119. methods: {
  120. getItemKey: function(s, i) { return (s && s.name) || i },
  121. /** 当前参与 X 轴布局的日期总数(优先 allPeriodDates,否则从 series 推导) */
  122. _allDatesLength: function() {
  123. var dates = this.allPeriodDates
  124. if (Array.isArray(dates) && dates.length > 0) return dates.length
  125. var set = {}
  126. var s
  127. for (var i = 0; i < this.series.length; i++) {
  128. s = this.series[i]
  129. if (!s || !Array.isArray(s.points)) continue
  130. for (var j = 0; j < s.points.length; j++) {
  131. var d = s.points[j] && s.points[j].reportDate
  132. if (d) set[d] = true
  133. }
  134. }
  135. return Object.keys(set).length
  136. },
  137. initCanvas: function(cb) {
  138. var self = this
  139. uni.createSelectorQuery().in(this)
  140. .select('#' + this.canvasId)
  141. .fields({ node: true, size: true, rect: true })
  142. .exec(function(res) {
  143. try {
  144. if (self._destroyed) return
  145. if (!res || !res[0] || !res[0].node) { if (cb) cb(false); return }
  146. var info = res[0]
  147. var canvas = info.node
  148. var width = info.width
  149. var height = info.height
  150. if (!width || !height) {
  151. var winWidth = 375
  152. try { winWidth = uni.getWindowInfo().windowWidth || 375 } catch (e) {}
  153. width = Math.round((self.width || 690) * winWidth / 750)
  154. height = Math.round((self.height || 420) * winWidth / 750)
  155. }
  156. var pixelRatio = 2
  157. try { pixelRatio = uni.getWindowInfo().pixelRatio || 2 } catch (e) {}
  158. canvas.width = width * pixelRatio
  159. canvas.height = height * pixelRatio
  160. var ctx = canvas.getContext('2d')
  161. if (!ctx) { if (cb) cb(false); return }
  162. ctx.scale(pixelRatio, pixelRatio)
  163. self.ctx = ctx
  164. self._canvasNode = canvas
  165. self.canvasWidth = width
  166. self.canvasHeight = height
  167. self.dpr = pixelRatio
  168. self._canvasLeft = info.left || 0
  169. self._canvasTop = info.top || 0
  170. self.canvasReady = true
  171. self._doRender()
  172. if (cb) cb(true)
  173. } catch (e) {
  174. console.log('[TrendChart] initCanvas 回调异常', e)
  175. if (cb) cb(false)
  176. }
  177. })
  178. },
  179. _safeSeries: function(arr) {
  180. if (!Array.isArray(arr)) return []
  181. return arr.filter(function(s) { return s && Array.isArray(s.points) && s.points.length > 0 })
  182. },
  183. /** 计算 X 轴日期全集(含缺失期)与 Y 轴数值范围(Y 范围必须包含 refLow/refHigh) */
  184. _computeRanges: function(seriesList) {
  185. var min = Infinity, max = -Infinity
  186. seriesList.forEach(function(s) {
  187. s.points.forEach(function(p) {
  188. var v = parseFloat(p.value)
  189. if (!isNaN(v)) { if (v < min) min = v; if (v > max) max = v }
  190. })
  191. })
  192. // 参考范围必须纳入 Y 轴范围,否则背景带跑到图外
  193. if (this.hasRefBand) {
  194. if (this.refLow < min) min = this.refLow
  195. if (this.refHigh > max) max = this.refHigh
  196. }
  197. if (min === Infinity) { min = 0; max = 1 }
  198. if (max === min) { max = min + 1 }
  199. var pad = (max - min) * 0.08
  200. return { yMin: Math.max(0, min - pad), yMax: max + pad }
  201. },
  202. /**
  203. * 构建画布布局:X 轴日期全集(含缺失期)、Y 轴数值范围、绘图区尺寸、坐标映射。
  204. * 结果同时挂到 this._layout,供 onCanvasTap(点选最近数据点)复用。
  205. * 约定(design §6.2):Y 轴范围必须包含 refLow/refHigh(_computeRanges 已处理)。
  206. */
  207. _buildLayout: function() {
  208. var w = this.canvasWidth || this.width || 690
  209. var h = this.canvasHeight || this.height || 420
  210. var padL = 34, padR = 14, padT = 16, padB = 26
  211. var plotW = Math.max(1, w - padL - padR)
  212. var plotH = Math.max(1, h - padT - padB)
  213. // X 轴日期全集:优先 allPeriodDates(含缺失期),否则从 series 推导并排序
  214. var allDates = []
  215. var dates = this.allPeriodDates
  216. if (Array.isArray(dates) && dates.length > 0) {
  217. allDates = dates.slice()
  218. } else {
  219. var set = {}
  220. for (var i = 0; i < this.series.length; i++) {
  221. var s = this.series[i]
  222. if (!s || !Array.isArray(s.points)) continue
  223. for (var j = 0; j < s.points.length; j++) {
  224. var d = s.points[j] && s.points[j].reportDate
  225. if (d) set[d] = true
  226. }
  227. }
  228. allDates = Object.keys(set).sort()
  229. }
  230. var ranges = this._computeRanges(this._safeSeries(this.series))
  231. var yMin = ranges.yMin
  232. var yMax = ranges.yMax
  233. var ySpan = (yMax - yMin) || 1
  234. var layout = {
  235. w: w, h: h,
  236. padL: padL, padR: padR, padT: padT, padB: padB,
  237. plotW: plotW, plotH: plotH,
  238. allDates: allDates,
  239. yMin: yMin, yMax: yMax
  240. }
  241. // 日期 → X 像素(等距布局)
  242. layout.xOf = function(dateStr) {
  243. var idx = allDates.indexOf(dateStr)
  244. if (idx < 0) return padL
  245. if (allDates.length <= 1) return padL + plotW / 2
  246. return padL + plotW * (idx / (allDates.length - 1))
  247. }
  248. // 数值 → Y 像素(Y 轴向上为正)
  249. layout.yOfC = function(v) {
  250. return padT + plotH * (1 - (v - yMin) / ySpan)
  251. }
  252. this._layout = layout
  253. return layout
  254. },
  255. _doRender: function() {
  256. if (!this.ctx) return
  257. var self = this
  258. var ctx = this.ctx
  259. var layout = this._buildLayout()
  260. var w = layout.w, h = layout.h
  261. var padL = layout.padL, padR = layout.padR, padT = layout.padT, padB = layout.padB
  262. var plotW = layout.plotW, plotH = layout.plotH
  263. var seriesList = this._safeSeries(this.series)
  264. var renderCfg = this.renderConfig
  265. var drawLine = renderCfg.draw
  266. var showValues = renderCfg.showValues
  267. var labelMode = renderCfg.labelMode
  268. // X 轴日期全集(含缺失期),用于等距布局
  269. var allDates = layout.allDates
  270. var xOf = layout.xOf
  271. var yOfC = layout.yOfC
  272. var yMin = layout.yMin, yMax = layout.yMax
  273. ctx.clearRect(0, 0, w, h)
  274. // 参考范围背景带(浅色横条 + 上下界虚线)
  275. if (this.hasRefBand && this.refLow !== null && this.refHigh !== null) {
  276. var bandAlpha = 0.10
  277. ctx.fillStyle = 'rgba(234, 88, 12, 0.10)' // 浅橙
  278. var topY = yOfC(this.refHigh)
  279. var botY = yOfC(this.refLow)
  280. ctx.fillRect(padL, topY, plotW, Math.max(1, botY - topY))
  281. // 上下界虚线
  282. ctx.strokeStyle = 'rgba(234, 88, 12, 0.55)'
  283. ctx.lineWidth = 1
  284. ctx.setLineDash ? ctx.setLineDash([4, 4]) : null
  285. ctx.beginPath(); ctx.moveTo(padL, topY); ctx.lineTo(w - padR, topY); ctx.stroke()
  286. ctx.beginPath(); ctx.moveTo(padL, botY); ctx.lineTo(w - padR, botY); ctx.stroke()
  287. ctx.setLineDash ? ctx.setLineDash([]) : null
  288. }
  289. // 网格(4 条横线 + 2 条纵线)
  290. ctx.strokeStyle = BrandColors.slateGhost
  291. ctx.lineWidth = 1
  292. for (var gi = 0; gi <= 3; gi++) {
  293. var gy = padT + plotH * (gi / 3)
  294. ctx.beginPath()
  295. ctx.moveTo(padL, gy); ctx.lineTo(w - padR, gy)
  296. ctx.stroke()
  297. }
  298. // Y 轴刻度文字
  299. ctx.fillStyle = BrandColors.appTextSubtle
  300. ctx.font = '10px sans-serif'
  301. ctx.textAlign = 'right'
  302. for (var ti = 0; ti <= 3; ti++) {
  303. var tv = yMin + (yMax - yMin) * (1 - ti / 3)
  304. var ty = padT + plotH * (ti / 3)
  305. ctx.fillText(self._fmtNum(tv), padL - 4, ty + 3)
  306. }
  307. // 折线 + 数据点 + 数值(缺失期断线:遍历 allPeriodDates,无点处不连线)
  308. var palette = [BrandColors.primary, BrandColors.infoSky, BrandColors.success, BrandColors.primary, BrandColors.danger, BrandColors.wealth]
  309. seriesList.forEach(function(s, si) {
  310. var color = s.color || palette[si % palette.length]
  311. ctx.strokeStyle = color
  312. ctx.lineWidth = 2
  313. if (drawLine) {
  314. ctx.beginPath()
  315. var started = false
  316. allDates.forEach(function(d) {
  317. var pt = null
  318. for (var pi = 0; pi < s.points.length; pi++) {
  319. if (s.points[pi].reportDate === d) { pt = s.points[pi]; break }
  320. }
  321. if (!pt) { started = false; return } // 缺失期:断线,下一个有效点重新起笔
  322. var v = parseFloat(pt.value)
  323. if (isNaN(v)) { started = false; return }
  324. var x = xOf(d), y = yOfC(v)
  325. if (!started) { ctx.moveTo(x, y); started = true } else { ctx.lineTo(x, y) }
  326. })
  327. ctx.stroke()
  328. }
  329. // 数据点 + 值
  330. s.points.forEach(function(p) {
  331. var v = parseFloat(p.value)
  332. if (isNaN(v)) return
  333. var x = xOf(p.reportDate), y = yOfC(v)
  334. ctx.fillStyle = color
  335. ctx.beginPath(); ctx.arc(x, y, 3.5, 0, 2 * Math.PI); ctx.fill()
  336. if (showValues) {
  337. var label = unitMismatchMark(p.value, p.unit, self.latestUnit, p.unitMismatch)
  338. ctx.fillStyle = BrandColors.slate600
  339. ctx.font = '10px sans-serif'
  340. ctx.textAlign = 'center'
  341. ctx.fillText(label, x, y - 8)
  342. }
  343. })
  344. // 序列名(最右端上方)
  345. ctx.fillStyle = color
  346. ctx.font = '11px sans-serif'
  347. ctx.textAlign = 'right'
  348. var last = s.points[s.points.length - 1]
  349. if (last && !isNaN(parseFloat(last.value))) {
  350. ctx.fillText(s.name || '', xOf(last.reportDate), yOfC(parseFloat(last.value)) - 14)
  351. }
  352. })
  353. // X 轴日期标签(抽稀,带 * 标记)
  354. if (showAxisLabels && allDates.length > 0) {
  355. ctx.fillStyle = BrandColors.appTextSubtle
  356. ctx.font = '10px sans-serif'
  357. ctx.textAlign = 'center'
  358. var indices = axisLabelIndices(allDates.length)
  359. indices.forEach(function(idx) {
  360. var d = allDates[idx]
  361. // 找对应点的 dateSource 用于 * 标记
  362. var ds = ''
  363. seriesList.forEach(function(s) {
  364. for (var pi = 0; pi < s.points.length; pi++) {
  365. if (s.points[pi].reportDate === d) { ds = s.points[pi].dateSource || ''; break }
  366. }
  367. })
  368. var label = dateWithSourceMark(normalizeDate(d), ds)
  369. var x = xOf(d)
  370. ctx.fillText(label, x, h - 8)
  371. })
  372. }
  373. },
  374. _fmtNum: function(v) {
  375. if (v >= 100) return Math.round(v) + ''
  376. if (v >= 10) return v.toFixed(1)
  377. return v.toFixed(2)
  378. },
  379. onCanvasTap: function(e) {
  380. if (!this.canvasReady) return
  381. var layout = this._layout
  382. if (!layout) return
  383. // 从事件中取页面坐标(与 RadarChart 同套容错)
  384. var pageX
  385. var pageY
  386. if (e.detail && typeof e.detail.x === 'number') {
  387. pageX = e.detail.x
  388. pageY = e.detail.y
  389. } else if (e.touches && e.touches[0]) {
  390. pageX = e.touches[0].x || e.touches[0].clientX || 0
  391. pageY = e.touches[0].y || e.touches[0].clientY || 0
  392. } else if (e.changedTouches && e.changedTouches[0]) {
  393. pageX = e.changedTouches[0].x || e.changedTouches[0].clientX || 0
  394. pageY = e.changedTouches[0].y || e.changedTouches[0].clientY || 0
  395. } else {
  396. return
  397. }
  398. // 转 canvas 相对坐标
  399. var relX = pageX - (this._canvasLeft || 0)
  400. var relY = pageY - (this._canvasTop || 0)
  401. if (relX < 0 || relY < 0 || relX > this.canvasWidth || relY > this.canvasHeight) return
  402. // 找最近数据点(P2-2 长按读数的基础)
  403. var best = null
  404. var bestDist = Infinity
  405. var hitRadius = 40
  406. for (var si = 0; si < this.series.length; si++) {
  407. var s = this.series[si]
  408. if (!s || !Array.isArray(s.points)) continue
  409. for (var pi = 0; pi < s.points.length; pi++) {
  410. var p = s.points[pi]
  411. if (!p) continue
  412. var v = parseFloat(p.value)
  413. if (isNaN(v)) continue
  414. var x = layout.xOf(p.reportDate)
  415. var y = layout.yOfC(v)
  416. var dx = x - relX
  417. var dy = y - relY
  418. var dist = dx * dx + dy * dy
  419. if (dist < bestDist) {
  420. bestDist = dist
  421. best = { index: pi, point: p, x: x, y: y }
  422. }
  423. }
  424. }
  425. if (best && bestDist <= hitRadius * hitRadius) {
  426. this.$emit('pointTap', { index: best.index, point: best.point, x: best.x, y: best.y })
  427. }
  428. }
  429. }
  430. }
  431. </script>
  432. <style scoped lang="scss">
  433. .trend-chart-wrap {
  434. display: flex;
  435. flex-direction: column;
  436. }
  437. .ref-band-hint {
  438. font-size: calc(16rpx * var(--font-scale, 1));
  439. color: #EA580C;
  440. padding: 0 8rpx 4rpx 8rpx;
  441. }
  442. .ref-band-label {
  443. font-weight: 600;
  444. }
  445. .trend-container {
  446. position: relative;
  447. }
  448. .trend-canvas {
  449. display: block;
  450. }
  451. .trend-tap-layer {
  452. position: absolute;
  453. left: 0;
  454. top: 0;
  455. width: 100%;
  456. height: 100%;
  457. }
  458. .trend-legend {
  459. display: flex;
  460. flex-direction: row;
  461. flex-wrap: wrap;
  462. justify-content: center;
  463. padding-top: 12rpx;
  464. }
  465. .legend-item {
  466. display: flex;
  467. flex-direction: row;
  468. align-items: center;
  469. margin: 0 16rpx 8rpx;
  470. }
  471. .legend-line {
  472. width: 32rpx;
  473. border-top: 4rpx solid $uni-info;
  474. margin-right: 8rpx;
  475. }
  476. .legend-text {
  477. font-size: calc(22rpx * var(--font-scale, 1));
  478. color: $facade-text-slate-deep;
  479. }
  480. </style>