<template>
  <view class="feeding-analysis-page">
    <!-- 状态栏占位 -->
    <view class="status-bar-placeholder"></view>

    <!-- 头部导航 -->
    <view class="header">
      <view class="nav-left" @click="goBack">
        <text class="back-btn">‹</text>
      </view>
    </view>

    <!-- 图例 -->
    <view class="legend-section">
      <view class="legend-item">
        <view class="legend-color legend-breastfeeding"></view>
        <text class="legend-text">母乳亲喂</text>
      </view>
      <view class="legend-item">
        <view class="legend-color legend-bottle"></view>
        <text class="legend-text">母乳瓶喂</text>
      </view>
      <view class="legend-item">
        <view class="legend-color legend-formula"></view>
        <text class="legend-text">奶粉喂养</text>
      </view>
      <view class="legend-item">
        <view class="legend-color legend-food"></view>
        <text class="legend-text">辅食</text>
      </view>
    </view>

    <!-- CSS柱状图区域 -->
    <view class="chart-section">
      <view class="chart-container">
        <view class="chart-nav-left" @click="prevWeek">
          <view class="nav-arrow">‹</view>
        </view>
        <view class="chart-content">
          <view class="chart-bars">
            <view 
              v-for="(day, index) in chartData" 
              :key="index"
              class="chart-bar-wrapper"
              :class="{ active: day.isActive }"
            >
              <view class="chart-bar">
                <view 
                  v-for="(typeData, typeIndex) in getBarSegments(day)" 
                  :key="typeIndex"
                  class="bar-segment"
                  :style="{
                    height: `${typeData.height}%`,
                    backgroundColor: typeData.color
                  }"
                ></view>
              </view>
              <view class="bar-count" v-if="day.isActive && day.totalCount > 0">
                {{ day.totalCount }}次
              </view>
              <view class="bar-date">{{ day.date }}</view>
            </view>
          </view>
        </view>
        <view class="chart-nav-right" @click="nextWeek">
          <view class="nav-arrow">›</view>
        </view>
      </view>
      
      <!-- 宝宝年龄 -->
      <view class="baby-age">
        <text>宝宝 5个月20天</text>
      </view>
    </view>

    <!-- 喂养记录列表 -->
    <scroll-view class="records-container" scroll-y>
      <view v-if="todayRecords.length === 0" class="empty-state">
        <text class="empty-text">当日暂无记录</text>
      </view>
      <view v-else class="record-list">
        <template v-for="(record, index) in todayRecords" :key="index">
          <view class="record-item">
            <view class="time-dot">
              <view class="dot" :style="{ backgroundColor: getRecordColor(record.type) }"></view>
              <text class="time">{{ record.time }}</text>
            </view>
            <view class="record-content" :style="{ backgroundColor: getRecordBgColor(record.type) }">
              <view class="record-header">
                <image :src="getRecordIcon(record.type)" :class="getRecordIconClass(record.type)" />
                <text class="record-type">{{ record.type }}</text>
                <text class="edit-btn" @click="editRecord(index)">修改</text>
              </view>
              <view class="record-details">
                <!-- 母乳亲喂：显示左右时间，时间加粗 -->
                <view v-if="record.type === '母乳亲喂' && (record.leftDuration || record.rightDuration)"
                  class="duration-info">
                  <view v-if="record.leftDuration" class="duration-text">
                    <text class="duration-label">左</text>
                    <text class="duration-time">{{ record.leftDuration }}</text>
                  </view>
                  <view v-if="record.rightDuration" class="duration-text">
                    <text class="duration-label">右</text>
                    <text class="duration-time">{{ record.rightDuration }}</text>
                  </view>
                </view>

                <!-- 母乳瓶喂：显示总乳量 -->
                <view v-if="record.type === '母乳瓶喂' && record.amount" class="amount-info">
                  <view class="amount-text">
                    <text class="amount-label">总乳量</text>
                    <text class="amount-value">{{ record.amount }}</text>
                  </view>
                </view>

                <!-- 奶粉喂养：显示总奶量 -->
                <view v-if="record.type === '奶粉喂养' && record.amount" class="amount-info">
                  <view class="amount-text">
                    <text class="amount-label">总奶量</text>
                    <text class="amount-value">{{ record.amount }}</text>
                  </view>
                </view>

                <!-- 辅食：显示内容，超出显示... -->
                <view v-if="record.type === '辅食' && record.content" class="content-info">
                  <view class="content-text">{{ record.content }}</view>
                </view>
              </view>
            </view>
          </view>
          <!-- 在两个记录之间添加连接线 -->
          <view v-if="index < todayRecords.length - 1" class="timeline-connector"></view>
        </template>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const version = 'v1'

