Procházet zdrojové kódy

feat(T04): 指标时间轴页 多指标同图归一化对比 + 关注指标收藏(D12 第二段)

A. 多指标同图归一化对比(PRD P2-4)
- indicator-timeline.vue 新增「多指标对比」显式开关,chips 变为多选勾选(硬性上限 3)
- 各指标按自身当前筛选范围 (min,max) 线性归一化到 [0,1],TrendChart 同图绘制
- 图例标注 指标名+单位+真实范围(min~max),归一化仅用于同图比较,真实数值可读回
- 归一化边界:min==max 恒定值→0.5 并标注无波动;仅 1 期/2 期 不连假线(drawLine=false)
- 缺失期断线不插值(allPeriodDates 并集 + TrendChart 逐日期断线)
- 新增「同图对比·各期真实值」明细表,读回每期真实数值
- 单指标路径零改动(compareMode=false 时行为与改动前完全一致)

B. 关注指标收藏
- 本地持久化(小程序 Storage),key 隔离维度 用户×家庭×成员×报告类型,防串号
- 收藏入口:指标头部卡★开关 + chip★标记 + 对比区每指标☆开关;取消收藏立即消失
- 注释标注「当前为本地持久化,后续若需跨端同步再接后端」,不新建表/不改后端接口

新增 utils/indicator-compare.js、utils/indicator-favorite.js 纯函数 + 58 项单测。
TrendChart.vue 支持逐序列 drawLine 与增强图例(向后兼容)。
iwt před 3 týdny
rodič
revize
dbf13c610

+ 335 - 0
cfc-frontend/__tests__/utils/indicator-compare.test.js

