weight.vue 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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="weightChart"
  24. id="weightChart"
  25. class="chart-canvas"
  26. :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
  27. ></canvas>
  28. </view>
  29. <!-- 其他内容保持不变 -->
  30. <view class="content">
  31. <view class="summary">共 {{ records.length }} 条记录,本月平均:{{ averageWeight }} kg</view>
  32. <view class="list">
  33. <view v-if="records.length === 0" class="empty">暂无记录,点击右下角 + 添加</view>
  34. <view v-for="item in records" :key="item.id" class="list-item">
  35. <view class="date">{{ item.date }}</view>
  36. <view class="value">{{ item.weight }} kg</view>
  37. <button class="btn-delete" @click="confirmDeleteRecord(item.id)">✕</button>
  38. </view>
  39. </view>
  40. </view>
  41. <view class="fab" @click="openAdd">
  42. <view class="fab-inner">+</view>
  43. </view>
  44. <view class="modal" v-if="showAdd">
  45. <view class="modal-backdrop" @click="closeAdd"></view>
  46. <view class="modal-panel">
  47. <view class="drag-handle"></view>
  48. <view class="modal-header"><text class="modal-title">添加体重</text></view>
  49. <view class="modal-inner">
  50. <view class="form-row">
  51. <text class="label">日期</text>
  52. <picker mode="date" :value="addDate" @change="onAddDateChange">
  53. <view class="picker-display">{{ addDateLabel }}</view>
  54. </picker>
  55. </view>
  56. <view class="form-row">
  57. <text class="label">体重 (kg)</text>
  58. <input type="number" v-model.number="addWeight" class="input" placeholder="请输入体重" />
  59. </view>
  60. </view>
  61. <view class="ruler-wrap">
  62. <ScaleRuler v-if="showAdd" :min="20" :max="200" :step="0.1" :gutter="20" :initialValue="addWeight ?? 65" @update="onAddRulerUpdate" @change="onAddRulerChange" />
  63. </view>
  64. <view class="fixed-footer">
  65. <button class="btn-primary btn-full" @click="confirmAdd">保存</button>
  66. </view>
  67. </view>
  68. </view>
  69. </view>
  70. <TabBar />
  71. </template>
  72. <script setup lang="ts">
  73. import { ref, computed, onMounted, watch, nextTick, onBeforeUnmount, getCurrentInstance } from 'vue'
  74. import uCharts from '@qiun/ucharts'
  75. import CustomNav from '@/components/custom-nav.vue'
  76. import TabBar from '@/components/tab-bar.vue'
  77. import ScaleRuler from '@/components/scale-ruler.vue'
  78. import { getWeekStart, getWeekEnd, getWeekNumber, formatDisplayDate, formatPickerDate, daysInMonth, weekDayIndex } from '@/utils/date'
  79. type RecordItem = { id: string; date: string; weight: number }
  80. // 当前展示年月
  81. const current = ref(new Date())
  82. const pickerValue = ref([current.value.getFullYear() - 2000, current.value.getMonth()]) // 年从2000年开始,月0-11
  83. // 视图模式:'month' 或 'week'
  84. const viewMode = ref<'month' | 'week'>('month')
  85. // 年月选择器的选项范围
  86. const pickerRange = ref([
  87. Array.from({ length: 50 }, (_, i) => `${2000 + i}年`), // 2000-2049年
  88. Array.from({ length: 12 }, (_, i) => `${i + 1}月`) // 1-12月
  89. ])
  90. // 明确的canvas尺寸(将由 getCanvasSize 初始化以匹配设备宽度)
  91. const canvasWidth = ref(700) // 初始值,会在 mounted 时覆盖
  92. const canvasHeight = ref(280)
  93. // 获取Canvas实际尺寸的函数 - 参考微信小程序示例使用固定尺寸
  94. function getCanvasSize(): Promise<{ width: number; height: number }> {
  95. return new Promise((resolve) => {
  96. // 使用固定尺寸,参考微信小程序示例
  97. const windowWidth = uni.getSystemInfoSync().windowWidth;
  98. const width = windowWidth; // 占满屏幕宽度
  99. const height = 280 / 750 * windowWidth; // 280rpx转换为px,与CSS高度匹配
  100. resolve({ width, height });
  101. });
  102. }
  103. // 使用 formatPickerDate 从 src/utils/date.ts
  104. const displayYear = computed(() => current.value.getFullYear())
  105. const displayMonth = computed(() => current.value.getMonth() + 1)
  106. // 显示周期的计算属性
  107. const displayPeriod = computed(() => {
  108. if (viewMode.value === 'month') {
  109. return `${displayYear.value}年 ${displayMonth.value}月`
  110. } else {
  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. const y = d.getFullYear()
  122. const m = d.getMonth()
  123. daysCount = daysInMonth(y, m)
  124. } else {
  125. daysCount = 7
  126. }
  127. const n = Math.floor(Math.random() * Math.min(daysCount, 7))
  128. for (let i = 0; i < n; i++) {
  129. let recordDate: Date
  130. if (viewMode.value === 'month') {
  131. const y = d.getFullYear()
  132. const m = d.getMonth()
  133. const day = Math.max(1, Math.floor(Math.random() * daysCount) + 1)
  134. recordDate = new Date(y, m, day)
  135. } else {
  136. const weekStart = getWeekStart(d)
  137. const dayOffset = Math.floor(Math.random() * 7)
  138. recordDate = new Date(weekStart)
  139. recordDate.setDate(weekStart.getDate() + dayOffset)
  140. }
  141. arr.push({
  142. id: `${recordDate.getTime()}${i}${Date.now()}`,
  143. date: formatDisplayDate(recordDate),
  144. weight: Number((50 + Math.random() * 50).toFixed(1))
  145. })
  146. }
  147. return arr.sort((a, b) => (a.date < b.date ? 1 : -1))
  148. }
  149. // 将 records 聚合为每天一个点(取最新记录)
  150. function aggregateDaily(recordsArr: RecordItem[], year: number, month: number) {
  151. const map = new Map<number, RecordItem>()
  152. for (const r of recordsArr) {
  153. const parts = r.date.split('-')
  154. if (parts.length >= 3) {
  155. const y = parseInt(parts[0], 10)
  156. const m = parseInt(parts[1], 10) - 1
  157. const d = parseInt(parts[2], 10)
  158. if (y === year && m === month) {
  159. // 覆盖同一天,保留最新的(数组头部为最新)
  160. map.set(d, r)
  161. }
  162. }
  163. }
  164. // 返回按日索引的数组
  165. return map
  166. }
  167. const averageWeight = computed(() => {
  168. if (records.value.length === 0) return '--'
  169. const sum = records.value.reduce((s, r) => s + r.weight, 0)
  170. return (sum / records.value.length).toFixed(1)
  171. })
  172. // 使用共享日期工具 (src/utils/date.ts)
  173. // Canvas / uCharts 绘图 - 修复版本
  174. const chartInstance = ref<any>(null)
  175. const vm = getCurrentInstance()
  176. let chartInitialized = false
  177. let chartBusy = false // 绘图锁,防止并发初始化/更新
  178. // 简化的图表绘制函数(支持月/周视图)
  179. async function drawChart() {
  180. if (chartBusy) return
  181. chartBusy = true
  182. if (chartInitialized && chartInstance.value) {
  183. try { await updateChartData() } finally { chartBusy = false }
  184. return
  185. }
  186. if (chartInstance.value) {
  187. try { if (chartInstance.value.destroy) chartInstance.value.destroy() } catch (e) { console.warn('Destroy chart error:', e) }
  188. chartInstance.value = null
  189. }
  190. if (typeof uCharts === 'undefined') { console.warn('uCharts not available'); return }
  191. const size = await getCanvasSize()
  192. const cssWidth = size.width
  193. const cssHeight = size.height
  194. const pixelRatio = 1
  195. const rightGap = Math.max(24, Math.round(cssWidth * 0.04))
  196. const chartWidth = Math.max(cssWidth - rightGap, Math.round(cssWidth * 0.85))
  197. const year = current.value.getFullYear()
  198. const month = current.value.getMonth()
  199. // categories 构造,区分月/周视图
  200. const categories: string[] = []
  201. if (viewMode.value === 'month') {
  202. const days = daysInMonth(year, month)
  203. const showLabelDays: number[] = []
  204. if (days > 0) {
  205. showLabelDays.push(1)
  206. if (days > 1) showLabelDays.push(days)
  207. if (days > 7) showLabelDays.push(Math.ceil(days / 3))
  208. if (days > 14) showLabelDays.push(Math.ceil(days * 2 / 3))
  209. }
  210. for (let d = 1; d <= days; d++) categories.push(showLabelDays.includes(d) ? `${d}日` : '')
  211. } else {
  212. const weekStart = getWeekStart(current.value)
  213. const weekDays = ['一', '二', '三', '四', '五', '六', '日']
  214. for (let i = 0; i < 7; i++) {
  215. const date = new Date(weekStart)
  216. date.setDate(weekStart.getDate() + i)
  217. categories.push(`${date.getDate()}日(${weekDays[i]})`)
  218. }
  219. }
  220. // 聚合数据
  221. const data: number[] = []
  222. const filteredCategories: string[] = []
  223. const dayMap = new Map<number, RecordItem>()
  224. if (viewMode.value === 'month') {
  225. for (const r of records.value) {
  226. const parts = r.date.split('-')
  227. if (parts.length >= 3) {
  228. const y = parseInt(parts[0], 10)
  229. const m = parseInt(parts[1], 10) - 1
  230. const d = parseInt(parts[2], 10)
  231. if (y === year && m === month) dayMap.set(d, r)
  232. }
  233. }
  234. const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b)
  235. for (const d of sortedDays) { const rec = dayMap.get(d)!; filteredCategories.push(`${d}日`); data.push(rec.weight) }
  236. } else {
  237. const weekStart = getWeekStart(current.value)
  238. for (const r of records.value) {
  239. const parts = r.date.split('-')
  240. if (parts.length >= 3) {
  241. const recordDate = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10))
  242. const weekStartDate = getWeekStart(recordDate)
  243. if (weekStartDate.getTime() === weekStart.getTime()) {
  244. const dayOfWeek = recordDate.getDay() || 7
  245. dayMap.set(dayOfWeek, r)
  246. }
  247. }
  248. }
  249. const weekDays = ['一','二','三','四','五','六','日']
  250. for (let i = 1; i <= 7; i++) {
  251. const rec = dayMap.get(i)
  252. if (rec) { const date = new Date(rec.date); filteredCategories.push(`${date.getDate()}日(${weekDays[i-1]})`); data.push(rec.weight) }
  253. }
  254. }
  255. const categoriesToUse = filteredCategories.length ? filteredCategories : categories
  256. const validData = data.filter(v => v > 0)
  257. const minVal = validData.length ? Math.floor(Math.min(...validData)) - 2 : 40
  258. const maxVal = validData.length ? Math.ceil(Math.max(...validData)) + 2 : 100
  259. const series = [{ name: '体重', data: data, color: '#ff6a00' }]
  260. // 获取 canvas 上下文
  261. let ctx: any = null
  262. try {
  263. if (typeof uni !== 'undefined' && typeof uni.createCanvasContext === 'function') {
  264. try { ctx = vm?.proxy ? uni.createCanvasContext('weightChart', vm.proxy) : uni.createCanvasContext('weightChart') } catch (e) { try { ctx = uni.createCanvasContext('weightChart') } catch (err) { ctx = null } }
  265. }
  266. } catch (e) { ctx = null }
  267. if (!ctx && typeof document !== 'undefined') {
  268. try {
  269. let el: HTMLCanvasElement | null = null
  270. for (let attempt = 0; attempt < 3; attempt++) {
  271. el = document.getElementById('weightChart') as HTMLCanvasElement | null
  272. if (el) break
  273. await new Promise(r => setTimeout(r, 50))
  274. }
  275. if (el && el.getContext) {
  276. try {
  277. const physicalW = Math.floor(cssWidth * pixelRatio)
  278. const physicalH = Math.floor(cssHeight * pixelRatio)
  279. if (el.width !== physicalW || el.height !== physicalH) { el.width = physicalW; el.height = physicalH; el.style.width = cssWidth + 'px'; el.style.height = cssHeight + 'px' }
  280. } catch (e) { console.warn('Set canvas physical size failed', e) }
  281. ctx = el.getContext('2d')
  282. }
  283. } catch (e) { ctx = null }
  284. }
  285. if (!ctx) { console.warn('Unable to obtain canvas context for uCharts.'); return }
  286. const config = {
  287. $this: vm?.proxy,
  288. canvasId: 'weightChart',
  289. context: ctx,
  290. type: 'line',
  291. fontSize: 10,
  292. categories: categoriesToUse,
  293. series: series,
  294. width: chartWidth,
  295. padding: [10, rightGap + 8, 18, 10],
  296. height: cssHeight,
  297. pixelRatio,
  298. background: 'transparent',
  299. animation: false,
  300. enableScroll: false,
  301. dataLabel: false,
  302. legend: { show: false },
  303. xAxis: { disableGrid: true, axisLine: true, axisLineColor: '#e0e0e0', fontColor: '#666666', fontSize: 10, boundaryGap: 'justify' },
  304. yAxis: { disableGrid: false, gridColor: '#f5f5f5', splitNumber: 4, min: minVal, max: maxVal, axisLine: true, axisLineColor: '#e0e0e0', fontColor: '#666666', fontSize: 10, format: (val: number) => val % 1 === 0 ? `${val}kg` : '' },
  305. extra: { line: { type: 'curve', width: 1, activeType: 'point', point: { radius: 0.5, strokeWidth: 0.5 } }, tooltip: { showBox: false, showCategory: false } }
  306. }
  307. try {
  308. if (chartInstance.value && chartInstance.value.destroy) { try { chartInstance.value.destroy() } catch (e) { console.warn('destroy before init failed', e) } chartInstance.value = null; chartInitialized = false }
  309. chartInstance.value = new uCharts(config)
  310. chartInitialized = true
  311. } catch (error) { console.error('uCharts init error:', error); chartInitialized = false }
  312. chartBusy = false
  313. }
  314. // 更新数据而不重新初始化
  315. async function updateChartData() {
  316. if (chartBusy) return
  317. chartBusy = true
  318. if (!chartInstance.value || !chartInitialized) {
  319. try {
  320. await drawChart()
  321. } finally {
  322. chartBusy = false
  323. }
  324. return
  325. }
  326. const year = current.value.getFullYear()
  327. const month = current.value.getMonth()
  328. const categories: string[] = []
  329. const data: number[] = []
  330. const filteredCategories: string[] = []
  331. const dayMap = new Map<number, RecordItem>()
  332. if (viewMode.value === 'month') {
  333. const days = daysInMonth(year, month)
  334. const showLabelDays: number[] = []
  335. if (days > 0) {
  336. showLabelDays.push(1)
  337. if (days > 1) showLabelDays.push(days)
  338. if (days > 7) showLabelDays.push(Math.ceil(days / 3))
  339. if (days > 14) showLabelDays.push(Math.ceil(days * 2 / 3))
  340. }
  341. for (let d = 1; d <= days; d++) categories.push(showLabelDays.includes(d) ? `${d}日` : '')
  342. for (const r of records.value) {
  343. const parts = r.date.split('-')
  344. if (parts.length >= 3) {
  345. const y = parseInt(parts[0], 10)
  346. const m = parseInt(parts[1], 10) - 1
  347. const d = parseInt(parts[2], 10)
  348. if (y === year && m === month) dayMap.set(d, r)
  349. }
  350. }
  351. const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b)
  352. for (const d of sortedDays) { const rec = dayMap.get(d)!; filteredCategories.push(`${d}日`); data.push(rec.weight) }
  353. } else {
  354. const weekStart = getWeekStart(current.value)
  355. const weekDays = ['一','二','三','四','五','六','日']
  356. for (let i = 0; i < 7; i++) {
  357. const date = new Date(weekStart)
  358. date.setDate(weekStart.getDate() + i)
  359. categories.push(`${date.getDate()}日(${weekDays[i]})`)
  360. }
  361. for (const r of records.value) {
  362. const parts = r.date.split('-')
  363. if (parts.length >= 3) {
  364. const recordDate = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10))
  365. const weekStartDate = getWeekStart(recordDate)
  366. if (weekStartDate.getTime() === weekStart.getTime()) {
  367. const dayOfWeek = recordDate.getDay() || 7
  368. dayMap.set(dayOfWeek, r)
  369. }
  370. }
  371. }
  372. for (let i = 1; i <= 7; i++) {
  373. const rec = dayMap.get(i)
  374. if (rec) { const date = new Date(rec.date); filteredCategories.push(`${date.getDate()}日(${weekDays[i-1]})`); data.push(rec.weight) }
  375. }
  376. }
  377. const categoriesToUse = filteredCategories.length ? filteredCategories : categories
  378. const validData = data.filter(v => v > 0)
  379. const minVal = validData.length ? Math.floor(Math.min(...validData)) - 2 : 40
  380. const maxVal = validData.length ? Math.ceil(Math.max(...validData)) + 2 : 100
  381. try {
  382. try {
  383. const size = await getCanvasSize()
  384. const cssWidth = size.width
  385. const rightGap = Math.max(24, Math.round(cssWidth * 0.04))
  386. const chartWidth = Math.max(cssWidth - rightGap, Math.round(cssWidth * 0.85))
  387. if (chartInstance.value.opts) {
  388. chartInstance.value.opts.width = chartWidth
  389. chartInstance.value.opts.padding = [10, rightGap + 8, 18, 10]
  390. }
  391. } catch (e) {}
  392. chartInstance.value.updateData({ categories: categoriesToUse, series: [{ name: '体重', data: data, color: '#ff6a00' }] })
  393. chartInstance.value.opts.yAxis.min = minVal
  394. chartInstance.value.opts.yAxis.max = maxVal
  395. } catch (error) {
  396. console.error('Update chart error:', error)
  397. try { if (chartInstance.value && chartInstance.value.destroy) chartInstance.value.destroy() } catch (e) { console.warn('destroy on update failure failed', e) }
  398. chartInstance.value = null
  399. chartInitialized = false
  400. try { await drawChart() } catch (e) { console.error('re-init after update failure also failed', e) }
  401. }
  402. chartBusy = false
  403. }
  404. onMounted(() => {
  405. // 延迟确保DOM渲染完成
  406. setTimeout(async () => {
  407. await nextTick()
  408. // 由 getCanvasSize 计算并覆盖 canvasWidth/canvasHeight(确保模板样式和绘图一致)
  409. try {
  410. const size = await getCanvasSize()
  411. canvasWidth.value = size.width
  412. canvasHeight.value = size.height
  413. } catch (e) {
  414. console.warn('getCanvasSize failed on mounted', e)
  415. }
  416. await drawChart()
  417. }, 500)
  418. })
  419. // 简化监听,避免频繁重绘
  420. watch([() => current.value], async () => {
  421. setTimeout(async () => {
  422. await updateChartData()
  423. }, 100)
  424. })
  425. watch([() => records.value], async () => {
  426. setTimeout(async () => {
  427. await updateChartData()
  428. }, 100)
  429. }, { deep: true })
  430. onBeforeUnmount(() => {
  431. if (chartInstance.value && chartInstance.value.destroy) {
  432. try {
  433. chartInstance.value.destroy()
  434. } catch (e) {
  435. console.warn('uCharts destroy error:', e)
  436. }
  437. }
  438. chartInstance.value = null
  439. chartInitialized = false
  440. })
  441. // 强制重建图表(用于切换月份时彻底刷新,如同退出页面再进入)
  442. async function rebuildChart() {
  443. // 如果正在绘制,等一小会儿再销毁
  444. if (chartBusy) {
  445. // 等待最大 300ms,避免长时间阻塞
  446. await new Promise(r => setTimeout(r, 50))
  447. }
  448. try {
  449. if (chartInstance.value && chartInstance.value.destroy) {
  450. try { chartInstance.value.destroy() } catch (e) { console.warn('destroy in rebuildChart failed', e) }
  451. }
  452. } catch (e) {
  453. console.warn('rebuildChart destroy error', e)
  454. }
  455. chartInstance.value = null
  456. chartInitialized = false
  457. // 等待 DOM/Tick 稳定
  458. await nextTick()
  459. // 重新初始化
  460. try {
  461. await drawChart()
  462. } catch (e) {
  463. console.error('rebuildChart drawChart failed', e)
  464. }
  465. }
  466. // 周/月切换和周期导航
  467. async function prevPeriod() {
  468. const d = new Date(current.value)
  469. if (viewMode.value === 'month') {
  470. d.setMonth(d.getMonth() - 1)
  471. } else {
  472. d.setDate(d.getDate() - 7)
  473. }
  474. current.value = d
  475. pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
  476. records.value = generateMockRecords(d)
  477. await rebuildChart()
  478. }
  479. async function nextPeriod() {
  480. const d = new Date(current.value)
  481. if (viewMode.value === 'month') {
  482. d.setMonth(d.getMonth() + 1)
  483. } else {
  484. d.setDate(d.getDate() + 7)
  485. }
  486. current.value = d
  487. pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
  488. records.value = generateMockRecords(d)
  489. await rebuildChart()
  490. }
  491. async function setViewMode(mode: 'month' | 'week') {
  492. if (viewMode.value !== mode) {
  493. viewMode.value = mode
  494. records.value = generateMockRecords(current.value)
  495. await rebuildChart()
  496. }
  497. }
  498. async function onPickerChange(e: any) {
  499. const val = e?.detail?.value || e
  500. if (Array.isArray(val) && val.length >= 2) {
  501. const y = 2000 + val[0]
  502. const m = val[1]
  503. const d = new Date(y, m, 1)
  504. current.value = d
  505. pickerValue.value = [val[0], val[1]]
  506. records.value = generateMockRecords(d)
  507. await rebuildChart()
  508. }
  509. }
  510. // 添加逻辑保持不变
  511. const showAdd = ref(false)
  512. const addDate = ref(formatPickerDate(new Date()))
  513. const addDateLabel = ref(formatDisplayDate(new Date()))
  514. const addWeight = ref<number | null>(null)
  515. function onAddRulerUpdate(val: number) {
  516. addWeight.value = Number(val.toFixed(1))
  517. }
  518. function onAddRulerChange(val: number) {
  519. addWeight.value = Number(val.toFixed(1))
  520. }
  521. function openAdd() {
  522. showAdd.value = true
  523. if (!addWeight.value) addWeight.value = 65
  524. }
  525. function closeAdd() {
  526. showAdd.value = false
  527. addWeight.value = null
  528. }
  529. function onAddDateChange(e: any) {
  530. const val = e?.detail?.value || e
  531. addDate.value = val
  532. addDateLabel.value = val.replace(/^(.{10}).*$/, '$1')
  533. }
  534. async function confirmAdd() {
  535. if (!addWeight.value) {
  536. uni.showToast && uni.showToast({ title: '请输入体重', icon: 'none' })
  537. return
  538. }
  539. const id = `user-${Date.now()}`
  540. const item: RecordItem = { id, date: addDateLabel.value, weight: Number(Number(addWeight.value).toFixed(1)) }
  541. const parts = addDate.value.split('-')
  542. const addY = parseInt(parts[0], 10)
  543. const addM = parseInt(parts[1], 10) - 1
  544. if (addY === current.value.getFullYear() && addM === current.value.getMonth()) {
  545. records.value = [item, ...records.value]
  546. }
  547. uni.showToast && uni.showToast({ title: '已添加', icon: 'success' })
  548. closeAdd()
  549. // 新增记录后彻底重建图表,确保像退出再进入一样刷新
  550. try {
  551. await rebuildChart()
  552. } catch (e) {
  553. console.warn('rebuildChart after add failed', e)
  554. }
  555. }
  556. async function confirmDeleteRecord(id: string) {
  557. if (typeof uni !== 'undefined' && uni.showModal) {
  558. uni.showModal({
  559. title: '删除',
  560. content: '确认删除该条记录吗?',
  561. success: async (res: any) => {
  562. if (res.confirm) {
  563. records.value = records.value.filter(r => r.id !== id)
  564. try { await rebuildChart() } catch (e) { console.warn('rebuildChart after delete failed', e) }
  565. }
  566. }
  567. })
  568. } else {
  569. records.value = records.value.filter(r => r.id !== id)
  570. try { await rebuildChart() } catch (e) { console.warn('rebuildChart after delete failed', e) }
  571. }
  572. }
  573. </script>
  574. <style scoped>
  575. .page {
  576. min-height: calc(100vh);
  577. padding-top: calc(var(--status-bar-height) + 44px);
  578. background: #f5f6f8;
  579. box-sizing: border-box
  580. }
  581. .header {
  582. padding: 20rpx 40rpx
  583. }
  584. .month-selector {
  585. display: flex;
  586. align-items: center;
  587. justify-content: center;
  588. gap: 12rpx
  589. }
  590. .period-controls {
  591. display: flex;
  592. flex-direction: column;
  593. align-items: center;
  594. gap: 8rpx;
  595. }
  596. .view-toggle {
  597. display: flex;
  598. gap: 4rpx;
  599. }
  600. .toggle-btn {
  601. padding: 4rpx 12rpx;
  602. border: 1rpx solid #ddd;
  603. background: #f5f5f5;
  604. color: #666;
  605. border-radius: 6rpx;
  606. font-size: 24rpx;
  607. min-width: 60rpx;
  608. text-align: center;
  609. }
  610. .toggle-btn.active {
  611. background: #ff6a00;
  612. color: #fff;
  613. border-color: #ff6a00;
  614. }
  615. .month-label {
  616. font-size: 34rpx;
  617. color: #333
  618. }
  619. .btn {
  620. background: transparent;
  621. border: none;
  622. font-size: 36rpx;
  623. color: #666
  624. }
  625. .content {
  626. padding: 20rpx 24rpx 100rpx 24rpx
  627. }
  628. .chart-wrap {
  629. background: #fff;
  630. border-radius: 12rpx;
  631. padding: 24rpx;
  632. margin: 0 24rpx 20rpx 24rpx;
  633. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03)
  634. }
  635. .chart-header {
  636. font-size: 32rpx;
  637. color: #333;
  638. margin-bottom: 20rpx;
  639. font-weight: 600
  640. }
  641. /* 关键修复:确保canvas样式正确,参考微信小程序示例 */
  642. .chart-canvas {
  643. width: 750rpx;
  644. height: 280rpx;
  645. background-color: #FFFFFF;
  646. display: block;
  647. }
  648. .summary {
  649. padding: 20rpx;
  650. color: #666;
  651. font-size: 28rpx
  652. }
  653. .list {
  654. background: #fff;
  655. border-radius: 12rpx;
  656. padding: 10rpx;
  657. box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03)
  658. }
  659. .empty {
  660. padding: 40rpx;
  661. text-align: center;
  662. color: #999
  663. }
  664. .list-item {
  665. display: flex;
  666. align-items: center;
  667. padding: 20rpx;
  668. border-bottom: 1rpx solid #f0f0f0
  669. }
  670. .list-item .date {
  671. color: #666
  672. }
  673. .list-item .value {
  674. color: #333;
  675. font-weight: 600;
  676. flex: 1;
  677. text-align: right
  678. }
  679. .btn-delete {
  680. width: 80rpx;
  681. height: 60rpx;
  682. min-width: 60rpx;
  683. min-height: 60rpx;
  684. display: inline-flex;
  685. align-items: center;
  686. justify-content: center;
  687. background: #fff0f0;
  688. color: #d9534f;
  689. border: 1rpx solid rgba(217,83,79,0.15);
  690. border-radius: 8rpx;
  691. margin-left: 30rpx
  692. }
  693. .fab {
  694. position: fixed;
  695. right: 28rpx;
  696. bottom: 160rpx;
  697. width: 110rpx;
  698. height: 110rpx;
  699. border-radius: 999px;
  700. background: linear-gradient(180deg, #ff7a00, #ff4a00);
  701. display: flex;
  702. align-items: center;
  703. justify-content: center;
  704. box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.2);
  705. z-index: 1200
  706. }
  707. .fab-inner {
  708. color: #fff;
  709. font-size: 56rpx;
  710. line-height: 56rpx
  711. }
  712. /* 模态框样式保持不变 */
  713. .modal {
  714. position: fixed;
  715. left: 0;
  716. right: 0;
  717. top: 0;
  718. bottom: 0;
  719. display: flex;
  720. align-items: flex-end;
  721. justify-content: center;
  722. z-index: 1300
  723. }
  724. .modal-backdrop {
  725. position: absolute;
  726. left: 0;
  727. right: 0;
  728. top: 0;
  729. bottom: 0;
  730. background: rgba(0, 0, 0, 0.4)
  731. }
  732. .modal-panel {
  733. position: relative;
  734. width: 100%;
  735. background: #fff;
  736. border-top-left-radius: 18rpx;
  737. border-top-right-radius: 18rpx;
  738. padding: 28rpx 24rpx 140rpx 24rpx;
  739. box-shadow: 0 -8rpx 30rpx rgba(0,0,0,0.12)
  740. }
  741. .modal-title {
  742. font-size: 56rpx;
  743. margin-block: 60rpx;
  744. color: #222;
  745. font-weight: 700;
  746. letter-spacing: 1rpx
  747. }
  748. .modal-inner {
  749. max-width: 70%;
  750. margin: 0 auto
  751. }
  752. .form-row {
  753. display: flex;
  754. align-items: center;
  755. justify-content: space-between;
  756. margin-bottom: 34rpx;
  757. padding: 14rpx 0;
  758. font-size: 32rpx
  759. }
  760. .input {
  761. width: 150rpx;
  762. text-align: right;
  763. padding: 16rpx;
  764. border-radius: 14rpx;
  765. border: 1rpx solid #eee;
  766. background: #fff7f0
  767. }
  768. .picker-display {
  769. color: #333
  770. }
  771. .btn-primary {
  772. background: #ff6a00;
  773. color: #fff;
  774. padding: 18rpx 22rpx;
  775. border-radius: 16rpx;
  776. text-align: center;
  777. width: 50%;
  778. box-shadow: 0 10rpx 28rpx rgba(255,106,0,0.18)
  779. }
  780. .drag-handle {
  781. width: 64rpx;
  782. height: 6rpx;
  783. background: rgba(0,0,0,0.08);
  784. border-radius: 999px;
  785. margin: 10rpx auto 14rpx auto
  786. }
  787. .modal-header {
  788. display: flex;
  789. align-items: center;
  790. justify-content: center;
  791. gap: 12rpx;
  792. margin-bottom: 6rpx
  793. }
  794. .label {
  795. color: #666
  796. }
  797. .ruler-wrap {
  798. margin: 12rpx 0
  799. }
  800. .fixed-footer {
  801. position: absolute;
  802. left: 0;
  803. right: 0;
  804. bottom: 40rpx;
  805. padding: 0 24rpx
  806. }
  807. .btn-full {
  808. width: 100%;
  809. padding: 18rpx;
  810. border-radius: 12rpx;
  811. }
  812. </style>