<!--
 * @Author: chris
 * @Date: 2025-10-22 10:46:12
 * @LastEditors: chris
 * @LastEditTime: 2025-10-22 11:24:24
-->
<script setup lang="ts">
// 定义页面标题
definePage({
  navigationBarTitleText: '土壤检测',
})

// 土壤指标类型定义
interface SoilIndicator {
  id: string
  name: string
  value: number
  unit: string
  color: string
  description: string
}

// 时间序列数据类型
interface TimeSeriesData {
  time: string
  value: number
}

// 模拟的土壤指标数据
const soilIndicators: SoilIndicator[] = [
  { id: 'temperature', name: '温度', value: 25.5, unit: '°C', color: '#FF6B6B', description: '土壤温度' },
  { id: 'humidity', name: '湿度', value: 65.2, unit: '%', color: '#4ECDC4', description: '土壤湿度' },
  { id: 'ph', name: 'pH值', value: 6.8, unit: '', color: '#45B7D1', description: '土壤酸碱度' },
  { id: 'ec', name: '电导率', value: 2.3, unit: 'mS/cm', color: '#FF8C42', description: '土壤电导率(EC)' },
  { id: 'nitrogen', name: '氮含量', value: 120, unit: 'mg/kg', color: '#96CEB4', description: '土壤氮含量' },
  { id: 'phosphorus', name: '磷含量', value: 45, unit: 'mg/kg', color: '#FFEAA7', description: '土壤磷含量' },
  { id: 'potassium', name: '钾含量', value: 180, unit: 'mg/kg', color: '#DDA0DD', description: '土壤钾含量' },
]

// 当前选中的指标
const selectedIndicator = ref<string>('temperature')

// 生成模拟的24小时时间序列数据
function generateTimeSeriesData(indicatorId: string): TimeSeriesData[] {
  const data: TimeSeriesData[] = []
  const now = new Date()

  // 根据不同指标设置不同的波动范围
  let baseValue = 0
  let min = 0
  let max = 0

  switch (indicatorId) {
    case 'temperature':
      baseValue = 25
      min = 20
      max = 30
      break
    case 'humidity':
      baseValue = 65
      min = 50
      max = 80
      break
    case 'ph':
      baseValue = 6.8
      min = 5.5
      max = 8.0
      break
    case 'ec':
      baseValue = 2.3
      min = 0.5
      max = 4.0
      break
    case 'nitrogen':
      baseValue = 120
      min = 80
      max = 160
      break
    case 'phosphorus':
      baseValue = 45
      min = 20
      max = 70
      break
    case 'potassium':
      baseValue = 180
      min = 140
      max = 220
      break
  }

  // 生成24小时的数据
  for (let i = 23; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 60 * 60 * 1000)
    const hour = time.getHours()
    // 添加一些时间相关的波动
    const timeFactor = Math.sin((hour / 24) * Math.PI * 2) * 0.1
    // 添加随机波动
    const randomFactor = (Math.random() - 0.5) * 0.2
    let value = baseValue * (1 + timeFactor + randomFactor)

    // 确保值在合理范围内
    value = Math.max(min, Math.min(max, value))

    // 根据指标类型格式化值
    if (indicatorId === 'ph' || indicatorId === 'ec') {
      value = Number.parseFloat(value.toFixed(1))
    }
    else {
      value = Math.round(value * 10) / 10
    }

    data.push({
      time: `${hour.toString().padStart(2, '0')}:00`,
      value,
    })
  }

  return data
};

// 时间序列数据
const timeSeriesData = ref<TimeSeriesData[]>([])

// 图表配置
const chartOption = ref<any>({})

// 切换选中的指标
function handleIndicatorClick(indicatorId: string) {
  selectedIndicator.value = indicatorId
  updateChart()
};

// 更新图表
function updateChart() {
  const currentIndicator = soilIndicators.find(ind => ind.id === selectedIndicator.value)
  if (!currentIndicator)
    return

  timeSeriesData.value = generateTimeSeriesData(selectedIndicator.value)

  chartOption.value = {
    title: {
      text: `${currentIndicator.name} 24小时变化趋势`,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
      },
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const data = params[0]
        return `${data.axisValue}<br/>${currentIndicator.name}: ${data.value} ${currentIndicator.unit}`
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '20%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: timeSeriesData.value.map(item => item.time),
      axisLabel: {
        rotate: 45,
        fontSize: 10,
      },
    },
    yAxis: {
      type: 'value',
      name: currentIndicator.unit,
      nameLocation: 'middle',
      nameGap: 30,
    },
    series: [
      {
        data: timeSeriesData.value.map(item => item.value),
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: currentIndicator.color,
        },
        lineStyle: {
          width: 2,
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: `${currentIndicator.color}80`, // 80是透明度
              },
              {
                offset: 1,
                color: `${currentIndicator.color}20`, // 20是透明度
              },
            ],
          },
        },
      },
    ],
  }
};