@@ -0,0 +1,335 @@
+/**
+ * utils/indicator-compare 多指标同图归一化纯函数单测
+ * 覆盖:PRD §4.3 P2-4 / design §1.2.1 第二段 / design §1092
+ */
+import * as ic from '@/utils/indicator-compare'
+
+describe('indicator-compare 多指标同图归一化', () => {
+  describe('MAX_COMPARE_INDICATORS', () => {
+    test('上限为 3', () => {
+      expect(ic.MAX_COMPARE_INDICATORS).toBe(3)
+    })
+  })
+
+  describe('pointNumeric', () => {
+    test('numericValue 优先', () => {
+      expect(ic.pointNumeric({ value: 'abc', numericValue: 2.5 })).toBe(2.5)
+    })
+    test('回退 value', () => {
+      expect(ic.pointNumeric({ value: '3.62' })).toBe(3.62)
+    })
+    test('非数字返回 null', () => {
+      expect(ic.pointNumeric({ value: 'N/A' })).toBe(null)
+    })
+    test('null/undefined 输入返回 null', () => {
+      expect(ic.pointNumeric(null)).toBe(null)
+      expect(ic.pointNumeric(undefined)).toBe(null)
+      expect(ic.pointNumeric({})).toBe(null)
+    })
+    test('numericValue 为 0 正确返回 0', () => {
+      expect(ic.pointNumeric({ value: '0', numericValue: 0 })).toBe(0)
+    })
+  })
+
+  describe('normalizeValue', () => {
+    test('正常线性映射', () => {
+      expect(ic.normalizeValue(5, 0, 10)).toBeCloseTo(0.5)
+      expect(ic.normalizeValue(0, 0, 10)).toBeCloseTo(0)
+      expect(ic.normalizeValue(10, 0, 10)).toBeCloseTo(1)
+    })
+    test('min === max 恒定值 → 0.5', () => {
+      expect(ic.normalizeValue(3.62, 3.62, 3.62)).toBe(0.5)
+    })
+    test('越界值夹到 [0,1]', () => {
+      expect(ic.normalizeValue(-1, 0, 10)).toBe(0)
+      expect(ic.normalizeValue(15, 0, 10)).toBe(1)
+    })
+    test('null/min/max 安全返回 null', () => {
+      expect(ic.normalizeValue(null, 0, 10)).toBe(null)
+      expect(ic.normalizeValue(5, null, 10)).toBe(null)
+      expect(ic.normalizeValue(5, 0, null)).toBe(null)
+    })
+    test('NaN 输入返回 null', () => {
+      expect(ic.normalizeValue(NaN, 0, 10)).toBe(null)
+    })
+  })
+
+  describe('computeRealRange', () => {
+    test('空 points → count=0', () => {
+      var r = ic.computeRealRange({ points: [] })
+      expect(r.count).toBe(0)
+      expect(r.min).toBe(null)
+      expect(r.max).toBe(null)
+    })
+    test('undefined item → count=0', () => {
+      expect(ic.computeRealRange(null).count).toBe(0)
+      expect(ic.computeRealRange(undefined).count).toBe(0)
+    })
+    test('单点 → count=1,无波动', () => {
+      var r = ic.computeRealRange({ points: [{ value: '3.62', numericValue: 3.62 }] })
+      expect(r.count).toBe(1)
+      expect(r.min).toBeCloseTo(3.62)
+      expect(r.max).toBeCloseTo(3.62)
+      expect(r.hasVariance).toBe(false)
+    })
+    test('恒定值 ≥2 点 → count≥2 但 hasVariance=false', () => {
+      var r = ic.computeRealRange({
+        points: [{ value: '3.62', numericValue: 3.62 }, { value: '3.62', numericValue: 3.62 }]
+      })
+      expect(r.count).toBe(2)
+      expect(r.min).toBeCloseTo(3.62)
+      expect(r.max).toBeCloseTo(3.62)
+      expect(r.hasVariance).toBe(false)
+    })
+    test('正常变化 → hasVariance=true', () => {
+      var r = ic.computeRealRange({
+        points: [
+          { value: '3.62', numericValue: 3.62 },
+          { value: '4.10', numericValue: 4.10 }
+        ]
+      })
+      expect(r.count).toBe(2)
+      expect(r.min).toBeCloseTo(3.62)
+      expect(r.max).toBeCloseTo(4.10)
+      expect(r.hasVariance).toBe(true)
+    })
+    test('有效数值过滤 NaN / 单位不同时 numericValue 仍可用', () => {
+      var r = ic.computeRealRange({
+        points: [
+          { value: '10%', numericValue: 10 },
+          { value: 'abc' }  // numericValue 缺失且 value 不可转数字
+        ]
+      })
+      expect(r.count).toBe(1)
+      expect(r.min).toBeCloseTo(10)
+      expect(r.max).toBeCloseTo(10)
+    })
+  })
+
+  describe('toggleCompareSelection', () => {
+    test('第 1 个添加成功', () => {
+      var res = ic.toggleCompareSelection([], 101)
+      expect(res.changed).toBe(true)
+      expect(res.rejected).toBe(false)
+      expect(res.ids).toEqual([101])
+    })
+    test('添加第 2、3 个均成功', () => {
+      var res = ic.toggleCompareSelection([101], 102)
+      expect(res.ids).toEqual([101, 102])
+      res = ic.toggleCompareSelection(res.ids, 103)
+      expect(res.ids).toEqual([101, 102, 103])
+    })
+    test('第 4 个被拒(上限 3)', () => {
+      var res = ic.toggleCompareSelection([101, 102, 103], 104)
+      expect(res.changed).toBe(false)
+      expect(res.rejected).toBe(true)
+      expect(res.ids).toEqual([101, 102, 103])
+    })
+    test('取消勾选移除', () => {
+      var res = ic.toggleCompareSelection([101, 102], 102)
+      expect(res.ids).toEqual([101])
+      expect(res.changed).toBe(true)
+    })
+    test('重复添加忽略', () => {
+      var res = ic.toggleCompareSelection([101], 101)
+      expect(res.ids).toEqual([])
+    })
+    test('传 null/undefined definitionId 不改变 ids', () => {
+      var res = ic.toggleCompareSelection([101], null)
+      expect(res.changed).toBe(false)
+      expect(res.ids).toEqual([101])
+      res = ic.toggleCompareSelection([101], undefined)
+      expect(res.changed).toBe(false)
+    })
+    test('自定义 max 生效', () => {
+      var res = ic.toggleCompareSelection([101, 102], 103, 2)
+      expect(res.rejected).toBe(true)
+    })
+  })
+
+  describe('buildCompareSeries', () => {
+    var baseItem = function(defId, name, unit, pts) {
+      return { definitionId: defId, name: name, unit: unit, points: pts }
+    }
+    test('无有效数值 → 不纳入 series', () => {
+      var items = [baseItem(1, 'A', '%', [{ reportDate: '2026-01-01', value: 'N/A' }])]
+      var s = ic.buildCompareSeries(items)
+      expect(s.length).toBe(0)
+    })
+    test('constant 系列 hasVariance=false,drawLine=true(≥1 个点始终画点)', () => {
+      var items = [baseItem(1, 'A', '%', [{ reportDate: '2026-01-01', value: '5', numericValue: 5 }])]
+      var s = ic.buildCompareSeries(items)
+      expect(s.length).toBe(1)
+      expect(s[0].realMin).toBeCloseTo(5)
+      expect(s[0].realMax).toBeCloseTo(5)
+      expect(s[0].realCount).toBe(1)
+      expect(s[0].hasVariance).toBe(false)
+      // 单点:n<3 → drawLine=false(红线:n<3 不连假线)
+      expect(s[0].drawLine).toBe(false)
+      expect(s[0].points.length).toBe(1)
+      expect(s[0].points[0].value).toBeCloseTo(0.5)   // min==max → 0.5
+    })
+    test('两期(n=2)→ drawLine=false(红线),数据仍在 series 中用于展示双点', () => {
+      var items = [baseItem(1, 'LDL-C', 'mmol/L', [
+        { reportDate: '2026-01-01', value: '3.62', numericValue: 3.62 },
+        { reportDate: '2026-06-01', value: '4.10', numericValue: 4.10 }
+      ])]
+      var s = ic.buildCompareSeries(items)
+      expect(s.length).toBe(1)
+      expect(s[0].drawLine).toBe(false)
+      expect(s[0].realCount).toBe(2)
+    })
+    test('三期(n=3)→ drawLine=true', () => {
+      var items = [baseItem(1, 'X', 'mmol/L', [
+        { reportDate: '2026-01', value: '1', numericValue: 1 },
+        { reportDate: '2026-02', value: '2', numericValue: 2 },
+        { reportDate: '2026-03', value: '3', numericValue: 3 }
+      ])]
+      var s = ic.buildCompareSeries(items)
+      expect(s[0].drawLine).toBe(true)
+    })
+    test('混合单位(mmol/L 与 %)各自归一化独立', () => {
+      var items = [
+        baseItem(1, 'A', 'mmol/L', [
+          { reportDate: '2026-01-01', value: '3.62', numericValue: 3.62 },
+          { reportDate: '2026-06-01', value: '4.10', numericValue: 4.10 }
+        ]),
+        baseItem(2, 'B', '%', [
+          { reportDate: '2026-01-01', value: '50', numericValue: 50 },
+          { reportDate: '2026-06-01', value: '80', numericValue: 80 }
+        ])
+      ]
+      var s = ic.buildCompareSeries(items)
+      expect(s.length).toBe(2)
+      // A 映射 [3.62, 4.10] → [0, 1]
+      expect(s[0].points[0].value).toBeCloseTo(0)
+      expect(s[0].points[1].value).toBeCloseTo(1)
+      // B 映射 [50, 80] → [0, 1]
+      expect(s[1].points[0].value).toBeCloseTo(0)
+      expect(s[1].points[1].value).toBeCloseTo(1)
+      // 真实范围保留
+      expect(s[0].realMin).toBeCloseTo(3.62)
+      expect(s[0].realMax).toBeCloseTo(4.10)
+      expect(s[1].realMin).toBeCloseTo(50)
+      expect(s[1].realMax).toBeCloseTo(80)
+      // 颜色轮转
+      expect(s[0].color).toBe('#F97316')
+      expect(s[1].color).toBe('#0EA5E9')
+    })
+    test('legendText 格式:有波动 → "name(unit) · 真实范围 min~max"', () => {
+      var items = [baseItem(1, 'LDL-C', 'mmol/L', [
+        { reportDate: '2026-01-01', value: '3.62', numericValue: 3.62 },
+        { reportDate: '2026-06-01', value: '4.10', numericValue: 4.10 }
+      ])]
+      var s = ic.buildCompareSeries(items)
+      expect(s[0].legendText).toMatch(/真实范围/)
+      expect(s[0].legendText).toContain('LDL-C')
+    })
+    test('legendText 格式:仅 1 期 → "仅 1 期 x(无趋势)"', () => {
+      var items = [baseItem(1, 'A', '%', [{ reportDate: '2026-01-01', value: '5', numericValue: 5 }])]
+      var s = ic.buildCompareSeries(items)
+      expect(s[0].legendText).toMatch(/仅 1 期/)
+    })
+    test('legendText 格式:无波动 → "无波动 恒定 x"', () => {
+      var items = [baseItem(1, 'A', '%', [
+        { reportDate: '2026-01-01', value: '5', numericValue: 5 },
+        { reportDate: '2026-06-01', value: '5', numericValue: 5 }
+      ])]
+      var s = ic.buildCompareSeries(items)
+      expect(s[0].legendText).toMatch(/无波动/)
+    })
+    test('无有效数值的条目跳过,不占 color 位置', () => {
+      var items = [
+        baseItem(1, 'A', '%', [{ reportDate: '2026-01-01', value: 'N/A' }]),
+        baseItem(2, 'B', '%', [{ reportDate: '2026-01-01', value: '5', numericValue: 5 }])
+      ]
+      var s = ic.buildCompareSeries(items)
+      expect(s.length).toBe(1)
+      expect(s[0].color).toBe('#F97316') // 仍然用 palette[0](首个有效)
+    })
+  })
+
+  describe('buildCompareAllDates', () => {
+    test('空数组 → []', () => {
+      expect(ic.buildCompareAllDates([])).toEqual([])
+    })
+    test('只含 points → 升序并集', () => {
+      var items = [
+        { points: [{ reportDate: '2026-03-01' }, { reportDate: '2026-05-01' }] },
+        { points: [{ reportDate: '2026-01-01' }, { reportDate: '2026-05-01' }] }
+      ]
+      var dates = ic.buildCompareAllDates(items)
+      expect(dates).toEqual(['2026-01-01', '2026-03-01', '2026-05-01'])
+    })
+    test('缺失期(missingPeriods)也并入 X 轴', () => {
+      var items = [{ points: [{ reportDate: '2026-01-01' }, { reportDate: '2026-03-01' }], missingPeriods: [{ reportDate: '2026-02-01' }] }]
+      var dates = ic.buildCompareAllDates(items)
+      expect(dates).toEqual(['2026-01-01', '2026-02-01', '2026-03-01'])
+    })
+    test('日期截断到 yyyy-MM-dd', () => {
+      var items = [{ points: [{ reportDate: '2026-01-15T14:30:00' }] }]
+      var dates = ic.buildCompareAllDates(items)
+      expect(dates).toEqual(['2026-01-15'])
+    })
+  })
+
+  describe('buildComparePeriodRows', () => {
+    test('缺失期 → 该期未检测', () => {
+      var items = [
+        { definitionId: 1, name: 'A', unit: 'mmol/L', points: [{ reportDate: '2026-01-01', value: '3.62', numericValue: 3.62 }, { reportDate: '2026-03-01', value: '4.10', numericValue: 4.10 }], missingPeriods: [{ reportDate: '2026-02-01' }] }
+      ]
+      var rows = ic.buildComparePeriodRows(items)
+      expect(rows.length).toBe(3)
+      // 按日期倒序(新→旧)
+      expect(rows[0].dateText).toContain('03-01')
+      expect(rows[1].dateText).toContain('02-01')
+      expect(rows[2].dateText).toContain('01-01')
+      // 缺失期单元格
+      expect(rows[1].cells[0].valueText).toBe('该期未检测')
+      expect(rows[1].cells[0].isMissing).toBe(true)
+    })
+    test('真实值读回带单位', () => {
+      var items = [{ definitionId: 1, name: 'LDL-C', unit: 'mmol/L', points: [{ reportDate: '2026-01-01', value: '3.62', numericValue: 3.62 }] }]
+      var rows = ic.buildComparePeriodRows(items)
+      expect(rows[0].cells[0].valueText).toContain('3.62')
+      expect(rows[0].cells[0].valueText).toContain('mmol/L')
+    })
+    test('多指标列对齐', () => {
+      var items = [
+        { definitionId: 1, name: 'A', unit: 'mmol/L', points: [{ reportDate: '2026-01-01', value: '1.0', numericValue: 1 }] },
+        { definitionId: 2, name: 'B', unit: '%', points: [{ reportDate: '2026-01-01', value: '50', numericValue: 50 }] }
+      ]
+      var rows = ic.buildComparePeriodRows(items)
+      expect(rows[0].cells.length).toBe(2)
+      expect(rows[0].cells[0].name).toBe('A')
+      expect(rows[0].cells[1].name).toBe('B')
+    })
+  })
+
+  describe('buildLegendText', () => {
+    test('count=0 → 暂无数据', () => {
+      expect(ic.buildLegendText({ points: [] })).toBe(' · 暂无数据')
+    })
+    test('count=1 → 仅 1 期 无趋势', () => {
+      var t = ic.buildLegendText({ name: 'A', unit: '%', points: [{ numericValue: 5 }] })
+      expect(t).toContain('仅 1 期')
+      expect(t).toContain('无趋势')
+    })
+    test('count≥2 且 min===max → 无波动 恒定', () => {
+      var t = ic.buildLegendText({ name: 'A', unit: '%', points: [{ numericValue: 5 }, { numericValue: 5 }] })
+      expect(t).toContain('无波动')
+      expect(t).toContain('恒定')
+      expect(t).toContain('5.00')
+    })
+    test('count=2 有波动 → 追加(仅 2 期,未连线)', () => {
+      var t = ic.buildLegendText({ name: 'LDL-C', unit: 'mmol/L', points: [{ numericValue: 3.62 }, { numericValue: 4.10 }] })
+      expect(t).toContain('仅 2 期,未连线')
+      expect(t).toContain('真实范围')
+    })
+    test('count≥3 有波动 → 仅真实范围', () => {
+      var t = ic.buildLegendText({ name: 'X', unit: 'mg/dL', points: [{ numericValue: 1 }, { numericValue: 2 }, { numericValue: 3 }] })
+      expect(t).toContain('真实范围')
+      expect(t).not.toContain('仅 2 期')
+    })
+  })
+})