// 资源路径
const feedingRecordRes = {
  icon_fushi: `/static/feedingRecord/${version}/icon_fushi.png`,
  icon_muru: `/static/feedingRecord/${version}/icon_muru.png`,
  icon_naifen: `/static/feedingRecord/${version}/icon_naifen.png`,
  icon_pingwei: `/static/feedingRecord/${version}/icon_pingwei.png`,
}

// 响应式数据
const currentWeek = ref(0) // 当前显示的周数
const selectedDate = ref('2025-07-03') // 当前选中的日期
const chartData = ref([])

// 喂养记录数据
const feedingRecords = ref({
  '2025-07-03': [
    {
      time: '06:20',
      type: '母乳亲喂',
      leftDuration: '10min',
      rightDuration: '10min'
    },
    {
      time: '09:30',
      type: '母乳瓶喂',
      amount: '约50ml'
    },
    {
      time: '13:50',
      type: '奶粉喂养',
      amount: '约50ml'
    },
    {
      time: '17:25',
      type: '辅食',
      content: '小米粥,玉米,馒头,煮面条,包子,奶糊...'
    }
  ],
  '2025-07-02': [
    {
      time: '07:00',
      type: '母乳亲喂',
      leftDuration: '12min',
      rightDuration: '8min'
    },
    {
      time: '11:30',
      type: '母乳瓶喂',
      amount: '约80ml'
    }
  ],
  '2025-07-01': [
    {
      time: '08:30',
      type: '母乳亲喂',
      leftDuration: '15min',
      rightDuration: '12min'
    }
  ],
  '2025-07-04': [
    {
      time: '06:00',
      type: '奶粉喂养',
      amount: '约60ml'
    },
    {
      time: '12:00',
      type: '辅食',
      content: '鸡蛋羹,胡萝卜泥'
    }
  ],
  '2025-07-05': [
    {
      time: '07:30',
      type: '母乳亲喂',
      leftDuration: '8min',
      rightDuration: '10min'
    },
    {
      time: '15:00',
      type: '辅食',
      content: '苹果泥,香蕉'
    }
  ],
  '2025-07-06': [
    {
      time: '09:00',
      type: '辅食',
      content: '南瓜粥,土豆泥'
    }
  ],
  '2025-07-07': [
    {
      time: '08:00',
      type: '母乳瓶喂',
      amount: '约70ml'
    },
    {
      time: '14:00',
      type: '奶粉喂养',
      amount: '约40ml'
    }
  ]
})

// 计算属性 - 当前选中日期的记录
const todayRecords = computed(() => {
  if (!selectedDate.value) return []
  return feedingRecords.value[selectedDate.value] || []
})

// 计算属性 - 当周最大次数
const maxWeekCount = computed(() => {
  if (chartData.value.length === 0) return 0
  return Math.max(...chartData.value.map(d => d.totalCount))
})

// 获取记录颜色 - 根据设计稿调整
function getRecordColor(type) {
  const colors = {
    '母乳亲喂': '#F9D9D9', // 浅粉色
    '母乳瓶喂': '#D9D9F9', // 浅紫色
    '奶粉喂养': '#F9E9D9', // 浅橙色/米色
    '辅食': '#D9F9D9' // 浅绿色
  }
  return colors[type] || '#CCCCCC'
}

// 获取记录背景色 - 根据设计稿调整
function getRecordBgColor(type) {
  const colors = {
    '母乳亲喂': '#F9D9D9', // 浅粉色
    '母乳瓶喂': '#D9D9F9', // 浅紫色
    '奶粉喂养': '#F9E9D9', // 浅橙色/米色
    '辅食': '#D9F9D9' // 浅绿色
  }
  return colors[type] || '#F5F5F5'
}