// 页面加载时初始化数据
onMounted(() => {
  updateChart()
})
</script>

<template>
  <view class="soil-monitor-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="header-title">土壤检测数据</text>
      <text class="header-subtitle">实时监测土壤各项指标</text>
    </view>

    <!-- 土壤指标卡片网格 -->
    <view class="indicators-grid">
      <view
        v-for="indicator in soilIndicators"
        :key="indicator.id"
        class="indicator-card"
        :class="{ active: selectedIndicator === indicator.id }"
        :style="{ borderColor: indicator.color }"
        @click="handleIndicatorClick(indicator.id)"
      >
        <view class="indicator-name">
          {{ indicator.name }}
        </view>
        <view class="indicator-value" :style="{ color: indicator.color }">
          {{ indicator.value }}<span class="indicator-unit">{{ indicator.unit }}</span>
        </view>
        <view class="indicator-description">
          {{ indicator.description }}
        </view>
      </view>
    </view>

    <!-- 曲线图区域 -->
    <view class="chart-container">
      <lime-echart
        class="soil-chart"
        :option="chartOption"
        :canvas-id="`soil-chart-${selectedIndicator}`"
        :lazy-load="true"
      />
    </view>
  </view>
</template>

<style lang="scss" scoped>
.soil-monitor-page {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-subtitle {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-top: 10rpx;
}

.indicators-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300rpx, 1fr));
  gap: 20rpx;
  margin-bottom: 30rpx;
  justify-content: center;
}

.indicator-card {
  background-color: #fff;
  padding: 16rpx 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border-left: 8rpx solid #e0e0e0;
  transition: all 0.3s ease;
  cursor: pointer;
  min-width: 280rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 120rpx;
  height: auto;
}

.indicator-card.active {
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  transform: translateY(-2rpx);
}

.indicator-name {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 4rpx;
}

.indicator-value {
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 2rpx;
}

.indicator-unit {
  font-size: 22rpx;
  font-weight: normal;
  margin-left: 4rpx;
}

.indicator-description {
  font-size: 18rpx;
  color: #999;
  margin-top: 4rpx;
}

.chart-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  height: 600rpx;
}

.soil-chart {
  width: 100%;
  height: 100%;
}

// 响应式调整
@media screen and (min-width: 768px) {
  .indicators-grid {
    grid-template-columns: repeat(3, 1fr);
    max-width: 900px;
    margin-left: auto;
    margin-right: auto;
  }

  // 处理7个项目的特殊排列 - 使用auto-fit代替固定列数，让第7个卡片居中
  .indicators-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280rpx, 1fr));
    gap: 24rpx;
    justify-items: center;
  }

  // 对于平板，确保7个项目有更好的分布
  .indicators-grid {
    --auto-grid-min-size: 280rpx;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(var(--auto-grid-min-size), 1fr));
    grid-gap: 24rpx;
    justify-content: center;
  }

  // 确保每个卡片都有相同的最小宽度
  .indicator-card {
    min-width: 280rpx;
    width: 100%;
    max-width: 320rpx;
  }
}

@media screen and (min-width: 1024px) {
  .indicators-grid {
    max-width: 1200px;
    --auto-grid-min-size: 260rpx;
  }

  // 对于桌面端，7个卡片可以采用更均匀的分布
  .indicators-grid {
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: auto auto;
  }

  // 重新排列第5-7个卡片，使布局更平衡
  .indicators-grid > .indicator-card:nth-child(5) {
    grid-column: 1;
    grid-row: 2;
  }
  .indicators-grid > .indicator-card:nth-child(6) {
    grid-column: 2;
    grid-row: 2;
  }
  .indicators-grid > .indicator-card:nth-child(7) {
    grid-column: 3;
    grid-row: 2;
    grid-column-end: 5; /* 让第7个卡片占据更宽的空间，平衡布局 */
    max-width: none;
  }

  // 调整第7个卡片的内部布局，使其内容居中显示
  .indicators-grid > .indicator-card:nth-child(7) {
    display: grid;
    grid-template-columns: 1fr 1fr;
    align-items: center;
    text-align: center;
  }

  .indicators-grid > .indicator-card:nth-child(7) .indicator-info {
    grid-column: 1 / -1;
  }

  .indicators-grid > .indicator-card:nth-child(7) .indicator-value-container {
    grid-column: 1 / -1;
    margin: 10rpx 0;
  }
}
</style>
