| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501 |
- <template>
- <view class="trend-chart-wrap" :style="{ '--font-scale': fontScale }">
- <!-- 参考范围背景带说明(refLow/refHigh 均存在时显示) -->
- <view class="ref-band-hint" v-if="hasRefBand">
- <text class="ref-band-label">参考范围 {{ refLow }}–{{ refHigh }} {{ refUnit || '' }}</text>
- </view>
- <view class="trend-container" :style="containerStyle">
- <canvas :id="canvasId" type="2d" class="trend-canvas" :style="canvasStyle"></canvas>
- <view class="trend-tap-layer" @click="onCanvasTap"></view>
- </view>
- <view class="trend-legend" v-if="series.length > 1 && mode !== 'pair'">
- <view class="legend-item" v-for="(s, i) in series" :key="getItemKey(s, i)">
- <view class="legend-line" :style="'border-color:' + s.color"></view>
- <text class="legend-text">{{ s.name }}</text>
- </view>
- </view>
- </view>
- </template>
- <script>
- import { BrandColors } from '../../../utils/brand-colors.js'
- import { chartRenderConfig } from '@/utils/indicator-change.js'
- import { axisLabelIndices, normalizeDate, dateWithSourceMark, unitMismatchMark } from '@/utils/indicator-timeline.js'
- /**
- * TrendChart - 多序列折线图 Canvas 组件(改造版)
- * 用法:<TrendChart :series="[{name,color,points:[{reportDate,value,unit,dateSource}]}]"
- * :mode="mode" :refLow="refLow" :refHigh="refHigh" :allPeriodDates="allPeriodDates" :showAxisLabels="true"
- * @pointTap="onPointTap" />
- * 新增 props:mode / refLow / refHigh / allPeriodDates / showAxisLabels;新增 emit pointTap
- * 渲染规则(design §6.2):
- * 参考范围背景带:refLow/refHigh 非 null 时画浅色横条 + 上下界虚线,Y 轴范围必须包含边界
- * 缺失期断线:遍历 allPeriodDates,当前日期在 points 中无对应点 → 不 lineTo,下一个有效点 moveTo 重新起笔
- * 上传日标记:dateSource 非 real/unknown 的点,日期标签后加 *
- * 单位不一致标记:点的 unit !== latest.unit → 值标签后加 *
- * X 轴抽稀:按 axisLabelIndices(allPeriodDates.length) 决定
- */
- import fontScaleMixin from '@/mixins/font-scale.js'
- export default {
- mixins: [fontScaleMixin],
- props: {
- /** 序列数组 [{ name, color, points:[{reportDate,value,unit,dateSource}] }] */
- series: { type: Array, default: function() { return [] } },
- /** 'line' 折线 | 'spark' 迷你 | 'compare' 双期对比条(由 IndicatorChangeRow 承担) */
- mode: { type: String, default: 'line' },
- /** 参考范围下界,非 null 时画浅色横条背景带 */
- refLow: { type: Number, default: null },
- /** 参考范围上界,非 null 时画浅色横条背景带 */
- refHigh: { type: Number, default: null },
- /** X 轴日期全集(含缺失期),用于等距布局与断线。不传则从 series 推导 */
- allPeriodDates: { type: Array, default: function() { return [] } },
- /** n ≤ 8 时每点标值;n ≥ 9 默认关闭(由 chartRenderConfig 综合决定,此处仅做兜底) */
- showValues: { type: Boolean, default: true },
- /** X 轴日期标签,抽稀由组件内部按 allPeriodDates.length 决定 */
- showAxisLabels: { type: Boolean, default: true },
- width: { type: Number, default: 690 },
- height: { type: Number, default: 420 },
- /** 最新一期单位,用于单位不一致 * 标记 */
- latestUnit: { type: String, default: '' }
- },
- data: function() {
- return {
- canvasReady: false, canvasWidth: 0, canvasHeight: 0, ctx: null, dpr: 1,
- _canvasNode: null, _canvasLeft: 0, _canvasTop: 0,
- _destroyed: false, _initTimer: null,
- canvasId: 'trendCanvas_' + (this._uid || 0)
- }
- },
- computed: {
- containerStyle: function() { return 'width:' + this.width + 'rpx;height:' + this.height + 'rpx' },
- canvasStyle: function() { return 'width:' + this.width + 'rpx;height:' + this.height + 'rpx' },
- hasRefBand: function() {
- return this.refLow !== null && this.refLow !== undefined &&
- this.refHigh !== null && this.refHigh !== undefined
- },
- refUnit: function() { return this.latestUnit || '' },
- /**
- * 有效 chartMode:mode 允许直接传后端 chartMode('empty'|'single'|'pair'|'line'|'line_aggregated'),
- * 也允许传语义值('compare' → 'pair',其余按 'line' 处理)。
- */
- effectiveChartMode: function() {
- var m = this.mode
- if (m === 'empty' || m === 'single' || m === 'pair' || m === 'line' || m === 'line_aggregated') return m
- if (m === 'compare') return 'pair'
- return 'line'
- },
- /** 图表形态消费结果(消费后端 chartMode,不自行判断) */
- renderConfig: function() {
- var n = this._allDatesLength()
- var cfg = chartRenderConfig(this.effectiveChartMode, n)
- // showValues prop 作为额外开关(false 时强制不标值)
- if (!this.showValues) cfg.showValues = false
- return cfg
- }
- },
- watch: {
- series: { handler: function() { if (this.canvasReady) this._doRender() }, deep: true }
- },
- mounted: function() {
- var self = this
- var retryCount = 0
- var maxRetry = 5
- function tryInit() {
- if (self._destroyed) return
- self.initCanvas(function(success) {
- if (self._destroyed) return
- if (!success && retryCount < maxRetry) {
- retryCount++
- self._initTimer = setTimeout(tryInit, 60)
- } else if (!success) {
- console.log('[TrendChart] 初始化失败,重试 ' + maxRetry + ' 次后放弃', self.canvasId)
- }
- })
- }
- self._initTimer = setTimeout(tryInit, 100)
- },
- beforeDestroy: function() {
- this._destroyed = true
- if (this._initTimer) { clearTimeout(this._initTimer); this._initTimer = null }
- },
- methods: {
- getItemKey: function(s, i) { return (s && s.name) || i },
- /** 当前参与 X 轴布局的日期总数(优先 allPeriodDates,否则从 series 推导) */
- _allDatesLength: function() {
- var dates = this.allPeriodDates
- if (Array.isArray(dates) && dates.length > 0) return dates.length
- var set = {}
- var s
- for (var i = 0; i < this.series.length; i++) {
- s = this.series[i]
- if (!s || !Array.isArray(s.points)) continue
- for (var j = 0; j < s.points.length; j++) {
- var d = s.points[j] && s.points[j].reportDate
- if (d) set[d] = true
- }
- }
- return Object.keys(set).length
- },
- initCanvas: function(cb) {
- var self = this
- uni.createSelectorQuery().in(this)
- .select('#' + this.canvasId)
- .fields({ node: true, size: true, rect: true })
- .exec(function(res) {
- try {
- if (self._destroyed) return
- if (!res || !res[0] || !res[0].node) { if (cb) cb(false); return }
- var info = res[0]
- var canvas = info.node
- var width = info.width
- var height = info.height
- if (!width || !height) {
- var winWidth = 375
- try { winWidth = uni.getWindowInfo().windowWidth || 375 } catch (e) {}
- width = Math.round((self.width || 690) * winWidth / 750)
- height = Math.round((self.height || 420) * winWidth / 750)
- }
- var pixelRatio = 2
- try { pixelRatio = uni.getWindowInfo().pixelRatio || 2 } catch (e) {}
- canvas.width = width * pixelRatio
- canvas.height = height * pixelRatio
- var ctx = canvas.getContext('2d')
- if (!ctx) { if (cb) cb(false); return }
- ctx.scale(pixelRatio, pixelRatio)
- self.ctx = ctx
- self._canvasNode = canvas
- self.canvasWidth = width
- self.canvasHeight = height
- self.dpr = pixelRatio
- self._canvasLeft = info.left || 0
- self._canvasTop = info.top || 0
- self.canvasReady = true
- self._doRender()
- if (cb) cb(true)
- } catch (e) {
- console.log('[TrendChart] initCanvas 回调异常', e)
- if (cb) cb(false)
- }
- })
- },
- _safeSeries: function(arr) {
- if (!Array.isArray(arr)) return []
- return arr.filter(function(s) { return s && Array.isArray(s.points) && s.points.length > 0 })
- },
- /** 计算 X 轴日期全集(含缺失期)与 Y 轴数值范围(Y 范围必须包含 refLow/refHigh) */
- _computeRanges: function(seriesList) {
- var min = Infinity, max = -Infinity
- seriesList.forEach(function(s) {
- s.points.forEach(function(p) {
- var v = parseFloat(p.value)
- if (!isNaN(v)) { if (v < min) min = v; if (v > max) max = v }
- })
- })
- // 参考范围必须纳入 Y 轴范围,否则背景带跑到图外
- if (this.hasRefBand) {
- if (this.refLow < min) min = this.refLow
- if (this.refHigh > max) max = this.refHigh
- }
- if (min === Infinity) { min = 0; max = 1 }
- if (max === min) { max = min + 1 }
- var pad = (max - min) * 0.08
- return { yMin: Math.max(0, min - pad), yMax: max + pad }
- },
- /**
- * 构建画布布局:X 轴日期全集(含缺失期)、Y 轴数值范围、绘图区尺寸、坐标映射。
- * 结果同时挂到 this._layout,供 onCanvasTap(点选最近数据点)复用。
- * 约定(design §6.2):Y 轴范围必须包含 refLow/refHigh(_computeRanges 已处理)。
- */
- _buildLayout: function() {
- var w = this.canvasWidth || this.width || 690
- var h = this.canvasHeight || this.height || 420
- var padL = 34, padR = 14, padT = 16, padB = 26
- var plotW = Math.max(1, w - padL - padR)
- var plotH = Math.max(1, h - padT - padB)
- // X 轴日期全集:优先 allPeriodDates(含缺失期),否则从 series 推导并排序
- var allDates = []
- var dates = this.allPeriodDates
- if (Array.isArray(dates) && dates.length > 0) {
- allDates = dates.slice()
- } else {
- var set = {}
- for (var i = 0; i < this.series.length; i++) {
- var s = this.series[i]
- if (!s || !Array.isArray(s.points)) continue
- for (var j = 0; j < s.points.length; j++) {
- var d = s.points[j] && s.points[j].reportDate
- if (d) set[d] = true
- }
- }
- allDates = Object.keys(set).sort()
- }
- var ranges = this._computeRanges(this._safeSeries(this.series))
- var yMin = ranges.yMin
- var yMax = ranges.yMax
- var ySpan = (yMax - yMin) || 1
- var layout = {
- w: w, h: h,
- padL: padL, padR: padR, padT: padT, padB: padB,
- plotW: plotW, plotH: plotH,
- allDates: allDates,
- yMin: yMin, yMax: yMax
- }
- // 日期 → X 像素(等距布局)
- layout.xOf = function(dateStr) {
- var idx = allDates.indexOf(dateStr)
- if (idx < 0) return padL
- if (allDates.length <= 1) return padL + plotW / 2
- return padL + plotW * (idx / (allDates.length - 1))
- }
- // 数值 → Y 像素(Y 轴向上为正)
- layout.yOfC = function(v) {
- return padT + plotH * (1 - (v - yMin) / ySpan)
- }
- this._layout = layout
- return layout
- },
- _doRender: function() {
- if (!this.ctx) return
- var self = this
- var ctx = this.ctx
- var layout = this._buildLayout()
- var w = layout.w, h = layout.h
- var padL = layout.padL, padR = layout.padR, padT = layout.padT, padB = layout.padB
- var plotW = layout.plotW, plotH = layout.plotH
- var seriesList = this._safeSeries(this.series)
- var renderCfg = this.renderConfig
- var drawLine = renderCfg.draw
- var showValues = renderCfg.showValues
- var labelMode = renderCfg.labelMode
- // X 轴日期全集(含缺失期),用于等距布局
- var allDates = layout.allDates
- var xOf = layout.xOf
- var yOfC = layout.yOfC
- var yMin = layout.yMin, yMax = layout.yMax
- ctx.clearRect(0, 0, w, h)
- // 参考范围背景带(浅色横条 + 上下界虚线)
- if (this.hasRefBand && this.refLow !== null && this.refHigh !== null) {
- var bandAlpha = 0.10
- ctx.fillStyle = 'rgba(234, 88, 12, 0.10)' // 浅橙
- var topY = yOfC(this.refHigh)
- var botY = yOfC(this.refLow)
- ctx.fillRect(padL, topY, plotW, Math.max(1, botY - topY))
- // 上下界虚线
- ctx.strokeStyle = 'rgba(234, 88, 12, 0.55)'
- ctx.lineWidth = 1
- ctx.setLineDash ? ctx.setLineDash([4, 4]) : null
- ctx.beginPath(); ctx.moveTo(padL, topY); ctx.lineTo(w - padR, topY); ctx.stroke()
- ctx.beginPath(); ctx.moveTo(padL, botY); ctx.lineTo(w - padR, botY); ctx.stroke()
- ctx.setLineDash ? ctx.setLineDash([]) : null
- }
- // 网格(4 条横线 + 2 条纵线)
- ctx.strokeStyle = BrandColors.slateGhost
- ctx.lineWidth = 1
- for (var gi = 0; gi <= 3; gi++) {
- var gy = padT + plotH * (gi / 3)
- ctx.beginPath()
- ctx.moveTo(padL, gy); ctx.lineTo(w - padR, gy)
- ctx.stroke()
- }
- // Y 轴刻度文字
- ctx.fillStyle = BrandColors.appTextSubtle
- ctx.font = '10px sans-serif'
- ctx.textAlign = 'right'
- for (var ti = 0; ti <= 3; ti++) {
- var tv = yMin + (yMax - yMin) * (1 - ti / 3)
- var ty = padT + plotH * (ti / 3)
- ctx.fillText(self._fmtNum(tv), padL - 4, ty + 3)
- }
- // 折线 + 数据点 + 数值(缺失期断线:遍历 allPeriodDates,无点处不连线)
- var palette = [BrandColors.primary, BrandColors.infoSky, BrandColors.success, BrandColors.primary, BrandColors.danger, BrandColors.wealth]
- seriesList.forEach(function(s, si) {
- var color = s.color || palette[si % palette.length]
- ctx.strokeStyle = color
- ctx.lineWidth = 2
- if (drawLine) {
- ctx.beginPath()
- var started = false
- allDates.forEach(function(d) {
- var pt = null
- for (var pi = 0; pi < s.points.length; pi++) {
- if (s.points[pi].reportDate === d) { pt = s.points[pi]; break }
- }
- if (!pt) { started = false; return } // 缺失期:断线,下一个有效点重新起笔
- var v = parseFloat(pt.value)
- if (isNaN(v)) { started = false; return }
- var x = xOf(d), y = yOfC(v)
- if (!started) { ctx.moveTo(x, y); started = true } else { ctx.lineTo(x, y) }
- })
- ctx.stroke()
- }
- // 数据点 + 值
- s.points.forEach(function(p) {
- var v = parseFloat(p.value)
- if (isNaN(v)) return
- var x = xOf(p.reportDate), y = yOfC(v)
- ctx.fillStyle = color
- ctx.beginPath(); ctx.arc(x, y, 3.5, 0, 2 * Math.PI); ctx.fill()
- if (showValues) {
- var label = unitMismatchMark(p.value, p.unit, self.latestUnit, p.unitMismatch)
- ctx.fillStyle = BrandColors.slate600
- ctx.font = '10px sans-serif'
- ctx.textAlign = 'center'
- ctx.fillText(label, x, y - 8)
- }
- })
- // 序列名(最右端上方)
- ctx.fillStyle = color
- ctx.font = '11px sans-serif'
- ctx.textAlign = 'right'
- var last = s.points[s.points.length - 1]
- if (last && !isNaN(parseFloat(last.value))) {
- ctx.fillText(s.name || '', xOf(last.reportDate), yOfC(parseFloat(last.value)) - 14)
- }
- })
- // X 轴日期标签(抽稀,带 * 标记)
- if (showAxisLabels && allDates.length > 0) {
- ctx.fillStyle = BrandColors.appTextSubtle
- ctx.font = '10px sans-serif'
- ctx.textAlign = 'center'
- var indices = axisLabelIndices(allDates.length)
- indices.forEach(function(idx) {
- var d = allDates[idx]
- // 找对应点的 dateSource 用于 * 标记
- var ds = ''
- seriesList.forEach(function(s) {
- for (var pi = 0; pi < s.points.length; pi++) {
- if (s.points[pi].reportDate === d) { ds = s.points[pi].dateSource || ''; break }
- }
- })
- var label = dateWithSourceMark(normalizeDate(d), ds)
- var x = xOf(d)
- ctx.fillText(label, x, h - 8)
- })
- }
- },
- _fmtNum: function(v) {
- if (v >= 100) return Math.round(v) + ''
- if (v >= 10) return v.toFixed(1)
- return v.toFixed(2)
- },
- onCanvasTap: function(e) {
- if (!this.canvasReady) return
- var layout = this._layout
- if (!layout) return
- // 从事件中取页面坐标(与 RadarChart 同套容错)
- var pageX
- var pageY
- if (e.detail && typeof e.detail.x === 'number') {
- pageX = e.detail.x
- pageY = e.detail.y
- } else if (e.touches && e.touches[0]) {
- pageX = e.touches[0].x || e.touches[0].clientX || 0
- pageY = e.touches[0].y || e.touches[0].clientY || 0
- } else if (e.changedTouches && e.changedTouches[0]) {
- pageX = e.changedTouches[0].x || e.changedTouches[0].clientX || 0
- pageY = e.changedTouches[0].y || e.changedTouches[0].clientY || 0
- } else {
- return
- }
- // 转 canvas 相对坐标
- var relX = pageX - (this._canvasLeft || 0)
- var relY = pageY - (this._canvasTop || 0)
- if (relX < 0 || relY < 0 || relX > this.canvasWidth || relY > this.canvasHeight) return
- // 找最近数据点(P2-2 长按读数的基础)
- var best = null
- var bestDist = Infinity
- var hitRadius = 40
- for (var si = 0; si < this.series.length; si++) {
- var s = this.series[si]
- if (!s || !Array.isArray(s.points)) continue
- for (var pi = 0; pi < s.points.length; pi++) {
- var p = s.points[pi]
- if (!p) continue
- var v = parseFloat(p.value)
- if (isNaN(v)) continue
- var x = layout.xOf(p.reportDate)
- var y = layout.yOfC(v)
- var dx = x - relX
- var dy = y - relY
- var dist = dx * dx + dy * dy
- if (dist < bestDist) {
- bestDist = dist
- best = { index: pi, point: p, x: x, y: y }
- }
- }
- }
- if (best && bestDist <= hitRadius * hitRadius) {
- this.$emit('pointTap', { index: best.index, point: best.point, x: best.x, y: best.y })
- }
- }
- }
- }
- </script>
- <style scoped lang="scss">
- .trend-chart-wrap {
- display: flex;
- flex-direction: column;
- }
- .ref-band-hint {
- font-size: calc(16rpx * var(--font-scale, 1));
- color: #EA580C;
- padding: 0 8rpx 4rpx 8rpx;
- }
- .ref-band-label {
- font-weight: 600;
- }
- .trend-container {
- position: relative;
- }
- .trend-canvas {
- display: block;
- }
- .trend-tap-layer {
- position: absolute;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- }
- .trend-legend {
- display: flex;
- flex-direction: row;
- flex-wrap: wrap;
- justify-content: center;
- padding-top: 12rpx;
- }
- .legend-item {
- display: flex;
- flex-direction: row;
- align-items: center;
- margin: 0 16rpx 8rpx;
- }
- .legend-line {
- width: 32rpx;
- border-top: 4rpx solid $uni-info;
- margin-right: 8rpx;
- }
- .legend-text {
- font-size: calc(22rpx * var(--font-scale, 1));
- color: $facade-text-slate-deep;
- }
- </style>
|