// 获取类型颜色
function getTypeColor(type) {
  const colors = {
    '母乳亲喂': '#F9D9D9', // 浅粉色
    '母乳瓶喂': '#D9D9F9', // 浅紫色
    '奶粉喂养': '#F9E9D9', // 浅橙色/米色
    '辅食': '#D9F9D9' // 浅绿色
  }
  return colors[type] || '#CCCCCC'
}

// 获取记录图标
function getRecordIcon(type) {
  const icons = {
    '母乳亲喂': feedingRecordRes.icon_muru,
    '母乳瓶喂': feedingRecordRes.icon_pingwei,
    '奶粉喂养': feedingRecordRes.icon_naifen,
    '辅食': feedingRecordRes.icon_fushi
  }
  return icons[type] || ''
}

// 获取记录图标样式类
function getRecordIconClass(type) {
  const classes = {
    '母乳亲喂': 'record-icon-img-muruqinwei',
    '母乳瓶喂': 'record-icon-img-pingwei',
    '奶粉喂养': 'record-icon-img-naifen',
    '辅食': 'record-icon-img-fushi'
  }
  return classes[type] || ''
}

// 编辑记录
function editRecord(index) {
  console.log('编辑记录:', index)
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 生成周数据
function generateWeekData(weekOffset = 0) {
  const data = []
  const baseDate = new Date('2025-07-03')
  baseDate.setDate(baseDate.getDate() + weekOffset * 7)
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(baseDate)
    date.setDate(date.getDate() + i)
    const dateString = date.toISOString().split('T')[0]
    const records = feedingRecords.value[dateString] || []
    
    // 统计各类型记录数量
    const typeCounts = {
      '母乳亲喂': 0,
      '母乳瓶喂': 0,
      '奶粉喂养': 0,
      '辅食': 0
    }
    
    records.forEach(record => {
      if (typeCounts.hasOwnProperty(record.type)) {
        typeCounts[record.type]++
      }
    })
    
    data.push({
      date: `${date.getMonth() + 1}/${date.getDate()}`,
      dateString,
      isActive: dateString === selectedDate.value,
      totalCount: records.length,
      typeCounts
    })
  }
  
  return data
}

// 上一周
function prevWeek() {
  currentWeek.value--
  updateChartData()
}

// 下一周
function nextWeek() {
  currentWeek.value++
  updateChartData()
}

// 更新图表数据
function updateChartData() {
  chartData.value = generateWeekData(currentWeek.value)
}

// 选择日期
function selectDate(dateString) {
  selectedDate.value = dateString
  updateChartData()
}

// 获取柱状图段数据
function getBarSegments(day) {
  const segments = [];
  const totalCount = day.totalCount;

  if (totalCount === 0 || maxWeekCount.value === 0) {
    return segments;
  }

  // 定义类型顺序和颜色
  const typeOrder = ['母乳亲喂', '母乳瓶喂', '奶粉喂养', '辅食'];
  const typeColors = {
    '母乳亲喂': '#F9D9D9', // 浅粉色
    '母乳瓶喂': '#D9D9F9', // 浅紫色
    '奶粉喂养': '#F9E9D9', // 浅橙色/米色
    '辅食': '#D9F9D9' // 浅绿色
  };

  // 按顺序添加有数据的类型，从底部向上堆叠
  typeOrder.forEach(type => {
    if (day.typeCounts[type] > 0) {
      // 计算该类型在当周最大次数中的占比
      const height = (day.typeCounts[type] / maxWeekCount.value) * 100;
      segments.push({
        height: height,
        color: typeColors[type]
      });
    }
  });

  return segments;
}

// 页面加载
onLoad(() => {
  updateChartData()
})

// 监听选中日期变化
watch(selectedDate, () => {
  updateChartData()
})
</script>

<style lang="scss" scoped>
.feeding-analysis-page {
  min-height: 100vh;
  background: #FDFBF7; // 根据设计稿调整背景色
  display: flex;
  flex-direction: column;
}

// 状态栏占位
.status-bar-placeholder {
  height: 75rpx;
  background: #FDFBF7;
}

