Bladeren bron

feat(health): 添加身高记录的周视图功能

- 新增周视图和月视图切换按钮
- 实现周视图下的日期范围显示
- 更新图表和列表以支持周视图数据展示
- 修改添加记录逻辑以适配当前视图周期
- 调整UI布局以容纳视图切换控件
mcbaiyun 2 maanden geleden
bovenliggende
commit
53c1f56a7c
1 gewijzigde bestanden met toevoegingen van 296 en 86 verwijderingen
  1. 296 86
      src/pages/health/details/height.vue

+ 296 - 86
src/pages/health/details/height.vue

@@ -3,17 +3,23 @@
   <view class="page">
     <view class="header">
       <view class="month-selector">
-        <button class="btn" @click="prevMonth">‹</button>
-        <picker mode="multiSelector" :value="pickerValue" :range="pickerRange" @change="onPickerChange">
-          <view class="month-label">{{ displayYear }}年 {{ displayMonth }}月</view>
-        </picker>
-        <button class="btn" @click="nextMonth">›</button>
+        <button class="btn" @click="prevPeriod">‹</button>
+        <view class="period-controls">
+          <picker mode="multiSelector" :value="pickerValue" :range="pickerRange" @change="onPickerChange">
+            <view class="month-label">{{ displayPeriod }}</view>
+          </picker>
+          <view class="view-toggle">
+            <button :class="['toggle-btn', { active: viewMode === 'month' }]" @click="setViewMode('month')">月</button>
+            <button :class="['toggle-btn', { active: viewMode === 'week' }]" @click="setViewMode('week')">周</button>
+          </view>
+        </view>
+        <button class="btn" @click="nextPeriod">›</button>
       </view>
     </view>
 
     <!-- 趋势图 - 简化canvas设置 -->
     <view class="chart-wrap">
-      <view class="chart-header">本月趋势</view>
+      <view class="chart-header">{{ viewMode === 'month' ? '本月' : '本周' }}趋势</view>
       <canvas 
         canvas-id="heightChart" 
         id="heightChart" 
@@ -23,10 +29,10 @@
     </view>
 
     <view class="content">
-      <view class="summary">共 {{ records.length }} 条记录,本月平均:{{ averageHeight }} cm</view>
+      <view class="summary">共 {{ records.length }} 条记录{{ viewMode === 'month' ? ',本月' : ',本周' }}平均:{{ averageHeight }} cm</view>
 
       <view class="list">
-        <view v-if="records.length === 0" class="empty">本月暂无身高记录,点击右下角 + 添加</view>
+        <view v-if="records.length === 0" class="empty">{{ viewMode === 'month' ? '本月' : '本周' }}暂无身高记录,点击右下角 + 添加</view>
         <view v-for="(r, idx) in records" :key="r.id" class="list-item">
           <view class="date">{{ r.date }}</view>
           <view class="value">{{ r.height }} cm</view>
@@ -88,6 +94,9 @@ type RecordItem = { id: string; date: string; height: number }
 const current = ref(new Date())
 const pickerValue = ref([current.value.getFullYear() - 2000, current.value.getMonth()]) // 年从2000年开始,月0-11
 