+ 101 - 0
cfc-frontend/__tests__/utils/indicator-favorite.test.js

@@ -0,0 +1,101 @@
+/**
+ * utils/indicator-favorite 关注指标收藏单测
+ * 规则来源:PRD §4.3 P2 隐含 / design §1.2.1 第二段
+ * 隔离维度:userId × familyId × memberId × sourceType → 不同 key,防串号
+ */
+import { buildFavoriteKey, readFavorites, writeFavorites, toggleFavorite } from '@/utils/indicator-favorite'
+
+describe('indicator-favorite 本地持久化收藏', () => {
+  beforeEach(function() {
+    // 每个用例前清空 storage,避免用例间污染
+    if (global.uni && global.uni._storage) {
+      Object.keys(global.uni._storage).filter(function(k) { return k.indexOf('cfc:indicator:fav:') === 0 }).forEach(function(k) { delete global.uni._storage[k] })
+    }
+  })
+
+  describe('buildFavoriteKey', () => {
+    test('默认维度全部填充占位符', () => {
+      var key = buildFavoriteKey({})
+      expect(key).toMatch(/cfc:indicator:fav:anon:nofamily:nomember:all$/)
+    })
+    test('全维度隔离', () => {
+      var k1 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 3, sourceType: 'gut_flora' })
+      var k2 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 4, sourceType: 'gut_flora' })
+      expect(k2).not.toBe(k1)
+      expect(k2).toContain(':4:')
+    })
+    test('sourceType 隔离', () => {
+      var k1 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 3, sourceType: 'gut_flora' })
+      var k2 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 3, sourceType: 'food_recommend' })
+      expect(k2).not.toBe(k1)
+    })
+    test('不同 familyId 隔离', () => {
+      var k1 = buildFavoriteKey({ userId: 1, familyId: 2, memberId: 3 })
+      var k2 = buildFavoriteKey({ userId: 1, familyId: 5, memberId: 3 })
+      expect(k2).not.toBe(k1)
+    })
+  })
+
+  describe('readFavorites', () => {
+    test('空 storage → []', () => {
+      expect(readFavorites({ userId: 1, familyId: 1, memberId: 1, sourceType: 'all' })).toEqual([])
+    })
+    test('写入后读取返回数组', () => {
+      writeFavorites({ userId: 1, familyId: 1, memberId: 1, sourceType: 'all' }, [101, 102])
+      var ids = readFavorites({ userId: 1, familyId: 1, memberId: 1, sourceType: 'all' })
+      expect(ids).toEqual([101, 102])
+    })
+    test('非法数据容错返回 []', () => {
+      var key = buildFavoriteKey({ userId: 1, familyId: 1, memberId: 1, sourceType: 'all' })
+      global.uni._storage[key] = 'not-a-json'
+      expect(readFavorites({ userId: 1, familyId: 1, memberId: 1, sourceType: 'all' })).toEqual([])
+      global.uni._storage[key] = 123
+      expect(readFavorites({ userId: 1, familyId: 1, memberId: 1, sourceType: 'all' })).toEqual([])
+    })
+    test('跨 scope 隔离:不同 memberId 读到空数组', () => {
+      writeFavorites({ userId: 1, familyId: 1, memberId: 2, sourceType: 'all' }, [101])
+      expect(readFavorites({ userId: 1, familyId: 1, memberId: 2, sourceType: 'all' })).toEqual([101])
+      expect(readFavorites({ userId: 1, familyId: 1, memberId: 3, sourceType: 'all' })).toEqual([])
+    })
+  })
+
+  describe('toggleFavorite', () => {
+    test('首次收藏 → added=true,写入存储', () => {
+      var scope = { userId: 1, familyId: 1, memberId: 1, sourceType: 'gut_flora' }
+      var res = toggleFavorite(scope, 101)
+      expect(res.added).toBe(true)
+      expect(res.ids).toEqual([101])
+      expect(readFavorites(scope)).toEqual([101])
+    })
+    test('已收藏再点 → added=false,从存储移除', () => {
+      var scope = { userId: 1, familyId: 1, memberId: 1, sourceType: 'gut_flora' }
+      toggleFavorite(scope, 101)
+      var res = toggleFavorite(scope, 101)
+      expect(res.added).toBe(false)
+      expect(res.ids).toEqual([])
+      expect(readFavorites(scope)).toEqual([])
+    })
+    test('多个收藏状态独立切换', () => {
+      var scope = { userId: 1, familyId: 1, memberId: 1, sourceType: 'gut_flora' }
+      toggleFavorite(scope, 101)
+      toggleFavorite(scope, 102)
+      toggleFavorite(scope, 101) // 取消 101
+      var ids = readFavorites(scope)
+      expect(ids).toEqual([102])
+    })
+    test('定义 id 非法(NaN)→ 不改变存储', () => {
+      var scope = { userId: 1, familyId: 1, memberId: 1, sourceType: 'gut_flora' }
+      writeFavorites(scope, [101])
+      var res = toggleFavorite(scope, 'not-a-number')
+      expect(res.ids).toEqual([101])
+      expect(res.added).toBe(false)
+    })
+    test('跨 sourceType 收藏隔离', () => {
+      var s1 = { userId: 1, familyId: 1, memberId: 1, sourceType: 'gut_flora' }
+      var s2 = { userId: 1, familyId: 1, memberId: 1, sourceType: 'food_recommend' }
+      toggleFavorite(s1, 101)
+      expect(readFavorites(s1)).toEqual([101])
+      expect(readFavorites(s2)).toEqual([])
+    })
+  })
+})

+ 10 - 2
cfc-frontend/pages/health/components/TrendChart.vue

@@ -11,7 +11,7 @@
     <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>
+        <text class="legend-text" :class="s.legendText ? 'legend-text-full' : ''">{{ s.legendText || s.name }}</text>
       </view>
     </view>
   </view>