// 头部导航
.header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #FDFBF7;

  .nav-left {
    display: flex;
    align-items: center;
    padding: 15rpx;

    .back-btn {
      font-size: 40rpx;
      color: #000000; // 黑色箭头
      font-weight: bold;
      line-height: 1;
    }
  }
}

// 图例
.legend-section {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 25rpx 40rpx;
  background: #FDFBF7;

  .legend-item {
    display: flex;
    align-items: center;
    gap: 12rpx;

    .legend-color {
      width: 32rpx; // 16px * 2
      height: 32rpx; // 16px * 2
      border-radius: 6rpx; // 稍微圆角

      &.legend-breastfeeding {
        background: #F9D9D9; // 浅粉色
      }

      &.legend-bottle {
        background: #D9D9F9; // 浅紫色
      }

      &.legend-formula {
        background: #F9E9D9; // 浅橙色/米色
      }

      &.legend-food {
        background: #D9F9D9; // 浅绿色
      }
    }

    .legend-text {
      font-size: 26rpx;
      color: #000000; // 黑色文字
      font-weight: 500;
    }
  }
}

// CSS柱状图区域
.chart-section {
  background: #FDFBF7;
  padding: 30rpx 0;

  .chart-container {
    display: flex;
    align-items: center;
    padding: 0 30rpx;

    .chart-nav-left,
    .chart-nav-right {
      width: 70rpx;
      height: 70rpx;
      background: #FDFBF7; // 浅米色背景
      border-radius: 35rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 15rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

      .nav-arrow {
        font-size: 28rpx;
        color: #000000; // 黑色箭头
        font-weight: bold;
        line-height: 1;
      }
    }

    .chart-content {
      flex: 1;
      margin: 0 25rpx;
      height: 220rpx;
      background: transparent; // 去掉背景色
      border-radius: 16rpx;
      padding: 20rpx;
      // 去掉阴影

      .chart-bars {
        display: flex;
        align-items: flex-end; // 从底部对齐
        justify-content: space-between;
        height: 100%;
        padding: 20rpx 0 40rpx 0;
        box-sizing: border-box;
        position: relative;

        .chart-bar-wrapper {
          display: flex;
          flex-direction: column;
          align-items: center;
          flex: 1;
          position: relative;
          padding: 0 10rpx;

          &.active {
            .chart-bar {
              // 选中状态不需要背景色，保持透明
            }
            
            // 选中状态的背景显示在日期文字后面
            .bar-date {
              background: #F0EFEA;
              padding: 4rpx 8rpx;
              border-radius: 4rpx;
            }
          }

          .chart-bar {
            width: 60rpx;
            height: 120rpx;
            display: flex;
            flex-direction: column;
            // 移除容器的border-radius，让内部段自己控制圆角
            position: relative;
            background: transparent;
            justify-content: flex-end; // 确保段从底部开始

            .bar-segment {
              width: 100%;
              min-height: 10rpx;
              transition: height 0.3s ease;
              flex-shrink: 0;
              
              // 如果只有一个段，整个柱子都有圆角
              &:only-child {
                border-radius: 8rpx !important;
              }
              
              // 多个段的情况
              &:not(:only-child) {
                // 第一个段（底部）有底部圆角
                &:first-child {
                  border-top-left-radius: 8rpx !important;
                  border-top-right-radius: 8rpx !important;
                }
                
                // 最后一个段（顶部）有顶部圆角
                &:last-child {
                  border-bottom-left-radius: 8rpx !important;
                  border-bottom-right-radius: 8rpx !important;
                }
                
                // 中间段没有圆角
                &:not(:first-child):not(:last-child) {
                  border-radius: 0 !important;
                }
              }
            }
          }

          .bar-count {
            position: absolute;
            top: -30rpx; // 调整位置到柱子顶部上方
            left: 50%;
            transform: translateX(-50%);
            font-size: 20rpx;
            color: #C89F6B;
            font-weight: bold;
            white-space: nowrap;
            z-index: 3;
          }

          .bar-date {
            margin-top: 10rpx;
            font-size: 24rpx;
            color: #666666;
            font-weight: 500;
          }

          &.active .bar-date {
            color: #C89F6B;
            font-weight: bold;
          }
        }
      }
    }
  }

  .baby-age {
    text-align: center;
    padding: 25rpx 0;

    text {
      font-size: 26rpx;
      color: #000000; // 黑色文字
      font-weight: bold; // 加粗
    }
  }
}

