height.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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">{{ viewMode === 'month' ? '本月' : '本周' }}趋势</view>
  22. <canvas
  23. canvas-id="heightChart"
  24. id="heightChart"
  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 }} 条记录{{ viewMode === 'month' ? ',本月' : ',本周' }}平均:{{ averageHeight }} cm</view>
  31. <view class="list">
  32. <view v-if="records.length === 0" class="empty">{{ viewMode === 'month' ? '本月' : '本周' }}暂无身高记录,点击右下角 + 添加</view>
  33. <view v-for="(r, idx) in records" :key="r.id" class="list-item">
  34. <view class="date">{{ r.date }}</view>
  35. <view class="value">{{ r.height }} cm</view>
  36. <button class="btn-delete" @click.stop.prevent="confirmDeleteRecord(r.id)">✕</button>
  37. </view>
  38. </view>
  39. </view>
  40. <!-- 悬浮添加按钮 -->
  41. <view class="fab" @click="openAdd">
  42. <view class="fab-inner">+</view>
  43. </view>
  44. <!-- 添加模态(包含刻度尺) -->
  45. <view class="modal" v-if="showAdd">
  46. <view class="modal-backdrop" @click="closeAdd"></view>
  47. <view class="modal-panel">
  48. <view class="drag-handle"></view>
  49. <view class="modal-header"><text class="modal-title">添加身高</text></view>
  50. <view class="modal-inner">
  51. <view class="form-row">
  52. <text class="label">日期</text>
  53. <picker mode="date" :value="addDate" @change="onAddDateChange">
  54. <view class="picker-display">{{ addDateLabel }}</view>
  55. </picker>
  56. </view>
  57. <view class="form-row">
  58. <text class="label">身高 (cm)</text>
  59. <input type="number" v-model.number="addHeight" class="input" placeholder="请输入身高" />
  60. </view>
  61. </view>
  62. <view class="ruler-wrap">
  63. <ScaleRuler v-if="showAdd" :min="120" :max="220" :step="1" :gutter="16" :initialValue="addHeight ?? 170" @update="onAddRulerUpdate" @change="onAddRulerChange" />
  64. </view>
  65. <view class="fixed-footer">
  66. <button class="btn-primary btn-full" @click="confirmAdd">保存</button>
  67. </view>
  68. </view>
  69. </view>
  70. </view>
  71. </template>
  72. <script setup lang="ts">
  73. import { ref, computed, onMounted, watch, nextTick, onBeforeUnmount, getCurrentInstance } from 'vue'
  74. import { createUChart } from '@/composables/useUChart'
  75. import CustomNav from '@/components/custom-nav.vue'
  76. import ScaleRuler from '@/components/scale-ruler.vue'
  77. import { getWeekStart, getWeekEnd, getWeekNumber, formatDisplayDate, formatPickerDate, daysInMonth, weekDayIndex } from '@/utils/date'
  78. type RecordItem = { id: string; date: string; height: number }
  79. // 当前展示年月
  80. const current = ref(new Date())
  81. const pickerValue = ref([current.value.getFullYear() - 2000, current.value.getMonth()]) // 年从2000年开始,月0-11
  82. // 视图模式:'month' 或 'week'
  83. const viewMode = ref<'month' | 'week'>('month')
  84. // 年月选择器的选项范围
  85. const pickerRange = ref([
  86. Array.from({ length: 50 }, (_, i) => `${2000 + i}年`), // 2000-2049年
  87. Array.from({ length: 12 }, (_, i) => `${i + 1}月`) // 1-12月
  88. ])
  89. // 明确的canvas尺寸(将由 getCanvasSize 初始化以匹配设备宽度)
  90. const canvasWidth = ref(700) // 初始值,会在 mounted 时覆盖
  91. const canvasHeight = ref(280)
  92. // 获取Canvas实际尺寸的函数 - 参考微信小程序示例使用固定尺寸
  93. function getCanvasSize(): Promise<{ width: number; height: number }> {
  94. return new Promise((resolve) => {
  95. // 使用固定尺寸,参考微信小程序示例
  96. const windowWidth = uni.getSystemInfoSync().windowWidth;
  97. const width = windowWidth; // 占满屏幕宽度
  98. const height = 280 / 750 * windowWidth; // 280rpx转换为px,与CSS高度匹配
  99. resolve({ width, height });
  100. });
  101. }
  102. // 使用 formatPickerDate 从 src/utils/date.ts
  103. const displayYear = computed(() => current.value.getFullYear())
  104. const displayMonth = computed(() => current.value.getMonth() + 1)
  105. // 显示周期的计算属性
  106. const displayPeriod = computed(() => {
  107. if (viewMode.value === 'month') {
  108. return `${displayYear.value}年 ${displayMonth.value}月`
  109. } else {
  110. // 周视图:显示该周的日期范围
  111. const weekStart = getWeekStart(current.value)
  112. const weekEnd = getWeekEnd(current.value)
  113. return `${formatDisplayDate(weekStart)} - ${formatDisplayDate(weekEnd)}`
  114. }
  115. })
  116. const records = ref<RecordItem[]>(generateMockRecords(current.value))
  117. function generateMockRecords(d: Date): RecordItem[] {
  118. const arr: RecordItem[] = []
  119. let daysCount: number
  120. if (viewMode.value === 'month') {
  121. // 月视图:生成该月的记录
  122. const y = d.getFullYear()
  123. const m = d.getMonth()
  124. daysCount = daysInMonth(y, m)
  125. } else {
  126. // 周视图:生成该周的记录(7天)
  127. daysCount = 7
  128. }
  129. const n = Math.floor(Math.random() * Math.min(daysCount, 7)) // 最多7条记录
  130. for (let i = 0; i < n; i++) {
  131. let recordDate: Date
  132. if (viewMode.value === 'month') {
  133. const y = d.getFullYear()
  134. const m = d.getMonth()
  135. const day = Math.max(1, Math.floor(Math.random() * daysCount) + 1)
  136. recordDate = new Date(y, m, day)
  137. } else {
  138. // 周视图:从周一开始
  139. const weekStart = getWeekStart(d)
  140. const dayOffset = Math.floor(Math.random() * 7)
  141. recordDate = new Date(weekStart)
  142. recordDate.setDate(weekStart.getDate() + dayOffset)
  143. }
  144. arr.push({
  145. id: `${recordDate.getTime()}${i}${Date.now()}`,
  146. date: formatDisplayDate(recordDate),
  147. height: 150 + Math.floor(Math.random() * 50)
  148. })
  149. }
  150. return arr.sort((a, b) => (a.date < b.date ? 1 : -1))
  151. }
  152. // 将 records 聚合为每天一个点(取最新记录)
  153. function aggregateDaily(recordsArr: RecordItem[], year: number, month: number) {
  154. const map = new Map<number, RecordItem>()
  155. for (const r of recordsArr) {
  156. const parts = r.date.split('-')
  157. if (parts.length >= 3) {
  158. const y = parseInt(parts[0], 10)
  159. const m = parseInt(parts[1], 10) - 1
  160. const d = parseInt(parts[2], 10)
  161. if (y === year && m === month) {
  162. // 覆盖同一天,保留最新的(数组头部为最新)
  163. map.set(d, r)
  164. }
  165. }
  166. }
  167. // 返回按日索引的数组
  168. return map
  169. }
  170. const averageHeight = computed(() => {
  171. if (records.value.length === 0) return '--'
  172. const sum = records.value.reduce((s, r) => s + r.height, 0)
  173. return (sum / records.value.length).toFixed(1)
  174. })
  175. // 使用共享日期工具函数 (src/utils/date.ts)
  176. // 使用 createUChart composable
  177. const vm = getCurrentInstance()
  178. const heightChart = createUChart({
  179. canvasId: 'heightChart',
  180. vm,
  181. getCanvasSize,
  182. seriesNames: '身高',
  183. valueAccessors: r => r.height,
  184. colors: '#ff6a00'
  185. })
  186. // 生命周期钩子
  187. onMounted(() => {
  188. // 延迟确保DOM渲染完成
  189. setTimeout(async () => {
  190. await nextTick()
  191. // 由 getCanvasSize 计算并覆盖 canvasWidth/canvasHeight(确保模板样式和绘图一致)
  192. try {
  193. const size = await getCanvasSize()
  194. canvasWidth.value = size.width
  195. canvasHeight.value = size.height
  196. } catch (e) {
  197. console.warn('getCanvasSize failed on mounted', e)
  198. }
  199. await heightChart.draw(records, current, viewMode)
  200. }, 500)
  201. })
  202. // 简化监听,避免频繁重绘
  203. watch([() => current.value], async () => {
  204. setTimeout(async () => {
  205. await heightChart.update(records, current, viewMode)
  206. }, 100)
  207. })
  208. watch([() => records.value], async () => {
  209. setTimeout(async () => {
  210. await heightChart.update(records, current, viewMode)
  211. }, 100)
  212. }, { deep: true })
  213. onBeforeUnmount(() => {
  214. heightChart.destroy()
  215. })
  216. // 其他函数保持不变
  217. async function prevPeriod() {
  218. const d = new Date(current.value)
  219. if (viewMode.value === 'month') {
  220. d.setMonth(d.getMonth() - 1)
  221. } else {
  222. d.setDate(d.getDate() - 7) // 前一周
  223. }
  224. current.value = d
  225. pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
  226. records.value = generateMockRecords(d)
  227. await heightChart.rebuild(records, current, viewMode)
  228. }
  229. async function nextPeriod() {
  230. const d = new Date(current.value)
  231. if (viewMode.value === 'month') {
  232. d.setMonth(d.getMonth() + 1)
  233. } else {
  234. d.setDate(d.getDate() + 7) // 后一周
  235. }
  236. current.value = d
  237. pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
  238. records.value = generateMockRecords(d)
  239. await heightChart.rebuild(records, current, viewMode)
  240. }
  241. async function setViewMode(mode: 'month' | 'week') {
  242. if (viewMode.value !== mode) {
  243. viewMode.value = mode
  244. // 重新生成数据和图表
  245. records.value = generateMockRecords(current.value)
  246. await heightChart.rebuild(records, current, viewMode)
  247. }
  248. }
  249. async function onPickerChange(e: any) {
  250. const val = e?.detail?.value || e
  251. if (Array.isArray(val) && val.length >= 2) {
  252. const y = 2000 + val[0]
  253. const m = val[1]
  254. const d = new Date(y, m, 1)
  255. current.value = d
  256. pickerValue.value = [val[0], val[1]]
  257. records.value = generateMockRecords(d)
  258. await heightChart.rebuild(records, current, viewMode)
  259. }
  260. }
  261. // 添加逻辑保持不变
  262. const showAdd = ref(false)
  263. const addDate = ref(formatPickerDate(new Date()))
  264. const addDateLabel = ref(formatDisplayDate(new Date()))
  265. const addHeight = ref<number | null>(null)
  266. function onAddRulerUpdate(val: number) {
  267. addHeight.value = Number(val.toFixed(1))
  268. }
  269. function onAddRulerChange(val: number) {
  270. addHeight.value = Number(val.toFixed(1))
  271. }
  272. function openAdd() {
  273. showAdd.value = true
  274. if (!addHeight.value) addHeight.value = 170
  275. }
  276. function closeAdd() {
  277. showAdd.value = false
  278. addHeight.value = null
  279. }
  280. function onAddDateChange(e: any) {
  281. const val = e?.detail?.value || e
  282. addDate.value = val
  283. addDateLabel.value = val.replace(/^(.{10}).*$/, '$1')
  284. }
  285. async function confirmAdd() {
  286. if (!addHeight.value) {
  287. uni.showToast && uni.showToast({ title: '请输入身高', icon: 'none' })
  288. return
  289. }
  290. const id = `user-${Date.now()}`
  291. const item: RecordItem = { id, date: addDateLabel.value, height: Number(Number(addHeight.value).toFixed(1)) }
  292. const parts = addDate.value.split('-')
  293. const addY = parseInt(parts[0], 10)
  294. const addM = parseInt(parts[1], 10) - 1
  295. const addD = parseInt(parts[2], 10)
  296. const addDateObj = new Date(addY, addM, addD)
  297. // 检查是否在当前周期内
  298. let isInCurrentPeriod = false
  299. if (viewMode.value === 'month') {
  300. isInCurrentPeriod = addY === current.value.getFullYear() && addM === current.value.getMonth()
  301. } else {
  302. const weekStart = getWeekStart(current.value)
  303. const recordWeekStart = getWeekStart(addDateObj)
  304. isInCurrentPeriod = weekStart.getTime() === recordWeekStart.getTime()
  305. }
  306. if (isInCurrentPeriod) {
  307. records.value = [item, ...records.value]
  308. }
  309. uni.showToast && uni.showToast({ title: '已添加', icon: 'success' })
  310. closeAdd()
  311. // 新增记录后彻底重建图表,确保像退出再进入一样刷新
  312. try {
  313. await heightChart.rebuild(records, current, viewMode)
  314. } catch (e) {
  315. console.warn('rebuildChart after add failed', e)
  316. }
  317. }
  318. async function confirmDeleteRecord(id: string) {
  319. if (typeof uni !== 'undefined' && uni.showModal) {
  320. uni.showModal({
  321. title: '删除',
  322. content: '确认删除该条记录吗?',
  323. success: async (res: any) => {
  324. if (res.confirm) {
  325. records.value = records.value.filter(r => r.id !== id)
  326. try { await heightChart.rebuild(records, current, viewMode) } catch (e) { console.warn('rebuildChart after delete failed', e) }
  327. }
  328. }
  329. })
  330. } else {
  331. records.value = records.value.filter(r => r.id !== id)
  332. try { await heightChart.rebuild(records, current, viewMode) } catch (e) { console.warn('rebuildChart after delete failed', e) }
  333. }
  334. }
  335. </script>
  336. <style scoped>
  337. .page {
  338. min-height: calc(100vh);
  339. padding-top: calc(var(--status-bar-height) + 44px);
  340. background: #f5f6f8;
  341. box-sizing: border-box
  342. }
  343. .header {
  344. padding: 20rpx 40rpx
  345. }
  346. .month-selector {
  347. display: flex;
  348. align-items: center;
  349. justify-content: center;
  350. gap: 12rpx
  351. }
  352. .period-controls {
  353. display: flex;
  354. flex-direction: column;
  355. align-items: center;
  356. gap: 8rpx;
  357. }
  358. .view-toggle {
  359. display: flex;
  360. gap: 4rpx;
  361. }
  362. .toggle-btn {
  363. padding: 4rpx 12rpx;
  364. border: 1rpx solid #ddd;
  365. background: #f5f5f5;
  366. color: #666;
  367. border-radius: 6rpx;
  368. font-size: 24rpx;
  369. min-width: 60rpx;
  370. text-align: center;
  371. }
  372. .toggle-btn.active {
  373. background: #ff6a00;
  374. color: #fff;
  375. border-color: #ff6a00;
  376. }
  377. .month-label {
  378. font-size: 34rpx;
  379. color: #333
  380. }
  381. .btn {
  382. background: transparent;
  383. border: none;
  384. font-size: 36rpx;
  385. color: #666
  386. }
  387. .content {
  388. padding: 20rpx 24rpx 100rpx 24rpx
  389. }
  390. .chart-wrap {
  391. height: 340rpx;
  392. overflow: hidden; /* 隐藏溢出内容 */
  393. background: #fff;
  394. border-radius: 12rpx;
  395. padding: 24rpx;
  396. margin: 0 24rpx 20rpx 24rpx;
  397. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03)
  398. }
  399. .chart-header {
  400. font-size: 32rpx;
  401. color: #333;
  402. margin-bottom: 20rpx;
  403. font-weight: 600
  404. }
  405. /* 关键修复:确保canvas样式正确,参考微信小程序示例 */
  406. .chart-canvas {
  407. height: 280rpx;
  408. background-color: #FFFFFF;
  409. display: block;
  410. }
  411. .summary {
  412. padding: 20rpx;
  413. color: #666;
  414. font-size: 28rpx
  415. }
  416. .list {
  417. background: #fff;
  418. border-radius: 12rpx;
  419. padding: 10rpx;
  420. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03)
  421. }
  422. .empty {
  423. padding: 40rpx;
  424. text-align: center;
  425. color: #999
  426. }
  427. .list-item {
  428. display: flex;
  429. align-items: center;
  430. padding: 20rpx;
  431. border-bottom: 1rpx solid #f0f0f0
  432. }
  433. .list-item .date {
  434. color: #666
  435. }
  436. .list-item .value {
  437. color: #333;
  438. font-weight: 600;
  439. flex: 1;
  440. text-align: right
  441. }
  442. .btn-delete {
  443. width: 80rpx;
  444. height: 60rpx;
  445. min-width: 60rpx;
  446. min-height: 60rpx;
  447. display: inline-flex;
  448. align-items: center;
  449. justify-content: center;
  450. background: #fff0f0;
  451. color: #d9534f;
  452. border: 1rpx solid rgba(217,83,79,0.15);
  453. border-radius: 8rpx;
  454. margin-left: 30rpx
  455. }
  456. .fab {
  457. position: fixed;
  458. right: 28rpx;
  459. bottom: 160rpx;
  460. width: 110rpx;
  461. height: 110rpx;
  462. border-radius: 999px;
  463. background: linear-gradient(180deg, #ff7a00, #ff4a00);
  464. display: flex;
  465. align-items: center;
  466. justify-content: center;
  467. box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.2);
  468. z-index: 1200
  469. }
  470. .fab-inner {
  471. color: #fff;
  472. font-size: 56rpx;
  473. line-height: 56rpx
  474. }
  475. .modal {
  476. position: fixed;
  477. left: 0;
  478. right: 0;
  479. top: 0;
  480. bottom: 0;
  481. display: flex;
  482. align-items: flex-end;
  483. justify-content: center;
  484. z-index: 1300
  485. }
  486. .modal-backdrop {
  487. position: absolute;
  488. left: 0;
  489. right: 0;
  490. top: 0;
  491. bottom: 0;
  492. background: rgba(0, 0, 0, 0.4)
  493. }
  494. .modal-panel {
  495. position: relative;
  496. width: 100%;
  497. background: #fff;
  498. border-top-left-radius: 18rpx;
  499. border-top-right-radius: 18rpx;
  500. padding: 28rpx 24rpx 140rpx 24rpx;
  501. box-shadow: 0 -8rpx 30rpx rgba(0,0,0,0.12)
  502. }
  503. .modal-title {
  504. font-size: 56rpx;
  505. margin-block: 60rpx;
  506. color: #222;
  507. font-weight: 700;
  508. letter-spacing: 1rpx
  509. }
  510. .modal-inner {
  511. max-width: 70%;
  512. margin: 0 auto
  513. }
  514. .form-row {
  515. display: flex;
  516. align-items: center;
  517. justify-content: space-between;
  518. margin-bottom: 34rpx;
  519. padding: 14rpx 0;
  520. font-size: 32rpx
  521. }
  522. .input {
  523. width: 150rpx;
  524. text-align: right;
  525. padding: 16rpx;
  526. border-radius: 14rpx;
  527. border: 1rpx solid #eee;
  528. background: #fff7f0
  529. }
  530. .picker-display {
  531. color: #333
  532. }
  533. .btn-primary {
  534. background: #ff6a00;
  535. color: #fff;
  536. padding: 18rpx 22rpx;
  537. border-radius: 16rpx;
  538. text-align: center;
  539. width: 50%;
  540. box-shadow: 0 10rpx 28rpx rgba(255,106,0,0.18)
  541. }
  542. .drag-handle {
  543. width: 64rpx;
  544. height: 6rpx;
  545. background: rgba(0,0,0,0.08);
  546. border-radius: 999px;
  547. margin: 10rpx auto 14rpx auto
  548. }
  549. .modal-header {
  550. display: flex;
  551. align-items: center;
  552. justify-content: center;
  553. gap: 12rpx;
  554. margin-bottom: 6rpx
  555. }
  556. .label {
  557. color: #666
  558. }
  559. .ruler-wrap {
  560. margin: 12rpx 0
  561. }
  562. .fixed-footer {
  563. position: absolute;
  564. left: 0;
  565. right: 0;
  566. bottom: 40rpx;
  567. padding: 0 24rpx
  568. }
  569. .btn-full {
  570. width: 100%;
  571. padding: 18rpx;
  572. border-radius: 12rpx;
  573. }
  574. </style>