blood-pressure.vue 14 KB

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