// 记录列表
.records-container {
  flex: 1;
  background: #FDFBF7; // 与背景色一致
  border-radius: 32rpx 32rpx 0 0;
  margin-top: 20rpx;
  padding: 30rpx 0 0 0;

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300rpx;

    .empty-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  .record-list {
    padding: 0 30rpx 30rpx 30rpx;

    .record-item {
      display: flex;
      margin-bottom: 50rpx;
      position: relative;

      .time-dot {
        width: 140rpx;
        display: flex;
        align-items: flex-start;
        padding-top: 35rpx;
        margin-right: 20rpx;
        flex-shrink: 0;

        .dot {
          width: 18rpx;
          height: 18rpx;
          border-radius: 50%;
          margin-right: 20rpx;
          margin-top: 10rpx;
          flex-shrink: 0;
        }

        .time {
          font-size: 26rpx;
          color: #000000; // 黑色文字
          line-height: 1.4;
          font-weight: bold; // 加粗
        }
      }

      .record-content {
        flex: 1;
        min-height: 160rpx;
        border-radius: 24rpx;
        padding: 28rpx;
        box-sizing: border-box;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);

        .record-header {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;

          .record-icon-img-muruqinwei,
          .record-icon-img-pingwei,
          .record-icon-img-naifen,
          .record-icon-img-fushi {
            width: 36rpx;
            height: 36rpx;
            margin-right: 16rpx;
            flex-shrink: 0;
          }

          .record-type {
            flex: 1;
            font-size: 30rpx;
            font-weight: 600;
            color: #000000; // 黑色文字
            line-height: 1.4;
          }

          .edit-btn {
            font-size: 24rpx;
            color: #AAAAAA; // 浅灰色文字
            padding: 10rpx 20rpx;
            border: 1rpx solid #E0E0E0; // 浅灰色边框
            border-radius: 20rpx;
            background: #F5F5F5; // 浅灰色背景
            opacity: 0.9;
            font-weight: 500;
          }
        }

        .record-details {
          .duration-info,
          .amount-info {
            .duration-text,
            .amount-text {
              display: flex;
              align-items: center;
              gap: 20rpx;
              margin-bottom: 12rpx;

              &:last-child {
                margin-bottom: 0;
              }

              .duration-label,
              .amount-label {
                font-size: 26rpx;
                color: #000000; // 黑色文字
                font-weight: 500;
                min-width: 60rpx;
              }

              .duration-time,
              .amount-value {
                font-size: 26rpx;
                color: #000000; // 黑色文字
                font-weight: 600;
              }
            }
          }

          .content-info {
            .content-text {
              font-size: 26rpx;
              color: #000000; // 黑色文字
              font-weight: 600;
              line-height: 1.5;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              max-width: 100%;
            }
          }
        }
      }
    }

    .timeline-connector {
      width: 3rpx;
      height: 50rpx;
      background: #E0E0E0; // 浅灰色连接线
      margin-left: 25rpx;
      margin-top: -25rpx;
      margin-bottom: -25rpx;
      border-radius: 2rpx;
    }
  }
}

// 响应式适配
@media screen and (max-width: 750rpx) {
  .legend-section {
    padding: 25rpx 30rpx;
    
    .legend-item {
      gap: 8rpx;
      
      .legend-color {
        width: 20rpx;
        height: 20rpx;
      }
      
      .legend-text {
        font-size: 24rpx;
      }
    }
  }
  
  .chart-section {
    .chart-container {
      padding: 0 20rpx;
      
      .chart-nav-left,
      .chart-nav-right {
        width: 60rpx;
        height: 60rpx;
        margin: 0 10rpx;
      }
      
      .chart-content {
        margin: 0 20rpx;
        height: 200rpx;
      }
    }
  }
  
  .records-container {
    .record-list {
      padding: 0 20rpx 30rpx 20rpx;
      
      .record-item {
        .time-dot {
          width: 120rpx;
          margin-right: 15rpx;
        }
        
        .record-content {
          padding: 24rpx;
        }
      }
    }
  }
}
</style>