+// 视图模式:'month' 或 'week'
+const viewMode = ref<'month' | 'week'>('month')
+
 // 年月选择器的选项范围
 const pickerRange = ref([
   Array.from({ length: 50 }, (_, i) => `${2000 + i}年`), // 2000-2049年
@@ -119,19 +128,54 @@ function formatPickerDate(d: Date) {
 const displayYear = computed(() => current.value.getFullYear())
 const displayMonth = computed(() => current.value.getMonth() + 1)
 
+// 显示周期的计算属性
+const displayPeriod = computed(() => {
+  if (viewMode.value === 'month') {
+    return `${displayYear.value}年 ${displayMonth.value}月`
+  } else {
+    // 周视图:显示该周的日期范围
+    const weekStart = getWeekStart(current.value)
+    const weekEnd = getWeekEnd(current.value)
+    return `${formatDisplayDate(weekStart)} - ${formatDisplayDate(weekEnd)}`
+  }
+})
+
 const records = ref<RecordItem[]>(generateMockRecords(current.value))
 
 function generateMockRecords(d: Date): RecordItem[] {
-  const y = d.getFullYear()
-  const m = d.getMonth()
   const arr: RecordItem[] = []
-  const n = Math.floor(Math.random() * 7)
+  let daysCount: number
+  
+  if (viewMode.value === 'month') {
+    // 月视图:生成该月的记录
+    const y = d.getFullYear()
+    const m = d.getMonth()
+    daysCount = daysInMonth(y, m)
+  } else {
+    // 周视图:生成该周的记录(7天)
+    daysCount = 7
+  }
+  
+  const n = Math.floor(Math.random() * Math.min(daysCount, 7)) // 最多7条记录
   for (let i = 0; i < n; i++) {
-    const day = Math.max(1, Math.floor(Math.random() * 28) + 1)
-    const date = new Date(y, m, day)
+    let recordDate: Date
+    
+    if (viewMode.value === 'month') {
+      const y = d.getFullYear()
+      const m = d.getMonth()
+      const day = Math.max(1, Math.floor(Math.random() * daysCount) + 1)
+      recordDate = new Date(y, m, day)
+    } else {
+      // 周视图:从周一开始
+      const weekStart = getWeekStart(d)
+      const dayOffset = Math.floor(Math.random() * 7)
+      recordDate = new Date(weekStart)
+      recordDate.setDate(weekStart.getDate() + dayOffset)
+    }
+    
     arr.push({ 
-      id: `${y}${m}${i}${Date.now()}`, 
-      date: formatDisplayDate(date), 
+      id: `${recordDate.getTime()}${i}${Date.now()}`, 
+      date: formatDisplayDate(recordDate), 
       height: 150 + Math.floor(Math.random() * 50)
     })
   }
@@ -171,6 +215,35 @@ function daysInMonth(year: number, month: number) {
   return new Date(year, month + 1, 0).getDate()
 }
 
+// 获取指定日期所在周的开始日期(星期一)
+function getWeekStart(date: Date): Date {
+  // 规范化到本地日期的00:00:00,避免时区/小时差异导致的比较不等问题
+  const d = new Date(date)
+  d.setHours(0, 0, 0, 0)
+  const day = d.getDay() // 0=周日, 1=周一, ..., 6=周六
+  const diff = day === 0 ? -6 : 1 - day // 调整为周一为开始
+  d.setDate(d.getDate() + diff)
+  d.setHours(0, 0, 0, 0)
+  return d
+}
+
+// 获取指定日期所在周的结束日期(星期日)
+function getWeekEnd(date: Date): Date {
+  const d = getWeekStart(date)
+  d.setDate(d.getDate() + 6)
+  d.setHours(0, 0, 0, 0)
+  return d
+}
+
+// 获取指定日期所在周的周数(一年中的第几周)
+function getWeekNumber(date: Date): number {
+  const d = new Date(date)
+  d.setHours(0, 0, 0, 0)
+  d.setDate(d.getDate() + 4 - (d.getDay() || 7)) // 调整到周四
+  const yearStart = new Date(d.getFullYear(), 0, 1)
+  return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7)
+}
+
 // Canvas / uCharts 绘图 - 修复版本
 const chartInstance = ref<any>(null)
 const vm = getCurrentInstance()
@@ -226,26 +299,36 @@ async function drawChart() {
 
   const year = current.value.getFullYear()
   const month = current.value.getMonth()
-  const days = daysInMonth(year, month)
-  
-  // 生成合理的categories - 只显示关键日期
-  const categories: string[] = []
-  const showLabelDays = []
-  
-  // 选择要显示的标签:1号、中间几天、最后一天
-  if (days > 0) {
-    showLabelDays.push(1) // 第1天
-    if (days > 1) showLabelDays.push(days) // 最后一天
-    // 中间添加2-3个关键点
-    if (days > 7) showLabelDays.push(Math.ceil(days / 3))
-    if (days > 14) showLabelDays.push(Math.ceil(days * 2 / 3))
-  }
+  let categories: string[] = []
+  let showLabelDays: number[] = []
   
-  for (let d = 1; d <= days; d++) {
-    if (showLabelDays.includes(d)) {
-      categories.push(`${d}日`)
-    } else {
-      categories.push('')
+  if (viewMode.value === 'month') {
+    // 月视图
+    const days = daysInMonth(year, month)
+    // 选择要显示的标签:1号、中间几天、最后一天
+    if (days > 0) {
+      showLabelDays.push(1) // 第1天
+      if (days > 1) showLabelDays.push(days) // 最后一天
+      // 中间添加2-3个关键点
+      if (days > 7) showLabelDays.push(Math.ceil(days / 3))
+      if (days > 14) showLabelDays.push(Math.ceil(days * 2 / 3))
+    }
+    
+    for (let d = 1; d <= days; d++) {
+      if (showLabelDays.includes(d)) {
+        categories.push(`${d}日`)
+      } else {
+        categories.push('')
+      }
+    }
+  } else {
+    // 周视图:显示星期一到星期日
+    const weekStart = getWeekStart(current.value)
+    const weekDays = ['一', '二', '三', '四', '五', '六', '日']
+    for (let i = 0; i < 7; i++) {
+      const date = new Date(weekStart)
+      date.setDate(weekStart.getDate() + i)
+      categories.push(`${date.getDate()}日(${weekDays[i]})`)
     }
   }
 
@@ -254,28 +337,58 @@ async function drawChart() {
   const filteredCategories: string[] = []
   // 使用Map按日聚合,保留最新记录(records 数组头部为最新)
   const dayMap = new Map<number, RecordItem>()
-  for (const r of records.value) {
-    const parts = r.date.split('-')
-    if (parts.length >= 3) {
-      const y = parseInt(parts[0], 10)
-      const m = parseInt(parts[1], 10) - 1
-      const d = parseInt(parts[2], 10)
-      if (y === year && m === month) {
-        // 以最后遍历到的(数组顺序保证头部为最新)作为最终值
-        dayMap.set(d, r)
+  
+  if (viewMode.value === 'month') {
+    // 月视图:按日期聚合
+    for (const r of records.value) {
+      const parts = r.date.split('-')
+      if (parts.length >= 3) {
+        const y = parseInt(parts[0], 10)
+        const m = parseInt(parts[1], 10) - 1
+        const d = parseInt(parts[2], 10)
+        if (y === year && m === month) {
+          // 以最后遍历到的(数组顺序保证头部为最新)作为最终值
+          dayMap.set(d, r)
+        }
+      }
+    }
+    
+    // 将有数据的日期按日顺序输出
+    const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b)
+    for (const d of sortedDays) {
+      const rec = dayMap.get(d)!
+      filteredCategories.push(`${d}日`)
+      data.push(rec.height)
+    }
+  } else {
+    // 周视图:按星期聚合
+    const weekStart = getWeekStart(current.value)
+    for (const r of records.value) {
+      const parts = r.date.split('-')
+      if (parts.length >= 3) {
+        const recordDate = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10))
+        const weekStartDate = getWeekStart(recordDate)
+        // 检查记录是否在本周内
+        if (weekStartDate.getTime() === weekStart.getTime()) {
+          const dayOfWeek = recordDate.getDay() || 7 // 0=周日,转换为7
+          dayMap.set(dayOfWeek, r)
+        }
+      }
+    }
+    
+    // 按星期一到星期日顺序输出
+    const weekDays = ['一', '二', '三', '四', '五', '六', '日']
+    for (let i = 1; i <= 7; i++) {
+      const rec = dayMap.get(i)
+      if (rec) {
+        const date = new Date(rec.date)
+        filteredCategories.push(`${date.getDate()}日(${weekDays[i-1]})`)
+        data.push(rec.height)
       }
     }
   }
 
-  // 将有数据的日期按日顺序输出
-  const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b)
-  for (const d of sortedDays) {
-    const rec = dayMap.get(d)!
-    filteredCategories.push(`${d}日`)
-    data.push(rec.height)
-  }
-
-  // 如果没有任何数据,则回退为整月空数据(避免 uCharts 抛错)
+  // 如果没有任何数据,则回退为整月/周空数据(避免 uCharts 抛错)
   const categoriesToUse = filteredCategories.length ? filteredCategories : categories
 
   // 计算合理的Y轴范围
@@ -444,23 +557,35 @@ async function updateChartData() {
 
   const year = current.value.getFullYear()
   const month = current.value.getMonth()
-  const days = daysInMonth(year, month)
   
-  const categories: string[] = []
-  const showLabelDays = []
+  let categories: string[] = []
+  let showLabelDays: number[] = []
   
-  if (days > 0) {
-    showLabelDays.push(1)
-    if (days > 1) showLabelDays.push(days)
-    if (days > 7) showLabelDays.push(Math.ceil(days / 3))
-    if (days > 14) showLabelDays.push(Math.ceil(days * 2 / 3))
-  }
-  
-  for (let d = 1; d <= days; d++) {
-    if (showLabelDays.includes(d)) {
-      categories.push(`${d}日`)
-    } else {
-      categories.push('')
+  if (viewMode.value === 'month') {
+    // 月视图
+    const days = daysInMonth(year, month)
+    if (days > 0) {
+      showLabelDays.push(1)
+      if (days > 1) showLabelDays.push(days)
+      if (days > 7) showLabelDays.push(Math.ceil(days / 3))
+      if (days > 14) showLabelDays.push(Math.ceil(days * 2 / 3))
+    }
+    
+    for (let d = 1; d <= days; d++) {
+      if (showLabelDays.includes(d)) {
+        categories.push(`${d}日`)
+      } else {
+        categories.push('')
+      }
+    }
+  } else {
+    // 周视图
+    const weekStart = getWeekStart(current.value)
+    const weekDays = ['一', '二', '三', '四', '五', '六', '日']
+    for (let i = 0; i < 7; i++) {
+      const date = new Date(weekStart)
+      date.setDate(weekStart.getDate() + i)
+      categories.push(`${date.getDate()}日(${weekDays[i]})`)
     }
   }
 
@@ -468,23 +593,49 @@ async function updateChartData() {
   const data: number[] = []
   const filteredCategories: string[] = []
   const dayMap = new Map<number, RecordItem>()
-  for (const r of records.value) {
-    const parts = r.date.split('-')
-    if (parts.length >= 3) {
-      const y = parseInt(parts[0], 10)
-      const m = parseInt(parts[1], 10) - 1
-      const d = parseInt(parts[2], 10)
-      if (y === year && m === month) {
-        dayMap.set(d, r)
+  
+  if (viewMode.value === 'month') {
+    for (const r of records.value) {
+      const parts = r.date.split('-')
+      if (parts.length >= 3) {
+        const y = parseInt(parts[0], 10)
+        const m = parseInt(parts[1], 10) - 1
+        const d = parseInt(parts[2], 10)
+        if (y === year && m === month) {
+          dayMap.set(d, r)
+        }
+      }
+    }
+    const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b)
+    for (const d of sortedDays) {
+      const rec = dayMap.get(d)!
+      filteredCategories.push(`${d}日`)
+      data.push(rec.height)
+    }
+  } else {
+    const weekStart = getWeekStart(current.value)
+    for (const r of records.value) {
+      const parts = r.date.split('-')
+      if (parts.length >= 3) {
+        const recordDate = new Date(parseInt(parts[0], 10), parseInt(parts[1], 10) - 1, parseInt(parts[2], 10))
+        const weekStartDate = getWeekStart(recordDate)
+        if (weekStartDate.getTime() === weekStart.getTime()) {
+          const dayOfWeek = recordDate.getDay() || 7
+          dayMap.set(dayOfWeek, r)
+        }
+      }
+    }
+    const weekDays = ['一', '二', '三', '四', '五', '六', '日']
+    for (let i = 1; i <= 7; i++) {
+      const rec = dayMap.get(i)
+      if (rec) {
+        const date = new Date(rec.date)
+        filteredCategories.push(`${date.getDate()}日(${weekDays[i-1]})`)
+        data.push(rec.height)
       }
     }
   }
-  const sortedDays = Array.from(dayMap.keys()).sort((a, b) => a - b)
-  for (const d of sortedDays) {
-    const rec = dayMap.get(d)!
-    filteredCategories.push(`${d}日`)
-    data.push(rec.height)
-  }
+  
   const categoriesToUse = filteredCategories.length ? filteredCategories : categories
 
   const validData = data.filter(v => v > 0)
@@ -603,24 +754,41 @@ async function rebuildChart() {
 }
 
 // 其他函数保持不变
-async function prevMonth() {
+async function prevPeriod() {
   const d = new Date(current.value)
-  d.setMonth(d.getMonth() - 1)
+  if (viewMode.value === 'month') {
+    d.setMonth(d.getMonth() - 1)
+  } else {
+    d.setDate(d.getDate() - 7) // 前一周
+  }
   current.value = d
   pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
   records.value = generateMockRecords(d)
   await rebuildChart()
 }
 
-async function nextMonth() {
+async function nextPeriod() {
   const d = new Date(current.value)
-  d.setMonth(d.getMonth() + 1)
+  if (viewMode.value === 'month') {
+    d.setMonth(d.getMonth() + 1)
+  } else {
+    d.setDate(d.getDate() + 7) // 后一周
+  }
   current.value = d
   pickerValue.value = [d.getFullYear() - 2000, d.getMonth()]
   records.value = generateMockRecords(d)
   await rebuildChart()
 }
 
+async function setViewMode(mode: 'month' | 'week') {
+  if (viewMode.value !== mode) {
+    viewMode.value = mode
+    // 重新生成数据和图表
+    records.value = generateMockRecords(current.value)
+    await rebuildChart()
+  }
+}
+
 async function onPickerChange(e: any) {
   const val = e?.detail?.value || e
   if (Array.isArray(val) && val.length >= 2) {
@@ -674,7 +842,20 @@ async function confirmAdd() {
   const parts = addDate.value.split('-')
   const addY = parseInt(parts[0], 10)
   const addM = parseInt(parts[1], 10) - 1
-  if (addY === current.value.getFullYear() && addM === current.value.getMonth()) {
+  const addD = parseInt(parts[2], 10)
+  const addDateObj = new Date(addY, addM, addD)
+  
+  // 检查是否在当前周期内
+  let isInCurrentPeriod = false
+  if (viewMode.value === 'month') {
+    isInCurrentPeriod = addY === current.value.getFullYear() && addM === current.value.getMonth()
+  } else {
+    const weekStart = getWeekStart(current.value)
+    const recordWeekStart = getWeekStart(addDateObj)
+    isInCurrentPeriod = weekStart.getTime() === recordWeekStart.getTime()
+  }
+  
+  if (isInCurrentPeriod) {
     records.value = [item, ...records.value]
   }
   uni.showToast && uni.showToast({ title: '已添加', icon: 'success' })
@@ -725,6 +906,35 @@ async function confirmDeleteRecord(id: string) {
   gap: 12rpx 
 }
 
+.period-controls {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  gap: 8rpx;
+}
+
+.view-toggle {
+  display: flex;
+  gap: 4rpx;
+}
+
+.toggle-btn {
+  padding: 4rpx 12rpx;
+  border: 1rpx solid #ddd;
+  background: #f5f5f5;
+  color: #666;
+  border-radius: 6rpx;
+  font-size: 24rpx;
+  min-width: 60rpx;
+  text-align: center;
+}
+
+.toggle-btn.active {
+  background: #ff6a00;
+  color: #fff;
+  border-color: #ff6a00;
+}
+
 .month-label { 
   font-size: 34rpx; 
   color: #333