physical.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. <template>
  2. <CustomNav title="体格数据" leftType="back" />
  3. <view class="page">
  4. <view class="header">
  5. <view class="month-selector">
  6. <button class="btn" @click="prevPeriod">‹</button>
  7. <view class="period-controls">
  8. <picker mode="multiSelector" :value="pickerValue" :range="pickerRange" @change="onPickerChange">
  9. <view class="month-label">{{ displayPeriod }}</view>
  10. </picker>
  11. <view class="view-toggle">
  12. <button :class="['toggle-btn', { active: viewMode === 'month' }]" @click="setViewMode('month')">月</button>
  13. <button :class="['toggle-btn', { active: viewMode === 'week' }]" @click="setViewMode('week')">周</button>
  14. </view>
  15. <view class="metric-toggle" style="margin-top:8rpx; display:flex; gap:8rpx;">
  16. <button :class="['toggle-btn', { active: selectedMetric === 'all' }]" @click.prevent="selectedMetric = 'all'">全部</button>
  17. <button :class="['toggle-btn', { active: selectedMetric === 'height' }]" @click.prevent="selectedMetric = 'height'">身高</button>
  18. <button :class="['toggle-btn', { active: selectedMetric === 'weight' }]" @click.prevent="selectedMetric = 'weight'">体重</button>
  19. <button :class="['toggle-btn', { active: selectedMetric === 'bmi' }]" @click.prevent="selectedMetric = 'bmi'">BMI</button>
  20. </view>
  21. </view>
  22. <button class="btn" @click="nextPeriod">›</button>
  23. </view>
  24. </view>
  25. <!-- 趋势图 - 简化canvas设置 -->
  26. <view class="chart-wrap">
  27. <view class="chart-header">本月趋势</view>
  28. <canvas
  29. canvas-id="bpChart"
  30. id="bpChart"
  31. class="chart-canvas"
  32. :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
  33. ></canvas>
  34. </view>
  35. <view class="content">
  36. <view class="summary">共 {{ records.length }} 条记录,本月平均:{{ averageHeight }} cm / {{ averageWeight }} kg;平均 BMI:{{ averageBMI }}</view>
  37. <view class="list">
  38. <view v-if="records.length === 0" class="empty">暂无记录</view>
  39. <view v-for="item in records" :key="item.id" class="list-item" :style="{ backgroundColor: getItemColor(item.h, item.w) }">
  40. <view class="date">{{ item.date }}</view>
  41. <view class="value">{{ item.h }} cm / {{ item.w }} kg · BMI {{ item.bmi }}</view>
  42. </view>
  43. </view>
  44. </view>
  45. <!-- 删除了添加按钮和相关功能,因为这是公共页面,仅供医生或家属查看患者健康数据 -->
  46. <!-- Removed add button and related functions because this is a public page for doctors or family members to view patient health data -->
  47. </view>
  48. </template>
  49. <script setup lang="ts">
  50. import { ref, computed, onMounted, watch, nextTick, onBeforeUnmount, getCurrentInstance } from 'vue'
  51. import { onShow, onLoad } from '@dcloudio/uni-app'
  52. import { createUChart } from '@/composables/useUChart'
  53. import CustomNav from '@/components/custom-nav.vue'
  54. import ScaleRuler from '@/components/scale-ruler.vue'
  55. import { getWeekStart, getWeekEnd, formatDisplayDate, formatPickerDate, daysInMonth, getTodayStart, isAfterTodayDate, isMonthAfterToday, isWeekAfterToday } from '@/utils/date'
  56. import { getWindowWidth, rpxToPx } from '@/utils/platform'
  57. import { listPhysicalByBoundUser } from '@/api/physical'
  58. type RecordItem = { id: string; date: string; h: number; w: number; bmi: number }
  59. // 当前展示年月
  60. const current = ref(new Date())
  61. // 使用 multiSelector 的索引形式: [yearOffset从2000起, month(0-11)]
  62. const pickerValue = ref([current.value.getFullYear() - 2000, current.value.getMonth()])
  63. // 视图模式:'month' 或 'week'
  64. const viewMode = ref<'month' | 'week'>('month')
  65. // 年月选择器的选项范围(与 height/weight 保持一致)
  66. const pickerRange = ref([
  67. Array.from({ length: 50 }, (_, i) => `${2000 + i}年`),
  68. Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
  69. ])
  70. // 明确的canvas尺寸(将由 getCanvasSize 初始化以匹配设备宽度)
  71. const canvasWidth = ref(700) // 初始值,会在 mounted 时覆盖
  72. const canvasHeight = ref(320)
  73. // 获取Canvas实际尺寸的函数 - 参考微信小程序示例使用固定尺寸
  74. function getCanvasSize(): Promise<{ width: number; height: number }> {
  75. return new Promise(async (resolve) => {
  76. const width = await getWindowWidth().catch(() => 375)
  77. const height = Math.round((320 / 750) * width)
  78. resolve({ width, height })
  79. })
  80. }
  81. // 使用 formatPickerDate 从 src/utils/date.ts
  82. const displayYear = computed(() => current.value.getFullYear())
  83. const displayMonth = computed(() => current.value.getMonth() + 1)
  84. // 显示周期(支持月/周)
  85. const displayPeriod = computed(() => {
  86. if (viewMode.value === 'month') {
  87. return `${displayYear.value}年 ${displayMonth.value}月`
  88. } else {
  89. const weekStart = getWeekStart(current.value)
  90. const weekEnd = getWeekEnd(current.value)
  91. return `${formatDisplayDate(weekStart)} - ${formatDisplayDate(weekEnd)}`
  92. }
  93. })
  94. const records = ref<RecordItem[]>([])
  95. const patientId = ref<string | null>(null)
  96. const bindingType = ref<string | null>(null)
  97. // 页面加载时检查是否传入了患者ID和绑定类型
  98. onLoad((options) => {
  99. if (options && options.patientId && options.bindingType) {
  100. patientId.value = options.patientId
  101. bindingType.value = options.bindingType
  102. } else {
  103. // 如果没有传入patientId或bindingType,则弹窗提示并返回上一页
  104. uni.showToast({
  105. title: '未携带必要参数',
  106. icon: 'none',
  107. duration: 2000
  108. })
  109. setTimeout(() => {
  110. uni.navigateBack()
  111. }, 2000)
  112. }
  113. })
  114. // 将 records 聚合为每天一个点(取最新记录)
  115. function aggregateDaily(recordsArr: RecordItem[], year: number, month: number) {
  116. const map = new Map<number, RecordItem>()
  117. for (const r of recordsArr) {
  118. const parts = r.date.split('-')
  119. if (parts.length >= 3) {
  120. const y = parseInt(parts[0], 10)
  121. const m = parseInt(parts[1], 10) - 1
  122. const d = parseInt(parts[2], 10)
  123. if (y === year && m === month) {
  124. // 覆盖同一天,保留最新的(数组头部为最新)
  125. map.set(d, r)
  126. }
  127. }
  128. }
  129. // 返回按日索引的数组
  130. return map
  131. }
  132. async function fetchRecords() {
  133. let startTime = ''
  134. let endTime = ''
  135. if (viewMode.value === 'month') {
  136. const y = current.value.getFullYear()
  137. const m = current.value.getMonth()
  138. startTime = new Date(y, m, 1).toISOString()
  139. // 将结束时间设为当日 23:59:59.999,避免 ISO 时间为当天 00:00
  140. const endDate = new Date(y, m + 1, 0)
  141. endDate.setHours(23, 59, 59, 999)
  142. endTime = endDate.toISOString()
  143. } else {
  144. const weekStart = getWeekStart(current.value)
  145. const weekEnd = getWeekEnd(current.value)
  146. // 确保周结束时间也是该日的 23:59:59.999
  147. startTime = weekStart.toISOString()
  148. try {
  149. const we = new Date(weekEnd)
  150. we.setHours(23, 59, 59, 999)
  151. endTime = we.toISOString()
  152. } catch (e) {
  153. endTime = weekEnd.toISOString()
  154. }
  155. }
  156. // 在发送请求前显示 loading 提示;使用 finally 确保在任何情况下都隐藏
  157. try {
  158. if (typeof uni !== 'undefined' && uni.showLoading) uni.showLoading({ title: '加载中...' })
  159. } catch (e) {
  160. // ignore
  161. }
  162. try {
  163. // 使用新的 ByBoundUser 接口
  164. if (patientId.value && bindingType.value) {
  165. const params = {
  166. patientUserId: patientId.value,
  167. bindingType: bindingType.value,
  168. baseQueryRequest: {
  169. pageNum: 1,
  170. pageSize: 100,
  171. startTime,
  172. endTime
  173. }
  174. }
  175. const res = await listPhysicalByBoundUser(params)
  176. if (res.statusCode === 401) {
  177. // Token 无效,清除并跳转登录
  178. uni.removeStorageSync('token')
  179. uni.removeStorageSync('role')
  180. uni.reLaunch({ url: '/pages/public/login/index' })
  181. return
  182. }
  183. if ((res.data as any) && (res.data as any).code === 200) {
  184. const apiRecords = (res.data as any).data?.records || []
  185. // 将后端记录映射为前端格式:确保 height/weight 为数字,优先使用后端返回的 bmi,若无则在客户端计算并保留 1 位小数
  186. records.value = apiRecords.map((item: any) => {
  187. const h = item.height == null ? 0 : Number(item.height)
  188. const w = item.weight == null ? 0 : Number(item.weight)
  189. let bmiVal: number | null = null
  190. if (item.bmi != null && item.bmi !== '') {
  191. const parsed = Number(item.bmi)
  192. if (!Number.isNaN(parsed)) bmiVal = Math.round(parsed * 10) / 10
  193. }
  194. if (bmiVal == null && h > 0 && w > 0) {
  195. bmiVal = Math.round((w / ((h / 100) * (h / 100))) * 10) / 10
  196. }
  197. return {
  198. id: String(item.id),
  199. date: formatDisplayDate(new Date(item.measureTime)),
  200. h,
  201. w,
  202. bmi: bmiVal ?? 0
  203. }
  204. })
  205. rebuildChart()
  206. } else {
  207. console.error('Fetch records failed', res.data)
  208. }
  209. }
  210. } catch (e) {
  211. console.error('Fetch records error', e)
  212. } finally {
  213. try {
  214. if (typeof uni !== 'undefined' && uni.hideLoading) uni.hideLoading()
  215. } catch (e) {
  216. // ignore
  217. }
  218. }
  219. }
  220. const averageHeight = computed(() => {
  221. if (records.value.length === 0) return '--'
  222. const sum = records.value.reduce((s, r) => s + r.h, 0)
  223. return Math.round(sum / records.value.length)
  224. })
  225. const averageWeight = computed(() => {
  226. if (records.value.length === 0) return '--'
  227. const sum = records.value.reduce((s, r) => s + r.w, 0)
  228. return Math.round(sum / records.value.length)
  229. })
  230. const averageBMI = computed(() => {
  231. if (records.value.length === 0) return '--'
  232. const sum = records.value.reduce((s, r) => s + (r.bmi || 0), 0)
  233. return Math.round((sum / records.value.length) * 10) / 10
  234. })
  235. // 根据血压值获取颜色
  236. function getItemColor(h: number, w: number): string {
  237. // 根据 BMI 简单分类
  238. if (!h || !w) return '#ffffff'
  239. const bmi = w / ((h / 100) * (h / 100))
  240. if (bmi < 18.5) return '#fff3cd' // 偏瘦 - 黄
  241. if (bmi < 25) return '#e8f5e8' // 正常 - 绿
  242. if (bmi < 30) return '#fff3cd' // 超重 - 黄
  243. return '#f8d7da' // 肥胖 - 红
  244. }
  245. // 使用共享日期工具 (src/utils/date.ts)
  246. // 使用可复用的 chart composable,支持多序列
  247. const vm = getCurrentInstance()
  248. // 选择显示的指标:'all' | 'height' | 'weight' | 'bmi'
  249. const selectedMetric = ref<'all'|'height'|'weight'|'bmi'>('all')
  250. let bpChart: any = null
  251. function createChartForMetric(metric: 'all'|'height'|'weight'|'bmi') {
  252. const seriesMap: Record<string, { names: string[]; accessors: Array<(r:any)=>number>; colors: string[] }> = {
  253. all: { names: ['身高','体重','BMI'], accessors: [ (r: RecordItem) => r.h, (r: RecordItem) => r.w, (r: RecordItem) => r.bmi ], colors: ['#ff6a00', '#007aff', '#28c76f'] },
  254. height: { names: ['身高'], accessors: [ (r: RecordItem) => r.h ], colors: ['#ff6a00'] },
  255. weight: { names: ['体重'], accessors: [ (r: RecordItem) => r.w ], colors: ['#007aff'] },
  256. bmi: { names: ['BMI'], accessors: [ (r: RecordItem) => r.bmi ], colors: ['#28c76f'] }
  257. }
  258. const cfg = seriesMap[metric]
  259. return createUChart({
  260. canvasId: 'bpChart',
  261. vm,
  262. getCanvasSize,
  263. seriesNames: cfg.names,
  264. valueAccessors: cfg.accessors,
  265. colors: cfg.colors
  266. })
  267. }
  268. // 延迟创建 chart:在 mounted 时先读取路由参数(metric),然后创建 chart 并绘制
  269. function initMetricFromRoute() {
  270. try {
  271. // 在 uni-app 中,可通过 getCurrentPages 获取当前页面的 options(包含 query)
  272. const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
  273. const currentPage = pages[pages.length - 1] || {}
  274. const opts = (currentPage && (currentPage as any).options) ? (currentPage as any).options : {}
  275. const metricParam = opts.metric || opts?.metric
  276. if (metricParam && ['all', 'height', 'weight', 'bmi'].includes(metricParam)) {
  277. ;(selectedMetric as any).value = metricParam
  278. }
  279. } catch (e) {
  280. console.warn('initMetricFromRoute error', e)
  281. }
  282. }
  283. onMounted(() => {
  284. // 延迟确保DOM渲染完成并设置canvas尺寸
  285. setTimeout(async () => {
  286. await nextTick()
  287. try {
  288. const size = await getCanvasSize()
  289. canvasWidth.value = size.width
  290. canvasHeight.value = size.height
  291. } catch (e) {
  292. console.warn('getCanvasSize failed on mounted', e)
  293. }
  294. // 先从路由读取 metric(如果有),然后创建 chart
  295. initMetricFromRoute()
  296. await fetchRecords()
  297. try {
  298. if (!bpChart) bpChart = createChartForMetric(selectedMetric.value)
  299. } catch (e) {
  300. console.warn('createChartForMetric failed', e)
  301. }
  302. try {
  303. if (bpChart && bpChart.draw) await bpChart.draw(records, current, viewMode)
  304. } catch (e) {
  305. console.warn('bpChart draw failed', e)
  306. }
  307. }, 500)
  308. })
  309. // 如果在微信小程序端且未登录,自动跳转到登录页
  310. onShow(() => {
  311. const token = uni.getStorageSync('token')
  312. if (!token) {
  313. // 使用 uni.reLaunch 替代 navigateTo,确保页面栈被清空
  314. uni.reLaunch({ url: '/pages/public/login/index' })
  315. }
  316. })
  317. // 监听并更新图表(轻微去抖)
  318. watch([() => current.value], async () => {
  319. setTimeout(async () => {
  320. await bpChart.update(records, current, viewMode)
  321. }, 100)
  322. })
  323. watch([() => records.value], async () => {
  324. setTimeout(async () => {
  325. // 如果图表实例已被替换,根据 current selectedMetric 的 chart 实例更新
  326. try {
  327. if (bpChart && bpChart.update) await bpChart.update(records, current, viewMode)
  328. } catch (e) {
  329. console.warn('bpChart update failed', e)
  330. }
  331. }, 100)
  332. }, { deep: true })
  333. // 监听 selectedMetric 变化,重建图表以使用不同的 series 配置
  334. watch(() => selectedMetric.value, async (val) => {
  335. try {
  336. if (bpChart && bpChart.destroy) {
  337. try { bpChart.destroy() } catch (e) { /* ignore */ }
  338. }
  339. bpChart = createChartForMetric(val)
  340. // small delay to ensure DOM/canvas availability
  341. await nextTick()
  342. try { await bpChart.draw(records, current, viewMode) } catch (e) { console.warn('draw after metric change failed', e) }
  343. } catch (e) {
  344. console.warn('selectedMetric watch error', e)
  345. }
  346. })
  347. onBeforeUnmount(() => {
  348. try { bpChart.destroy() } catch (e) { console.warn('bpChart destroy error', e) }
  349. })
  350. // 强制重建图表(用于切换月份时彻底刷新)
  351. async function rebuildChart() {
  352. try { if (bpChart && bpChart.rebuild) await bpChart.rebuild(records, current, viewMode) } catch (e) { console.warn('rebuildChart failed', e) }
  353. }
  354. // 周/月周期导航与 Picker 处理
  355. async function prevPeriod() {
  356. const d = new Date(current.value)
  357. if (viewMode.value === 'month') {
  358. d.setMonth(d.getMonth() - 1)
  359. } else {
  360. d.setDate(d.getDate() - 7)
  361. }
  362. current.value = d
  363. pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
  364. await fetchRecords()
  365. await rebuildChart()
  366. }
  367. async function nextPeriod() {
  368. const d = new Date(current.value)
  369. if (viewMode.value === 'month') {
  370. d.setMonth(d.getMonth() + 1)
  371. if (isMonthAfterToday(d)) {
  372. uni.showToast && uni.showToast({ title: '不能查看未来的日期', icon: 'none' })
  373. return
  374. }
  375. } else {
  376. d.setDate(d.getDate() + 7)
  377. if (isWeekAfterToday(d)) {
  378. uni.showToast && uni.showToast({ title: '不能查看未来的日期', icon: 'none' })
  379. return
  380. }
  381. }
  382. current.value = d
  383. pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
  384. await fetchRecords()
  385. await rebuildChart()
  386. }
  387. async function setViewMode(mode: 'month' | 'week') {
  388. if (viewMode.value !== mode) {
  389. viewMode.value = mode
  390. await fetchRecords()
  391. await rebuildChart()
  392. }
  393. }
  394. async function onPickerChange(e: any) {
  395. const val = e?.detail?.value || e
  396. if (Array.isArray(val) && val.length >= 2) {
  397. const y = 2000 + Number(val[0])
  398. const m = Number(val[1])
  399. let d = new Date(y, m, 1)
  400. if (isMonthAfterToday(d)) {
  401. const today = getTodayStart()
  402. uni.showToast && uni.showToast({ title: '不能选择未来的月份,已切换到当前月份', icon: 'none' })
  403. d = new Date(today.getFullYear(), today.getMonth(), 1)
  404. pickerValue.value = [today.getFullYear() - 2000, today.getMonth()]
  405. } else {
  406. pickerValue.value = [Number(val[0]), Number(val[1])]
  407. }
  408. current.value = d
  409. await fetchRecords()
  410. await rebuildChart()
  411. }
  412. }
  413. // 删除了添加逻辑,因为这是公共页面,仅供医生或家属查看患者健康数据
  414. // Removed add logic because this is a public page for doctors or family members to view patient health data
  415. // 删除了删除记录功能,因为这是公共页面,仅供医生或家属查看患者健康数据
  416. // Removed delete record function because this is a public page for doctors or family members to view patient health data
  417. </script>
  418. <style scoped>
  419. .page {
  420. min-height: calc(100vh);
  421. padding-top: calc(var(--status-bar-height) + 44px);
  422. background: #f5f6f8;
  423. box-sizing: border-box
  424. }
  425. .header {
  426. padding: 20rpx 40rpx
  427. }
  428. .month-selector {
  429. display: flex;
  430. align-items: center;
  431. justify-content: center;
  432. gap: 12rpx
  433. }
  434. .period-controls {
  435. display: flex;
  436. flex-direction: column;
  437. align-items: center;
  438. gap: 8rpx;
  439. }
  440. .view-toggle {
  441. display: flex;
  442. gap: 4rpx;
  443. }
  444. .toggle-btn {
  445. padding: 4rpx 12rpx;
  446. border: 1rpx solid #ddd;
  447. background: #f5f5f5;
  448. color: #666;
  449. border-radius: 6rpx;
  450. font-size: 24rpx;
  451. min-width: 60rpx;
  452. text-align: center;
  453. }
  454. .toggle-btn.active {
  455. background: #ff6a00;
  456. color: #fff;
  457. border-color: #ff6a00;
  458. }
  459. .month-label {
  460. font-size: 34rpx;
  461. color: #333
  462. }
  463. .btn {
  464. background: transparent;
  465. border: none;
  466. font-size: 36rpx;
  467. color: #666
  468. }
  469. .content {
  470. padding: 20rpx 24rpx 100rpx 24rpx
  471. }
  472. .chart-wrap {
  473. height: 380rpx;
  474. overflow: hidden; /* 隐藏溢出内容 */
  475. background: #fff;
  476. border-radius: 12rpx;
  477. padding: 24rpx;
  478. margin: 0 24rpx 20rpx 24rpx;
  479. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03)
  480. }
  481. .chart-header {
  482. font-size: 32rpx;
  483. color: #333;
  484. margin-bottom: 20rpx;
  485. font-weight: 600
  486. }
  487. /* 关键修复:确保canvas样式正确,参考微信小程序示例 */
  488. .chart-canvas { margin-left: -10rpx;
  489. height: 320rpx;
  490. background-color: #FFFFFF;
  491. display: block;
  492. }
  493. .summary {
  494. padding: 20rpx;
  495. color: #666;
  496. font-size: 28rpx
  497. }
  498. .list {
  499. background: #fff;
  500. border-radius: 12rpx;
  501. padding: 10rpx;
  502. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03)
  503. }
  504. .empty {
  505. padding: 40rpx;
  506. text-align: center;
  507. color: #999
  508. }
  509. .list-item {
  510. display: flex;
  511. align-items: center;
  512. padding: 20rpx;
  513. border-bottom: 1rpx solid #f0f0f0
  514. }
  515. .list-item .date {
  516. color: #666
  517. }
  518. .list-item .value {
  519. color: #333;
  520. font-weight: 600;
  521. flex: 1;
  522. text-align: right
  523. }
  524. /* 删除了浮动按钮样式,因为这是公共页面,仅供医生或家属查看患者健康数据 */
  525. /* Removed floating button styles because this is a public page for doctors or family members to view patient health data */
  526. /* 删除了模态框样式,因为这是公共页面,仅供医生或家属查看患者健康数据 */
  527. /* Removed modal styles because this is a public page for doctors or family members to view patient health data */
  528. </style>