@@ -272,6 +272,8 @@ export default {
       var seriesList = this._safeSeries(this.series)
       var renderCfg = this.renderConfig
       var drawLine = renderCfg.draw
+      // 逐 series 线控:s.drawLine === false 时该序列只画点不连线(期数不足的红线处理)
+      // 兼容旧用法:未传 drawLine 的序列沿用全局 drawLine(默认连线)
       var showValues = renderCfg.showValues
       var labelMode = renderCfg.labelMode
 
@@ -324,7 +326,7 @@ export default {
         var color = s.color || palette[si % palette.length]
         ctx.strokeStyle = color
         ctx.lineWidth = 2
-        if (drawLine) {
+        if (drawLine && s.drawLine !== false) {
           ctx.beginPath()
           var started = false
           allDates.forEach(function(d) {
@@ -488,6 +490,7 @@ export default {
   flex-direction: row;
   align-items: center;
   margin: 0 16rpx 8rpx;
+  max-width: 100%;
 }
 .legend-line {
   width: 32rpx;
@@ -498,4 +501,9 @@ export default {
   font-size: calc(22rpx * var(--font-scale, 1));
   color: $facade-text-slate-deep;
 }
+.legend-text-full {
+  flex: 1;
+  white-space: normal;
+  line-height: 1.4;
+}
 </style>

+ 377 - 35
cfc-frontend/pages/health/indicator-timeline.vue

@@ -10,7 +10,18 @@
       </picker>
     </view>
 
-    <!-- ⑤ 指标横向切换(chip) -->
+    <!-- ⑥·5 工具行:多指标对比开关(显式开关,单击 chip 仍是单指标切换,不破坏现有路径) -->
+    <view class="tool-row">
+      <view class="tool-group">
+        <view class="tool-btn" :class="compareMode ? 'tool-btn-on' : ''" @tap="onToggleCompareMode">
+          <text>{{ compareMode ? '退出对比' : '多指标对比' }}</text>
+        </view>
+        <text class="tool-note" v-if="compareMode">最多选 {{ maxCompare }} 个,已选 {{ compareIds.length }} 个</text>
+      </view>
+      <text class="tool-note tool-note-warn" v-if="compareLimitHint">{{ compareLimitHint }}</text>
+    </view>
+
+    <!-- ⑤ 指标横向切换(chip;★=已收藏,✓=对比已勾选) -->
     <scroll-view scroll-x class="chip-scroll" v-if="indicatorOptions.length > 1">
       <view
         class="indicator-chip"
@@ -18,14 +29,21 @@
         v-for="def in indicatorOptions"
         :key="getIndicatorKey(def)"
         @tap="onIndicatorTap(getIndicatorId(def))"
-      >{{ getIndicatorName(def) }}</view>
+      >
+        <text class="chip-check" v-if="compareMode && isSelectedDef(getIndicatorId(def))">✓</text>
+        <text class="chip-star" v-if="isFavoriteDef(getIndicatorId(def))">★</text>
+        <text>{{ getIndicatorName(def) }}</text>
+      </view>
     </scroll-view>
 
-    <!-- ② 指标头部卡 -->
-    <view class="head-card" v-if="hasItem">
+    <!-- ② 指标头部卡(单指标模式) -->
+    <view class="head-card" v-if="hasItem && !compareMode">
       <view class="head-row">
         <text class="head-name">{{ item.name }}</text>
-        <text class="status-tag" :class="latestMeta._cssClass">{{ latestMeta._statusText }}</text>
+        <view class="head-side">
+          <text class="fav-btn" :class="currentFavClass" @tap="onToggleFavorite(item.definitionId)">{{ currentFavText }}</text>
+          <text class="status-tag" :class="latestMeta._cssClass">{{ latestMeta._statusText }}</text>
+        </view>
       </view>
       <view class="head-value-row">
         <text class="head-value">{{ latestValueText }}</text>
@@ -38,14 +56,15 @@
       </view>
     </view>
 
-    <!-- ②·5 残缺横幅(P0 红线,不可裁剪) -->
+    <!-- ②·5 残缺横幅(P0 红线,不可裁剪;单指标模式) -->
     <IndicatorIncompleteBanner
+      v-if="!compareMode"
       :points-count="pointsCount"
       :total-report-count="totalReportCount"
     />
 
-    <!-- ③ 图表区(形态由 chartMode 决定) -->
-    <view class="chart-card">
+    <!-- ③ 图表区(单指标模式,形态由 chartMode 决定) -->
+    <view class="chart-card" v-if="!compareMode">
       <!-- loading -->
       <view class="chart-loading" v-if="loading">
         <text class="loading-text">加载中...</text>
@@ -111,8 +130,8 @@
       </view>
     </view>
 
-    <!-- ④ 期次明细表(倒序,最新在最上) -->
-    <view class="period-card" v-if="periodRows.length > 0">
+    <!-- ④ 期次明细表(单指标模式,倒序,最新在最上) -->
+    <view class="period-card" v-if="periodRows.length > 0 && !compareMode">
       <view class="section-title">期次明细</view>
       <view class="period-row" v-for="(row, ri) in periodRows" :key="getPeriodKey(row, ri)">
         <text class="period-date">{{ row._dateText }}</text>
@@ -129,6 +148,78 @@
       </view>
     </view>
 
+    <!-- ⑦ 多指标同图对比区(仅对比模式,P2-4) -->
+    <view v-if="compareMode">
+      <!-- 对比头部卡:说明 + 每指标真实范围 + 收藏开关 + 残缺横幅 -->
+      <view class="compare-head">
+        <view class="head-row">
+          <text class="head-name">多指标同图对比</text>
+          <text class="tool-note">归一化到 0–1</text>
+        </view>
+        <text class="compare-note">各线已按自身范围归一化,仅用于同图比较;真实数值见图例与下方明细。</text>
+        <text class="compare-note compare-note-ref">参考范围请以单指标视图为准。</text>
+        <view class="compare-ind-row" v-for="(row, ri) in compareSummaryRows" :key="getCompareRowKey(row, ri)">
+          <text class="compare-ind-star" :class="row.isFav ? 'compare-ind-star-on' : ''" @tap="onToggleFavorite(row.definitionId)">{{ row.isFav ? '★' : '☆' }}</text>
+          <text class="compare-ind-name">{{ row.name }}</text>
+          <text class="compare-ind-unit" v-if="row.unit">{{ row.unit }}</text>
+          <text class="compare-ind-range">{{ row.rangeText }}</text>
+        </view>
+        <IndicatorIncompleteBanner
+          v-for="cmpItem in compareItems"
+          :key="getCompareBannerKey(cmpItem)"
+          :points-count="cmpItem.pointsCount || 0"
+          :total-report-count="cmpItem.totalReportCount || 0"
+        />
+      </view>
+
+      <!-- 对比图表卡(归一化多序列,n<3 序列不连线,缺失期断线) -->
+      <view class="chart-card">
+        <view class="chart-loading" v-if="compareLoading">
+          <text class="loading-text">加载中...</text>
+        </view>
+        <view v-else-if="compareErrorState">
+          <IndicatorDegrade scene="error" :retry="retryCompareLoad" />
+        </view>
+        <view v-else-if="compareIds.length < 2">
+          <text class="empty-text">{{ compareEmptyHint }}</text>
+        </view>
+        <view v-else-if="compareSeries.length < 2">
+          <text class="empty-text">所选指标中只有 {{ compareSeries.length }} 个有有效数值数据,暂无法同图对比</text>
+        </view>
+        <view v-else>
+          <view class="granularity-switch" v-if="compareShowGranularity">
+            <text class="gran-btn" :class="granularity === 'month' ? 'gran-active' : ''" @tap="onGranularityTap('month')">按月</text>
+            <text class="gran-btn" :class="granularity === 'raw' ? 'gran-active' : ''" @tap="onGranularityTap('raw')">按原始点</text>
+          </view>
+          <TrendChart
+            :series="compareSeries"
+            mode="line"
+            :ref-low="null"
+            :ref-high="null"
+            :all-period-dates="compareAllDates"
+            :show-values="false"
+            :show-axis-labels="true"
+          />
+        </view>
+      </view>
+
+      <!-- 对比明细(各期真实值,读回真实数值) -->
+      <view class="period-card" v-if="comparePeriodRows.length > 0">
+        <view class="section-title">同图对比 · 各期真实值</view>
+        <view class="compare-period-header">
+          <text class="compare-cell compare-cell-date">日期</text>
+          <text class="compare-cell compare-cell-name" v-for="(cmpItem, ci) in compareItems" :key="getCompareCellKey(cmpItem, ci)">{{ cmpItem.name }}</text>
+        </view>
+        <view class="compare-period-row" v-for="(row, ri) in comparePeriodRows" :key="getCompareRowKey(row, ri)">
+          <text class="compare-cell compare-cell-date">{{ row.dateText }}</text>
+          <text class="compare-cell" :class="cell.isMissing ? 'compare-cell-missing' : ''" v-for="(cell, ci) in row.cells" :key="getCompareRowCellKey(row, ci)">{{ cell.valueText }}</text>
+        </view>
+        <view class="period-footnote" v-if="compareHasUploadDate">
+          <text>* 未识别到采样日期,按上传日期记录</text>
+        </view>
+      </view>
+    </view>
+
     <!-- ⑥ 合规 footer(常显不可关) -->
     <view class="footer">
       <text class="footer-text">本页数据来自检测报告,趋势仅表示数值变化,不构成医学诊断或治疗建议。</text>
@@ -139,7 +230,9 @@
 <script>
 import { getFamilyMemberList, getIndicatorTimeline, getIndicatorSourceTypes, getIndicatorChangeRanking } from '@/utils/api'
 import { resolveChange, formatCompareDate } from '@/utils/indicator-change.js'
-import { consumeChartMode, buildAllPeriodDates, buildPeriodRows, formatPeriodDate, dateWithSourceMark, normalizeDate } from '@/utils/indicator-timeline.js'
+import { consumeChartMode, buildAllPeriodDates, buildPeriodRows, formatPeriodDate, dateWithSourceMark, normalizeDate, roundSig } from '@/utils/indicator-timeline.js'
+import { MAX_COMPARE_INDICATORS, buildCompareSeries, buildCompareAllDates, buildComparePeriodRows, computeRealRange, toggleCompareSelection } from '@/utils/indicator-compare.js'
+import { readFavorites, toggleFavorite } from '@/utils/indicator-favorite.js'
 import IndicatorIncompleteBanner from '@/pages/health/components/IndicatorIncompleteBanner.vue'
 import IndicatorDegrade from '@/pages/health/components/IndicatorDegrade.vue'
 import TrendChart from '@/pages/health/components/TrendChart.vue'
@@ -162,7 +255,17 @@ export default {
       granularity: 'raw',
       _hasLeftPage: false,
       _pendingEntry: false,
-      reportId: null
+      reportId: null,
+      // ---- P2-4 多指标同图对比 ----
+      compareMode: false,
+      compareIds: [],
+      compareItems: [],
+      compareLoading: false,
+      compareErrorState: false,
+      compareLimitHint: '',
+      _limitHintTimer: null,
+      // ---- 关注指标收藏(本地持久化,隔离维度见 favoriteScope) ----
+      favoriteIds: []
     }
   },
   computed: {
@@ -307,6 +410,66 @@ export default {
     },
     hasUnitMismatch: function() {
       return this.item && this.item.unitMismatch === true
+    },
+    // ---- P2-4 多指标同图对比 ----
+    maxCompare: function() { return MAX_COMPARE_INDICATORS },
+    /** 单指标头部卡收藏按钮态(预计算,:class 不调用带参方法) */
+    currentFavClass: function() { return this.isFavoriteDef(this.definitionId) ? 'fav-on' : '' },
+    currentFavText: function() { return this.isFavoriteDef(this.definitionId) ? '★ 已关注' : '☆ 关注' },
+    /** 收藏持久化隔离维度:用户×家庭×成员×报告类型(避免串号) */
+    favoriteScope: function() {
+      return {
+        userId: uni.getStorageSync('userId'),
+        familyId: uni.getStorageSync('familyId'),
+        memberId: this.currentMemberId,
+        sourceType: this.activeReportType
+      }
+    },
+    compareSeries: function() { return buildCompareSeries(this.compareItems) },
+    compareAllDates: function() { return buildCompareAllDates(this.compareItems) },
+    comparePeriodRows: function() { return buildComparePeriodRows(this.compareItems) },
+    compareShowGranularity: function() {
+      var items = this.compareItems || []
+      return items.some(function(it) { return it && it.chartMode === 'line_aggregated' })
+    },
+    compareHasUploadDate: function() {
+      var items = this.compareItems || []
+      return items.some(function(it) {
+        if (Array.isArray(it.points) && it.points.some(function(p) {
+          return p.dateSource && p.dateSource !== 'real' && p.dateSource !== 'unknown'
+        })) return true
+        return Array.isArray(it.missingPeriods) && it.missingPeriods.some(function(m) {
+          return m.dateSource && m.dateSource !== 'real' && m.dateSource !== 'unknown'
+        })
+      })
+    },
+    /** 对比头部:每指标 真实范围 + 收藏开关 行 */
+    compareSummaryRows: function() {
+      var self = this
+      var items = this.compareItems || []
+      return items.map(function(it) {
+        var range = computeRealRange(it)
+        var rangeText
+        if (range.count === 0) rangeText = '暂无有效数值'
+        else if (range.count === 1) rangeText = '仅 1 期 ' + roundSig(range.min) + '(无趋势)'
+        else if (!range.hasVariance) rangeText = '无波动 恒定 ' + roundSig(range.min) + (it.unit ? ' ' + it.unit : '')
+        else {
+          rangeText = '真实范围 ' + roundSig(range.min) + '~' + roundSig(range.max)
+          if (range.count === 2) rangeText += '(仅 2 期,未连线)'
+        }
+        return {
+          definitionId: it.definitionId,
+          name: it.name || '',
+          unit: it.unit || '',
+          rangeText: rangeText,
+          isFav: self.isFavoriteDef(it.definitionId)
+        }
+      })
+    },
+    compareEmptyHint: function() {
+      if (this.compareIds.length === 0) return '请选择至少 2 个指标进行同图对比'
+      var need = Math.max(1, 2 - this.compareIds.length)
+      return '已选 ' + this.compareIds.length + ' 个指标,再选 ' + need + ' 个即可同图对比(最多 ' + MAX_COMPARE_INDICATORS + ' 个)'
     }
   },
   onLoad: function(options) {
@@ -339,7 +502,15 @@ export default {
     onMemberChange: function(e) {
       var idx = Number(e.detail.value)
       var m = this.members[idx]
-      if (m) { this.currentMemberId = m.id; this.reloadAll() }
+      if (m) {
+        this.currentMemberId = m.id
+        // 切换成员:清空对比选择与收藏态(隔离维度不同,防串号)
+        this.compareIds = []
+        this.compareItems = []
+        this.compareLimitHint = ''
+        this.favoriteIds = []
+        this.reloadAll()
+      }
     },
     loadSourceTypes: function() {
       var self = this
@@ -363,10 +534,17 @@ export default {
     onReportTypeChange: function(e) {
       var idx = Number(e.detail.value)
       var o = this.reportTypeOptions[idx]
-      if (o) { this.activeReportType = o.sourceType; this.onReportTypeSelected() }
+      if (o) {
+        this.activeReportType = o.sourceType
+        this.compareIds = []
+        this.compareItems = []
+        this.compareLimitHint = ''
+        this.onReportTypeSelected()
+      }
     },
     onReportTypeSelected: function() {
       this.loadIndicatorOptions()
+      this.loadFavorites()
       this.loadTimeline()
     },
     loadIndicatorOptions: function() {
@@ -377,19 +555,17 @@ export default {
       getIndicatorChangeRanking({ subjectId: this.currentMemberId, reportType: rt, scope: 'adjacent', orderBy: 'magnitude', limit: 20 }).then(function(res) {
         var items = (res.data && res.data.items) || []
         self.indicatorOptions = items.map(function(it) {
-          return {
-            definitionId: it.definitionId,
-            name: it.name,
-            _chipClass: it.definitionId === self.definitionId ? 'chip-active' : ''
-          }
+          return { definitionId: Number(it.definitionId), name: it.name }
         })
         // 入口传入的 definitionId 不在榜单中时,追加占位(名称由 timeline 负载补全)
-        if (self.definitionId && !self.indicatorOptions.some(function(d) { return d.definitionId === self.definitionId })) {
-          self.indicatorOptions.push({ definitionId: self.definitionId, name: String(self.definitionId), _chipClass: 'chip-active' })
+        if (self.definitionId && !self.indicatorOptions.some(function(d) { return d.definitionId === Number(self.definitionId) })) {
+          self.indicatorOptions.push({ definitionId: Number(self.definitionId), name: String(self.definitionId) })
         }
+        self._refreshChipStates()
       })
     },
     loadTimeline: function() {
+      if (this.compareMode) { this.loadCompareTimeline(); return }
       var self = this
       if (!this.currentMemberId || !this.definitionId) return
       self.loading = true
@@ -405,36 +581,68 @@ export default {
           var items = (res.data && res.data.items) || []
           if (items.length > 0) {
             self.item = items[0]
-            // 选中态同步到 chip;入口 definitionId 不在榜单中时补全名称
-            var found = false
-            self.indicatorOptions = self.indicatorOptions.map(function(d) {
-              var active = d.definitionId === self.definitionId
-              if (active) { found = true; d.name = self.item.name }
-              d._chipClass = active ? 'chip-active' : ''
-              return d
-            })
+            // 入口 definitionId 不在榜单中时补全名称
+            var found = self.indicatorOptions.some(function(d) { return Number(d.definitionId) === Number(self.definitionId) })
             if (!found) {
               self.indicatorOptions.unshift({
-                definitionId: self.item.definitionId,
-                name: self.item.name,
-                _chipClass: 'chip-active'
+                definitionId: Number(self.definitionId),
+                name: self.item.name || String(self.definitionId)
               })
             }
+            self._backfillChipNames([self.item])
           } else {
             self.item = null
+            self._refreshChipStates()
           }
         } else {
           self.errorState = true
           self.item = null
+          self._refreshChipStates()
         }
       }).catch(function() {
         self.loading = false
         self.errorState = true
+        self._refreshChipStates()
+      })
+    },
+    /** 多指标同图:一次请求多 definitionIds,各自归一化后同图 */
+    loadCompareTimeline: function() {
+      var self = this
+      if (!this.currentMemberId || this.compareIds.length === 0) {
+        self.compareItems = []
+        self.compareLoading = false
+        self.compareErrorState = false
+        return
+      }
+      self.compareLoading = true
+      self.compareErrorState = false
+      getIndicatorTimeline({
+        subjectId: this.currentMemberId,
+        definitionIds: this.compareIds.slice(0, MAX_COMPARE_INDICATORS),
+        sourceType: this.activeReportType || undefined,
+        granularity: this.granularity
+      }).then(function(res) {
+        self.compareLoading = false
+        if (res.code === 200) {
+          var items = (res.data && res.data.items) || []
+          self.compareItems = items
+          if (items.length > 0) self._backfillChipNames(items)
+        } else {
+          self.compareErrorState = true
+          self.compareItems = []
+        }
+      }).catch(function() {
+        self.compareLoading = false
+        self.compareErrorState = true
+        self.compareItems = []
       })
     },
     onIndicatorTap: function(definitionId) {
-      if (definitionId === this.definitionId) return
-      this.definitionId = definitionId
+      // 对比模式:chip 变为多选勾选;普通模式:保持单指标切换(现有路径不变)
+      if (this.compareMode) { this.onCompareChipTap(definitionId); return }
+      if (definitionId === null || definitionId === undefined) return
+      if (Number(definitionId) === Number(this.definitionId)) return
+      this.definitionId = Number(definitionId)
       this.loadTimeline()
     },
     onGranularityTap: function(gran) {
@@ -443,6 +651,7 @@ export default {
       this.loadTimeline()
     },
     retryLoad: function() { this.loadTimeline() },
+    retryCompareLoad: function() { this.loadCompareTimeline() },
     getIndicatorKey: function(def) { return def ? (def.definitionId || def.name) : '' },
     getIndicatorId: function(def) { return def ? def.definitionId : null },
     getIndicatorName: function(def) { return (def && def.name) || '' },
@@ -454,6 +663,104 @@ export default {
     /** 重载全部数据(切成员 / 下拉刷新) */
     reloadAll: function() {
       this.loadSourceTypes()
+    },
+    // ---- P2-4 多指标同图对比 ----
+    onToggleCompareMode: function() {
+      this.compareMode = !this.compareMode
+      this.compareLimitHint = ''
+      if (this.compareMode) {
+        // 进入对比:默认把当前单指标带入勾选,降低认知成本
+        if (this.compareIds.length === 0 && this.definitionId) {
+          this.compareIds = [Number(this.definitionId)]
+        }
+      } else {
+        this.compareIds = []
+        this.compareItems = []
+      }
+      this._refreshChipStates()
+      if (this.compareMode) this.loadCompareTimeline()
+    },
+    onCompareChipTap: function(definitionId) {
+      var res = toggleCompareSelection(this.compareIds, definitionId, MAX_COMPARE_INDICATORS)
+      if (res.rejected) {
+        // 达上限:置灰 chip 已由 _refreshChipStates 处理,这里给出文案提示
+        this.compareLimitHint = '最多对比 ' + MAX_COMPARE_INDICATORS + ' 个指标,请先取消一个'
+        var self = this
+        if (this._limitHintTimer) clearTimeout(this._limitHintTimer)
+        this._limitHintTimer = setTimeout(function() { self.compareLimitHint = '' }, 3000)
+        return
+      }
+      this.compareLimitHint = ''
+      this.compareIds = res.ids
+      this._refreshChipStates()
+      this.loadCompareTimeline()
+    },
+    isSelectedDef: function(definitionId) {
+      return this.compareIds.indexOf(Number(definitionId)) >= 0
+    },
+    /** 刷新 chip 状态类(:class 不调用带参方法,统一预计算 _chipClass) */
+    _refreshChipStates: function() {
+      var self = this
+      var max = MAX_COMPARE_INDICATORS
+      this.indicatorOptions = (this.indicatorOptions || []).map(function(d) {
+        var id = Number(d.definitionId)
+        if (self.compareMode) {
+          if (self.compareIds.indexOf(id) >= 0) d._chipClass = 'chip-selected'
+          else if (self.compareIds.length >= max) d._chipClass = 'chip-disabled'
+          else d._chipClass = ''
+        } else {
+          d._chipClass = (id === Number(self.definitionId)) ? 'chip-active' : ''
+        }
+        return d
+      })
+    },
+    /** 用后端真实名回填 chip(占位名 → 真实名),并刷新 chip 状态 */
+    _backfillChipNames: function(items) {
+      var self = this
+      var byDef = {}
+      var arr = Array.isArray(items) ? items : []
+      for (var i = 0; i < arr.length; i++) {
+        if (arr[i] && arr[i].definitionId !== undefined && arr[i].definitionId !== null && arr[i].name) {
+          byDef[Number(arr[i].definitionId)] = arr[i].name
+        }
+      }
+      this.indicatorOptions = (this.indicatorOptions || []).map(function(d) {
+        var id = Number(d.definitionId)
+        if (byDef[id]) d.name = byDef[id]
+        return d
+      })
+      this._refreshChipStates()
+    },
+    // ---- 关注指标收藏(本地持久化) ----
+    isFavoriteDef: function(definitionId) {
+      var id = Number(definitionId)
+      if (isNaN(id)) return false
+      return this.favoriteIds.indexOf(id) >= 0
+    },
+    loadFavorites: function() {
+      this.favoriteIds = readFavorites(this.favoriteScope)
+    },
+    onToggleFavorite: function(definitionId) {
+      var res = toggleFavorite(this.favoriteScope, definitionId)
+      this.favoriteIds = res.ids
+      this._refreshChipStates()
+    },
+    // ---- 对比区 key(:key 禁止表达式) ----
+    getCompareRowKey: function(row, ri) {
+      if (!row) return 'cmp-row-' + ri
+      return 'cmp-row-' + (row.dateText || ri) + '-' + ri
+    },
+    getCompareCellKey: function(item, ci) {
+      var id = (item && item.definitionId !== undefined && item.definitionId !== null) ? item.definitionId : ci
+      return 'cmp-cell-' + id + '-' + ci
+    },
+    getCompareRowCellKey: function(row, ci) {
+      return 'cmp-rowcell-' + (row && row.dateText ? row.dateText : ci) + '-' + ci
+    },
+    getCompareBannerKey: function(item) {
+      if (!item) return 'cmp-banner-x'
+      if (item.definitionId !== undefined && item.definitionId !== null) return 'cmp-banner-' + item.definitionId
+      return 'cmp-banner-' + ((item.name) || 'x')
     }
   }
 }
@@ -467,19 +774,34 @@ export default {
 .filter-bar { display: flex; flex-direction: row; align-items: center; justify-content: space-between; gap: 16rpx; }
 .filter-item { flex: 1; display: flex; align-items: center; justify-content: center; height: 72rpx; padding: 0 16rpx; background: #f7f8fa; border-radius: 16rpx; font-size: calc(26rpx * var(--font-scale, 1)); color: #374151; }
 
+/* ---- ⑥·5 工具行(多指标对比开关) ---- */
+.tool-row { display: flex; flex-direction: row; align-items: center; justify-content: space-between; gap: 16rpx; flex-wrap: wrap; }
+.tool-group { display: flex; flex-direction: row; align-items: center; gap: 16rpx; }
+.tool-btn { display: flex; align-items: center; justify-content: center; height: 56rpx; padding: 0 24rpx; border-radius: 12rpx; font-size: calc(24rpx * var(--font-scale, 1)); color: #374151; background: #f3f4f6; border: 1rpx solid #e5e7eb; }
+.tool-btn-on { background: #FFF7ED; color: #C2410C; border-color: #F97316; font-weight: 600; }
+.tool-note { font-size: calc(22rpx * var(--font-scale, 1)); color: #6b7280; }
+.tool-note-warn { color: #c2410c; }
+
 /* ---- ⑤ 指标 chip ---- */
 .chip-scroll { display: flex; flex-direction: row; align-items: center; padding: 0 4rpx; min-height: 28rpx; white-space: nowrap; }
 .indicator-chip { display: flex; align-items: center; justify-content: center; height: 48rpx; padding: 0 24rpx; margin-right: 16rpx; border-radius: 24rpx; font-size: calc(24rpx * var(--font-scale, 1)); color: #374151; background: #f3f4f6; flex-shrink: 0; }
 .indicator-chip.chip-active { background: #F97316; color: #fff; font-weight: 600; }
+.indicator-chip.chip-selected { background: #FFF7ED; color: #C2410C; border: 1rpx solid #F97316; font-weight: 600; }
+.indicator-chip.chip-disabled { opacity: 0.45; }
+.chip-check { margin-right: 8rpx; font-weight: 700; }
+.chip-star { margin-right: 8rpx; color: #F59E0B; }
 
 /* ---- ② 指标头部卡 ---- */
 .head-card { background: #fff; border-radius: 20rpx; padding: 28rpx; box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.04); }
 .head-row { display: flex; flex-direction: row; align-items: center; justify-content: space-between; margin-bottom: 16rpx; }
+.head-side { display: flex; flex-direction: row; align-items: center; gap: 16rpx; }
 .head-name { font-size: calc(30rpx * var(--font-scale, 1)); font-weight: 700; color: #111827; }
 .status-tag { font-size: calc(22rpx * var(--font-scale, 1)); padding: 6rpx 16rpx; border-radius: 20rpx; }
 .status-tag.status-normal { background: #ecfdf5; color: #047857; }
 .status-tag.status-high { background: #fff7ed; color: #c2410c; }
 .status-tag.status-low { background: #eff6ff; color: #1d4ed8; }
+.fav-btn { font-size: calc(22rpx * var(--font-scale, 1)); color: #6b7280; padding: 6rpx 16rpx; border-radius: 20rpx; border: 1rpx solid #e5e7eb; }
+.fav-btn.fav-on { color: #B45309; border-color: #F59E0B; background: #FFFBEB; }
 .head-value-row { display: flex; flex-direction: row; align-items: baseline; margin-bottom: 8rpx; }
 .head-value { font-size: calc(48rpx * var(--font-scale, 1)); font-weight: 800; color: #111827; line-height: 1.2; }
 .head-unit { font-size: calc(24rpx * var(--font-scale, 1)); color: #6b7280; margin-left: 8rpx; }
@@ -527,7 +849,27 @@ export default {
 .period-trend { width: 160rpx; font-size: calc(24rpx * var(--font-scale, 1)); text-align: right; }
 .period-footnote { font-size: calc(22rpx * var(--font-scale, 1)); color: #9ca3af; padding: 12rpx 0 0 0; }
 
+/* ---- ⑦ 多指标同图对比区 ---- */
+.compare-head { background: #fff; border-radius: 20rpx; padding: 28rpx; box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.04); }
+.compare-note { display: block; font-size: calc(22rpx * var(--font-scale, 1)); color: #6b7280; line-height: 1.6; padding: 4rpx 0; }
+.compare-note-ref { color: #9ca3af; }
+.compare-ind-row { display: flex; flex-direction: row; align-items: center; padding: 14rpx 0; border-bottom: 1rpx solid #f3f4f6; }
+.compare-ind-star { width: 48rpx; font-size: calc(32rpx * var(--font-scale, 1)); color: #d1d5db; flex-shrink: 0; }
+.compare-ind-star-on { color: #F59E0B; }
+.compare-ind-name { font-size: calc(26rpx * var(--font-scale, 1)); font-weight: 600; color: #111827; margin-right: 12rpx; }
+.compare-ind-unit { font-size: calc(22rpx * var(--font-scale, 1)); color: #6b7280; margin-right: 16rpx; }
+.compare-ind-range { flex: 1; font-size: calc(22rpx * var(--font-scale, 1)); color: #6b7280; text-align: right; }
+
+/* ---- 对比明细表(各期真实值) ---- */
+.compare-period-header { display: flex; flex-direction: row; padding: 12rpx 0; border-bottom: 1rpx solid #e5e7eb; }
+.compare-period-row { display: flex; flex-direction: row; align-items: center; padding: 14rpx 0; border-bottom: 1rpx solid #f3f4f6; }
+.compare-period-row:last-child { border-bottom: none; }
+.compare-cell { flex: 1; font-size: calc(22rpx * var(--font-scale, 1)); color: #111827; text-align: center; overflow: hidden; }
+.compare-cell-name { font-weight: 600; color: #374151; }
+.compare-cell-date { width: 140rpx; flex: none; text-align: left; color: #374151; font-weight: 600; }
+.compare-cell-missing { color: #9ca3af; }
+
 /* ---- ⑥ 合规 footer ---- */
 .footer { padding: 24rpx 0; }
 .footer-text { font-size: calc(22rpx * var(--font-scale, 1)); color: #9ca3af; text-align: center; line-height: 1.6; }
-</style>
+</style>

+ 261 - 0
cfc-frontend/utils/indicator-compare.js

@@ -0,0 +1,261 @@
+/* ==============================================================
+ * utils/indicator-compare.js - 多指标同图归一化对比纯函数
+ * 规则来源:PRD §4.3 P2-4 / design §1.2.1 第二段 / design §1092
+ * 职责:归一化算法(min/max → [0,1])、图例真实范围、多指标上限校验、对比明细
+ * 合规红线:
+ *   - 归一化仅用于同图比较,真实数值永不丢弃(图例给真实区间、明细表读回真实值)
+ *   - 期数不足不连假线:n<3 的 series drawLine=false(TrendChart 只画点不连线)
+ *   - 缺失期由调用方按 allPeriodDates 断线,不插值
+ * ============================================================== */
+import { roundSig, formatPeriodDate } from './indicator-timeline.js'
+
+/** 多指标同图上限(design §1092:definitionIds 由调用方控制在 ≤ 3 个;UI 硬性限制) */
+export const MAX_COMPARE_INDICATORS = 3
+
+/** 同图对比色板(颜色不是唯一区分手段,图例同时给 名称+单位+真实范围) */
+export const COMPARE_COLORS = ['#F97316', '#0EA5E9', '#10B981']
+
+/**
+ * 取点的有效数值(优先 numericValue,回退 value);无效返回 null
+ * @param {Object} point
+ * @returns {number|null}
+ */
+export function pointNumeric(point) {
+  if (!point) return null
+  var raw = (point.numericValue !== undefined && point.numericValue !== null && point.numericValue !== '')
+    ? point.numericValue : point.value
+  if (raw === undefined || raw === null || raw === '') return null
+  var n = Number(raw)
+  if (isNaN(n) || !isFinite(n)) return null
+  return n
+}
+
+/**
+ * 线性归一化到 [0,1]
+ * - min === max(恒定值/单点)→ 0.5,由图例如实标注「无波动」或「仅 1 期」
+ * - 越界值夹到 [0,1]
+ * @param {number|string} value
+ * @param {number|null} min
+ * @param {number|null} max
+ * @returns {number|null}
+ */
+export function normalizeValue(value, min, max) {
+  if (value === null || value === undefined || value === '') return null
+  var v = Number(value)
+  if (isNaN(v) || !isFinite(v)) return null
+  if (min === null || min === undefined || max === null || max === undefined) return null
+  if (max === min) return 0.5
+  var r = (v - min) / (max - min)
+  if (r < 0) r = 0
+  if (r > 1) r = 1
+  return r
+}
+
+/**
+ * 计算某指标在自身 points(当前筛选范围)上的真实范围
+ * @param {Object} item timeline item(含 points[])
+ * @returns {{min:number|null, max:number|null, count:number, hasVariance:boolean}}
+ *   count = 有效数值点数;hasVariance = count≥2 且 min<max(有波动)
+ */
+export function computeRealRange(item) {
+  var points = (item && Array.isArray(item.points)) ? item.points : []
+  var min = null
+  var max = null
+  var count = 0
+  for (var i = 0; i < points.length; i++) {
+    var v = pointNumeric(points[i])
+    if (v === null) continue
+    count++
+    if (min === null || v < min) min = v
+    if (max === null || v > max) max = v
+  }
+  return { min: min, max: max, count: count, hasVariance: count >= 2 && max !== min }
+}
+
+/**
+ * 图例文本:指标名 + 单位 + 真实范围(min~max)
+ *   无波动(恒定值,count≥2 且 min==max)→ 「无波动 恒定 x unit」
+ *   仅 1 期 → 「仅 1 期 x(无趋势)」,不假装有波动
+ *   仅 2 期 → 追加「(仅 2 期,未连线)」,与红线「n=2 不画折线」呼应
+ * @param {Object} item
+ * @param {Object} [range] 预先算好的范围,缺省内部重算
+ * @returns {string}
+ */
+export function buildLegendText(item, range) {
+  var name = (item && item.name) || ''
+  var unit = (item && item.unit) || ''
+  var r = range || computeRealRange(item)
+  var base = name + (unit ? '(' + unit + ')' : '')
+  if (r.count === 0) return base + ' · 暂无数据'
+  if (r.count === 1) {
+    return base + ' · 仅 1 期 ' + (r.min !== null ? roundSig(r.min) : '--') + '(无趋势)'
+  }
+  if (!r.hasVariance) {
+    return base + ' · 无波动 恒定 ' + (r.min !== null ? roundSig(r.min) : '--') + (unit ? ' ' + unit : '')
+  }
+  var rangeText = base + ' · 真实范围 ' + roundSig(r.min) + '~' + roundSig(r.max)
+  if (r.count === 2) rangeText += '(仅 2 期,未连线)'
+  return rangeText
+}
+
+/**
+ * 构造归一化后的多 series(供 TrendChart 绘制)
+ * 每个 series 的 points[].value 为归一化 [0,1](保留真实 numericValue 供读数);
+ * series 携带图例元信息(unit / realMin / realMax / hasVariance / legendText)与
+ * drawLine(有效点数 <3 时不连线,避免两点连线暗示假趋势)。
+ * 无有效数值点的指标被剔除(不画假线)。
+ * @param {Array} items timeline items 数组(一次请求多 definitionIds 的返回)
+ * @param {Array} [colors]
+ * @returns {Array} TrendChart series 数组
+ */
+export function buildCompareSeries(items, colors) {
+  var palette = (Array.isArray(colors) && colors.length > 0) ? colors : COMPARE_COLORS
+  var list = Array.isArray(items) ? items : []
+  var out = []
+  for (var i = 0; i < list.length; i++) {
+    var item = list[i]
+    if (!item) continue
+    var range = computeRealRange(item)
+    if (range.count === 0) continue
+    var src = Array.isArray(item.points) ? item.points : []
+    var points = []
+    for (var j = 0; j < src.length; j++) {
+      var p = src[j]
+      if (!p || !p.reportDate) continue
+      var v = pointNumeric(p)
+      if (v === null) continue
+      points.push({
+        reportDate: String(p.reportDate).slice(0, 10),
+        value: normalizeValue(v, range.min, range.max),
+        numericValue: v,
+        unit: p.unit,
+        dateSource: p.dateSource
+      })
+    }
+    if (points.length === 0) continue
+    out.push({
+      name: item.name || '',
+      color: palette[out.length % palette.length],
+      points: points,
+      definitionId: item.definitionId,
+      unit: item.unit || '',
+      realMin: range.min,
+      realMax: range.max,
+      realCount: range.count,
+      hasVariance: range.hasVariance,
+      drawLine: points.length >= 3,
+      legendText: buildLegendText(item, range)
+    })
+  }
+  return out
+}
+
+/**
+ * X 轴日期全集:所有选中指标的 (points ∪ missingPeriods) 日期并集,升序
+ * 用于等距布局与缺失期断线(某指标在某期无值 → 该 series 断线,不插值)
+ * @param {Array} items
+ * @returns {string[]}
+ */
+export function buildCompareAllDates(items) {
+  var set = {}
+  var list = Array.isArray(items) ? items : []
+  for (var i = 0; i < list.length; i++) {
+    var item = list[i]
+    if (!item) continue
+    var pts = Array.isArray(item.points) ? item.points : []
+    for (var j = 0; j < pts.length; j++) {
+      if (pts[j] && pts[j].reportDate) set[String(pts[j].reportDate).slice(0, 10)] = true
+    }
+    var mis = Array.isArray(item.missingPeriods) ? item.missingPeriods : []
+    for (var k = 0; k < mis.length; k++) {
+      if (mis[k] && mis[k].reportDate) set[String(mis[k].reportDate).slice(0, 10)] = true
+    }
+  }
+  return Object.keys(set).sort()
+}
+
+/**
+ * 构建对比明细表行:按统一日期倒序(新→旧),每行列出各指标的该期真实值
+ * 缺失期 → 「该期未检测」;上传日 → dateText 加 * 并在行级标记(hasUploadMark)
+ * @param {Array} items
+ * @returns {Array<{dateText:string, hasUploadMark:boolean, cells:Array<{name:string, valueText:string, isMissing:boolean}>}>}
+ */
+export function buildComparePeriodRows(items) {
+  var list = Array.isArray(items) ? items : []
+  var allDates = buildCompareAllDates(list)
+  var refDate = allDates.length > 0 ? allDates[allDates.length - 1] : ''
+  allDates.sort(function(a, b) { return a < b ? 1 : (a > b ? -1 : 0) })
+  var rows = []
+  for (var i = 0; i < allDates.length; i++) {
+    var dateStr = allDates[i]
+    var cells = []
+    var hasUpload = false
+    for (var k = 0; k < list.length; k++) {
+      var item = list[k]
+      var name = (item && item.name) || ''
+      var cell = { name: name, valueText: '该期未检测', isMissing: true, upload: false }
+      var pts = (item && Array.isArray(item.points)) ? item.points : []
+      for (var j = 0; j < pts.length; j++) {
+        var p = pts[j]
+        if (!p || String(p.reportDate).slice(0, 10) !== dateStr) continue
+        var v = pointNumeric(p)
+        if (v !== null) {
+          cell.valueText = roundSig(v) + ((p.unit || (item && item.unit)) ? ' ' + (p.unit || item.unit) : '')
+          cell.isMissing = false
+        } else {
+          cell.valueText = (p.value !== undefined && p.value !== null)
+            ? String(p.value) + ((p.unit || (item && item.unit)) ? ' ' + (p.unit || item.unit) : '') : '该期未检测'
+          cell.isMissing = true
+        }
+        cell.upload = !!(p.dateSource && p.dateSource !== 'real' && p.dateSource !== 'unknown')
+        break
+      }
+      if (cell.isMissing) {
+        var mis = (item && Array.isArray(item.missingPeriods)) ? item.missingPeriods : []
+        for (var m = 0; m < mis.length; m++) {
+          if (mis[m] && String(mis[m].reportDate).slice(0, 10) === dateStr) {
+            cell.upload = !!(mis[m].dateSource && mis[m].dateSource !== 'real' && mis[m].dateSource !== 'unknown')
+            break
+          }
+        }
+      }
+      if (cell.upload) hasUpload = true
+      cells.push(cell)
+    }
+    rows.push({
+      dateText: formatPeriodDate(dateStr, refDate) + (hasUpload ? ' *' : ''),
+      hasUploadMark: hasUpload,
+      cells: cells
+    })
+  }
+  return rows
+}
+
+/**
+ * 勾选/取消勾选指标(多选硬性上限 ≤ MAX_COMPARE_INDICATORS)
+ * @param {Array} currentIds 当前已选 definitionId
+ * @param {number|string} definitionId 本次点击的指标
+ * @param {number} [max] 上限,缺省 MAX_COMPARE_INDICATORS
+ * @returns {{ids:number[], changed:boolean, rejected:boolean}}
+ *   rejected=true 表示已达上限被拒绝(调用方据此提示用户)
+ */
+export function toggleCompareSelection(currentIds, definitionId, max) {
+  var limit = (typeof max === 'number' && max > 0) ? max : MAX_COMPARE_INDICATORS
+  var ids = Array.isArray(currentIds) ? currentIds.slice() : []
+  if (definitionId === null || definitionId === undefined || definitionId === '') {
+    return { ids: ids, changed: false, rejected: false }
+  }
+  var target = Number(definitionId)
+  if (isNaN(target)) return { ids: ids, changed: false, rejected: false }
+  var idx = -1
+  for (var i = 0; i < ids.length; i++) {
+    if (Number(ids[i]) === target) { idx = i; break }
+  }
+  if (idx >= 0) {
+    ids.splice(idx, 1)
+    return { ids: ids, changed: true, rejected: false }
+  }
+  if (ids.length >= limit) return { ids: ids, changed: false, rejected: true }
+  ids.push(target)
+  return { ids: ids, changed: true, rejected: false }
+}

+ 99 - 0
cfc-frontend/utils/indicator-favorite.js

@@ -0,0 +1,99 @@
+/* ==============================================================
+ * utils/indicator-favorite.js - 关注指标收藏(本地持久化)
+ * ⚠️ 当前为本地持久化(小程序 Storage),后续若需跨端同步再接后端。
+ *    本文件注释即契约:不要在此接后端,等有跨端同步需求时再改。
+ * 隔离维度:登录用户 userId + 家庭 familyId + 成员 memberId + 报告类型 sourceType。
+ *    同一存储 key 只对应一个「用户×家庭×成员×报告类型」视角,避免串号
+ *    (不同账号/不同成员/不同报告类型之间的收藏互不干扰)。
+ * 持久化结构:key → number[](definitionId 列表)
+ * ============================================================== */
+
+const KEY_PREFIX = 'cfc:indicator:fav'
+
+/**
+ * 拼装存储 key(维度隔离;缺失维度用占位符,避免不同账号/成员互相覆盖)
+ * @param {{userId?:*, familyId?:*, memberId?:*, sourceType?:*}} scope
+ * @returns {string}
+ */
+export function buildFavoriteKey(scope) {
+  var s = scope || {}
+  var userId = (s.userId === undefined || s.userId === null || s.userId === '') ? 'anon' : String(s.userId)
+  var familyId = (s.familyId === undefined || s.familyId === null || s.familyId === '') ? 'nofamily' : String(s.familyId)
+  var memberId = (s.memberId === undefined || s.memberId === null || s.memberId === '') ? 'nomember' : String(s.memberId)
+  var sourceType = (s.sourceType === undefined || s.sourceType === null || s.sourceType === '') ? 'all' : String(s.sourceType)
+  return KEY_PREFIX + ':' + userId + ':' + familyId + ':' + memberId + ':' + sourceType
+}
+
+/** 数字数组去重、丢弃非法值 */
+function normalizeIds(val) {
+  if (val === undefined || val === null || val === '') return []
+  if (typeof val === 'string') {
+    try { val = JSON.parse(val) } catch (e) { return [] }
+  }
+  if (!Array.isArray(val)) return []
+  var out = []
+  var seen = {}
+  for (var i = 0; i < val.length; i++) {
+    var n = Number(val[i])
+    if (isNaN(n)) continue
+    if (seen[n]) continue
+    seen[n] = true
+    out.push(n)
+  }
+  return out
+}
+
+/**
+ * 读取某视角的收藏指标 definitionId 列表
+ * @param {Object} scope
+ * @returns {number[]}
+ */
+export function readFavorites(scope) {
+  var key = buildFavoriteKey(scope)
+  var val
+  try {
+    val = uni.getStorageSync(key)
+  } catch (e) {
+    return []
+  }
+  return normalizeIds(val)
+}
+
+/**
+ * 写入某视角的收藏列表
+ * @param {Object} scope
+ * @param {number[]} ids
+ * @returns {number[]} 写入后的规范化列表
+ */
+export function writeFavorites(scope, ids) {
+  var key = buildFavoriteKey(scope)
+  var arr = normalizeIds(ids)
+  try {
+    uni.setStorageSync(key, arr)
+  } catch (e) {
+    // 存储失败静默(收藏是增强功能,不影响主流程)
+    console.warn('[indicator-favorite] 写入失败', key, e)
+  }
+  return arr
+}
+
+/**
+ * 切换某指标的收藏状态(加入/取消收藏)
+ * @param {Object} scope
+ * @param {number|string} definitionId
+ * @returns {{ids:number[], added:boolean}} added=true 表示新加入收藏
+ */
+export function toggleFavorite(scope, definitionId) {
+  var id = Number(definitionId)
+  var ids = readFavorites(scope)
+  if (isNaN(id)) return { ids: ids, added: false }
+  var idx = ids.indexOf(id)
+  if (idx >= 0) {
+    ids.splice(idx, 1)
+    writeFavorites(scope, ids)
+    return { ids: ids, added: false }
+  }
+  ids.push(id)
+  writeFavorites(scope, ids)
+  return { ids: ids, added: true }
+}