<template>
  <view class="parameter-record-page">
    <!-- 固定头部 -->
    <view class="fixed-header">
      <text class="header-title">移动式检修车间</text>
    </view>
    
    <!-- 内容区域 -->
    <view class="tabbar-content">
      <!-- 日期选择区域 -->
      <view class="date-picker-container">
        <picker 
          mode="date" 
          :value="selectedDate" 
          @change="onDateChange"
          class="date-picker"
        >
          <view class="picker-input">
            <text class="picker-text">{{ selectedDate || '请选择日期' }}</text>
            <text class="picker-icon">▼</text>
          </view>
        </picker>
      </view>
    
    <!-- 温度趋势图表 -->
    <view class="chart-card">
      <view class="chart-header">
        <text class="chart-title">温度趋势 (WD)</text>
        <!-- <view class="status-indicator">
          <view class="status-dot temperature-dot"></view>
          <text class="status-text">{{ chartData.temperature.length > 0 ? '有数据' : '无数据' }}</text>
        </view> -->
      </view>
      <view class="chart-container">
        <e-chart ref="temperatureChartRef" @ready="initTemperatureChart" :height="400" />
      </view>
    </view>
    
    <!-- 湿度趋势图表 -->
    <view class="chart-card">
      <view class="chart-header">
        <text class="chart-title">湿度趋势 (SD)</text>
        <!-- <view class="status-indicator">
          <view class="status-dot humidity-dot"></view>
          <text class="status-text">{{ chartData.humidity.length > 0 ? '有数据' : '无数据' }}</text>
        </view> -->
      </view>
      <view class="chart-container">
        <e-chart ref="humidityChartRef" @ready="initHumidityChart" :height="400" />
      </view>
    </view>
    
    <!-- PM2.5趋势图表 -->
    <view class="chart-card">
      <view class="chart-header">
        <text class="chart-title">PM趋势 (PM)</text>
        <!-- <view class="status-indicator">
          <view class="status-dot pm25-dot"></view>
          <text class="status-text">{{ chartData.pm.length > 0 ? '有数据' : '无数据' }}</text>
        </view> -->
      </view>
      <view class="chart-container">
        <e-chart ref="pm25ChartRef" @ready="initPM25Chart" :height="400" />
      </view>
    </view>
    </view>
  </view>
</template>

<script>
import mqttDataManager from '@/utils/mqttDataManager.js'
import { dataHistoryApi, eventApi } from '@/utils/api.js'
import EChart from '@/uni_modules/e-chart/components/e-chart/e-chart.vue'

export default {
  components: {
    EChart
  },
  data() {
    return {
      selectedDate: this.getTodayDate(), // 默认选择今天
      // 24小时数据 (0-23点) - 默认显示0
      temperatureData: new Array(24).fill(0),
      humidityData: new Array(24).fill(0),
      pm25Data: new Array(24).fill(0),
      connectionStatus: {
        isConnected: false,
        lastUpdate: null
      },
      // 历史数据
      historyData: [],
      // 处理后的图表数据
      chartData: {
        temperature: [],
        humidity: [],
        pm: []
      },
      // 数据状态
      dataStatus: {
        isRealData: false,
        lastUpdateTime: null,
        dataSource: 'empty' // 'api' | 'empty' | 'error'
      },
      // 页面初始化状态
      hasInitialized: false,
      // 查询模式：'default' 表示过去24小时，'date' 表示按日期查询
      queryMode: 'default',
      // ECharts配置选项
      temperatureOption: {
        title: {
          text: '',
          left: 'center',
          textStyle: {
            fontSize: 16,
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const data = params[0];
            return `时间: ${data.axisValue} 温度: ${data.value}°C`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.generateXAxisLabels(),
          axisLabel: {
            interval: 3, // 每4个小时显示一个标签
            fontSize: 10
          }
        },
        yAxis: {
          type: 'value',
          name: '温度(°C)',
          min: 0,
          max: 80,
          axisLabel: {
            formatter: '{value}°C',
            fontSize: 10
          }
        },
        series: [{
          name: '温度',
          type: 'line',
          data: [],
          smooth: true,
          lineStyle: {
            color: '#ff6b35',
            width: 3
          },
          itemStyle: {
            color: '#ff6b35'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(255, 107, 53, 0.3)'
              }, {
                offset: 1, color: 'rgba(255, 107, 53, 0.1)'
              }]
            }
          }
        }]
      },
      humidityOption: {
        title: {
          text: '',
          left: 'center',
          textStyle: {
            fontSize: 16,
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const data = params[0];
            return `时间: ${data.axisValue} 湿度: ${data.value}%`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.generateXAxisLabels(),
          axisLabel: {
            interval: 3,
            fontSize: 10
          }
        },
        yAxis: {
          type: 'value',
          name: '湿度(%)',
          min: 0,
          max: 80,
          axisLabel: {
            formatter: '{value}%',
            fontSize: 10
          }
        },
        series: [{
          name: '湿度',
          type: 'line',
          data: [],
          smooth: true,
          lineStyle: {
            color: '#4a90e2',
            width: 3
          },
          itemStyle: {
            color: '#4a90e2'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(74, 144, 226, 0.3)'
              }, {
                offset: 1, color: 'rgba(74, 144, 226, 0.1)'
              }]
            }
          }
        }]
      },
      pm25Option: {
        title: {
          text: '',
          left: 'center',
          textStyle: {
            fontSize: 16,
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const data = params[0];
            return `时间: ${data.axisValue} PM2.5: ${data.value}μg/m³`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.generateXAxisLabels(),
          axisLabel: {
            interval: 3,
            fontSize: 10
          }
        },
        yAxis: {
          type: 'value',
          name: 'PM2.5(μg/m³)',
          min: 0,
          max: 50,
          axisLabel: {
            formatter: '{value}μg/m³',
            fontSize: 10
          }
        },
        series: [{
          name: 'PM2.5',
          type: 'line',
          data: [],
          smooth: true,
          lineStyle: {
            color: '#7ed321',
            width: 3
          },
          itemStyle: {
            color: '#7ed321'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(126, 211, 33, 0.3)'
              }, {
                offset: 1, color: 'rgba(126, 211, 33, 0.1)'
              }]
            }
          }
        }]
      }
    }
  },
  onLoad() {
    this.initMqttListener()
    // 调用历史数据接口
    this.getHistoryData()
  },
  onShow() {
    // 重置时间相关状态
    this.resetTimeState()
    
    // 只有在非首次显示时才重新获取历史数据
    // 首次显示时已经在onLoad中获取过了
    if (this.hasInitialized) {
      this.getHistoryData()
    } else {
      this.hasInitialized = true
    }
  },
  onHide() {
    // 页面隐藏时清除数据，防止缓存
    this.clearPageData()
  },
  onUnload() {
    // 页面卸载时移除监听器
    if (this.dataUpdateHandler) {
      mqttDataManager.removeListener('dataUpdate', this.dataUpdateHandler)
    }
    if (this.statusUpdateHandler) {
      mqttDataManager.removeListener('connectionStatus', this.statusUpdateHandler)
    }
  },
  methods: {
    // 重置时间相关状态
    resetTimeState() {
      // 页面切换后重置为默认查询模式（过去24小时）
      this.queryMode = 'default'
      this.selectedDate = this.getTodayDate()
      // 强制更新X轴标签
      this.$nextTick(() => {
        this.updateCharts()
      })
    },
    
    // 清除页面数据缓存
    clearPageData() {
      // 清除图表数据
      this.temperatureData = new Array(24).fill(0)
      this.humidityData = new Array(24).fill(0)
      this.pm25Data = new Array(24).fill(0)
      
      // 清除历史数据
      this.historyData = []
      
      // 清除处理后的图表数据
      this.chartData = {
        temperature: [],
        humidity: [],
        pm: []
      }
      
      // 重置数据状态
      this.dataStatus = {
        isRealData: false,
        lastUpdateTime: null,
        dataSource: 'empty'
      }
      
      // 重置连接状态
      this.connectionStatus = {
        isConnected: false,
        lastUpdate: null
      }
      
      console.log('✅ 页面数据缓存已清除')
    },
    
    // 生成x轴标签
    generateXAxisLabels() {
      if (this.queryMode === 'date') {
        // 按日期查询时，显示0-23小时
        return Array.from({length: 24}, (_, i) => `${i.toString().padStart(2, '0')}:00`)
      } else {
        // 默认查询时，显示当前时间之前24小时（整点时间）
        const now = new Date()
        const currentHour = now.getHours()
        const labels = []
        for (let i = 23; i >= 0; i--) {
          // 计算目标小时
          let targetHour = currentHour - i
          if (targetHour < 0) {
            targetHour += 24 // 跨天处理
          }
          labels.push(`${String(targetHour).padStart(2, '0')}:00`)
        }
        
        return labels
      }
    },
    
    // 获取今天的日期（本地时区）
    getTodayDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 格式化日期为 YYYY-MM-DD 格式
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 获取星期几
    getWeekday(dateString) {
      const date = new Date(dateString)
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      return weekdays[date.getDay()]
    },
    
    
    // 获取时间范围显示文本
    getTimeRangeText() {
      if (this.queryMode === 'date') {
        return `查询日期: ${this.selectedDate}`
      } else {
        const now = new Date()
        const past24Hours = new Date(now.getTime() - 24 * 60 * 60 * 1000)
        const startTime = this.formatTimeDisplay(past24Hours)
        const endTime = this.formatTimeDisplay(now)
        return `过去24小时: ${startTime} ~ ${endTime}`
      }
    },
    
    // 格式化时间显示（用于界面显示）
    formatTimeDisplay(date) {
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${month}-${day} ${hours}:${minutes}`
    },
    // 初始化MQTT监听
    initMqttListener() {
      // 监听数据更新
      this.dataUpdateHandler = (data) => {
        // this.updateChartData(data)
      }
      mqttDataManager.addListener('dataUpdate', this.dataUpdateHandler)
      
      // 监听连接状态
      this.statusUpdateHandler = (status) => {
        this.connectionStatus = status
      }
      mqttDataManager.addListener('connectionStatus', this.statusUpdateHandler)
      
      // 获取初始连接状态
      this.connectionStatus = mqttDataManager.getConnectionStatus()
    },
    
    // 更新图表数据
    updateChartData(data) {
      
      // 只处理WSD设备的数据
      if (data.deviceType === 'WSD') {
        const now = new Date()
        const currentHour = now.getHours()
        const currentMinute = now.getMinutes()
        const currentTimeInHours = currentHour + currentMinute / 60
        
        // 计算数据在数组中的索引位置
        let dataIndex
        if (this.queryMode === 'date') {
          // 按日期查询时，直接使用当前小时
          dataIndex = currentHour
        } else {
          // 默认查询时，当前时间对应索引0（最新数据）
          dataIndex = 0
        }
        
        // 更新对应位置的数据
        if (data.temperature !== undefined) {
          Math.round(data.temperature) && (this.temperatureData[dataIndex] = Math.round(data.temperature))
        }
        if (data.humidity !== undefined) {
          Math.round(data.humidity) && (this.humidityData[dataIndex] = Math.round(data.humidity))
        }
        if (data.pm !== undefined) {
          Math.round(data.pm) && (this.pm25Data[dataIndex] = Math.round(data.pm))
        }
        
        // 重新绘制图表
        this.$nextTick(() => {
          this.updateCharts()
        })
      } else {
        console.log('⚠️ 非WSD设备数据，跳过图表更新:', data.deviceType)
      }
    },
    
    // 图表初始化方法
    initTemperatureChart() {
      this.temperatureOption.xAxis.data = this.generateXAxisLabels()
      this.temperatureOption.series[0].data = this.temperatureData
      this.$refs.temperatureChartRef.init(this.temperatureOption)
    },
    
    initHumidityChart() {
      this.humidityOption.xAxis.data = this.generateXAxisLabels()
      this.humidityOption.series[0].data = this.humidityData
      this.$refs.humidityChartRef.init(this.humidityOption)
    },
    
    initPM25Chart() {
      this.pm25Option.xAxis.data = this.generateXAxisLabels()
      this.pm25Option.series[0].data = this.pm25Data
      this.$refs.pm25ChartRef.init(this.pm25Option)
    },
    
    // 日期选择处理，选择后直接查询
    onDateChange(e) {
      this.selectedDate = e.detail.value
      this.queryMode = 'date' // 切换到按日期查询模式
      
      // 显示加载状态
      uni.showLoading({
        title: '加载数据中...'
      })
      
      // 重新获取历史数据
      this.getHistoryDataByDate().finally(() => {
        uni.hideLoading()
      })
    },
    
    // 更新图表数据
    updateCharts() {
      const xAxisLabels = this.generateXAxisLabels()
      
      if (this.$refs.temperatureChartRef) {
        this.temperatureOption.xAxis.data = xAxisLabels
        this.temperatureOption.series[0].data = this.temperatureData
        this.$refs.temperatureChartRef.setOption(this.temperatureOption)
      }
      if (this.$refs.humidityChartRef) {
        this.humidityOption.xAxis.data = xAxisLabels
        this.humidityOption.series[0].data = this.humidityData
        this.$refs.humidityChartRef.setOption(this.humidityOption)
      }
      if (this.$refs.pm25ChartRef) {
        this.pm25Option.xAxis.data = xAxisLabels
        this.pm25Option.series[0].data = this.pm25Data
        this.$refs.pm25ChartRef.setOption(this.pm25Option)
      }
    },
    
    // 根据选择的日期获取历史数据
    async getHistoryDataByDate(retryCount = 0) {
      try {
        // 根据选择的日期构建时间范围
        const startTime = `${this.selectedDate} 00:00:00`
        const endTime = `${this.selectedDate} 23:59:59`
        
        const params = {
          startTime: startTime,
          endTime: endTime
        }
        // 增加超时时间到20秒
        const response = await dataHistoryApi.getHistory(params, { timeout: 20000 })
        
        // 处理历史数据
        if (response && Array.isArray(response) && response.length > 0) {
          this.historyData = response
          this.processHistoryData(response)
          
          // 更新数据状态
          this.dataStatus = {
            isRealData: true,
            lastUpdateTime: new Date().toLocaleString(),
            dataSource: 'api'
          }
          
          // 保存查询事件
          await this.createQueryEvent('success', response.length)
        } else {
          // 没有数据时显示空状态
          this.showEmptyState()
          
          // 更新数据状态
          this.dataStatus = {
            isRealData: false,
            lastUpdateTime: new Date().toLocaleString(),
            dataSource: 'empty'
          }
          
          // 保存查询事件（无数据）
          await this.createQueryEvent('empty', 0)
        }
        
        return response
        
      } catch (error) {
        // 如果是超时错误且重试次数少于2次，则重试
        if (error.message.includes('timeout') && retryCount < 2) {
          uni.showToast({
            title: `网络超时，重试中...`,
            icon: 'loading',
            duration: 1500
          })
          
          // 等待1秒后重试
          await new Promise(resolve => setTimeout(resolve, 1000))
          return this.getHistoryDataByDate(retryCount + 1)
        }
        
        // 出错时显示空状态
        this.showEmptyState()
        
        // 更新数据状态
        this.dataStatus = {
          isRealData: false,
          lastUpdateTime: new Date().toLocaleString(),
          dataSource: 'error'
        }
        
        // 保存查询事件（错误）
        await this.createQueryEvent('error', 0)
        
        // 显示错误提示
        const errorMessage = error.message.includes('timeout') ? '网络连接超时，请检查网络' : '数据加载失败'
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        })
        
        // 不再抛出错误，避免未捕获的Promise错误
        return null
      }
    },
    
    // 获取历史数据（默认过去24小时）
    async getHistoryData(retryCount = 0) {
      try {
        // 构建时间范围：从当前时间开始过去24小时
        const now = new Date()
        const past24Hours = new Date(now.getTime() - 24 * 60 * 60 * 1000) // 24小时前
        
        // 格式化时间字符串
        const startTime = this.formatDateTimeString(past24Hours)
        const endTime = this.formatDateTimeString(now)
        
        const params = {
          startTime: startTime,
          endTime: endTime
        }
        // 增加超时时间到20秒
        const response = await dataHistoryApi.getHistory(params, { timeout: 20000 })
        
        // 处理历史数据
        if (response && Array.isArray(response) && response.length > 0) {
          this.historyData = response
          this.processHistoryData(response)
          
          // 更新数据状态
          this.dataStatus = {
            isRealData: true,
            lastUpdateTime: new Date().toLocaleString(),
            dataSource: 'api'
          }
          
          // 保存查询事件
          await this.createQueryEvent('success', response.length)
        } else {
          // 没有数据时显示空状态
          this.showEmptyState()
          
          // 更新数据状态
          this.dataStatus = {
            isRealData: false,
            lastUpdateTime: new Date().toLocaleString(),
            dataSource: 'empty'
          }
          
          // 保存查询事件（无数据）
          await this.createQueryEvent('empty', 0)
        }
        
        return response
        
      } catch (error) {
        // 如果是超时错误且重试次数少于2次，则重试
        if (error.message.includes('timeout') && retryCount < 2) {
          uni.showToast({
            title: `网络超时，重试中...`,
            icon: 'loading',
            duration: 1500
          })
          
          // 等待1秒后重试
          await new Promise(resolve => setTimeout(resolve, 1000))
          return this.getHistoryData(retryCount + 1)
        }
        
        // 出错时显示空状态
        this.showEmptyState()
        
        // 更新数据状态
        this.dataStatus = {
          isRealData: false,
          lastUpdateTime: new Date().toLocaleString(),
          dataSource: 'error'
        }
        
        // 保存查询事件（错误）
        await this.createQueryEvent('error', 0)
        
        // 显示错误提示
        const errorMessage = error.message.includes('timeout') ? '网络连接超时，请检查网络' : '数据加载失败'
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        })
        
        // 不再抛出错误，避免未捕获的Promise错误
        return null
      }
    },
    
    // 使用默认数据
    useDefaultData() {
      // 使用预设的示例数据
      this.temperatureData = [22, 25, 28, 32, 35, 38, 40, 38, 35, 32, 28, 25, 22, 20, 18, 20, 22, 25, 28, 30, 32, 30, 28, 25]
      this.humidityData = [45, 50, 55, 60, 65, 70, 75, 70, 65, 60, 55, 50, 45, 40, 35, 40, 45, 50, 55, 60, 65, 60, 55, 50]
      this.pm25Data = [15, 18, 22, 25, 28, 32, 35, 32, 28, 25, 22, 18, 15, 12, 10, 12, 15, 18, 22, 25, 28, 25, 22, 18]
      
      // 更新数据状态
      this.dataStatus = {
        isRealData: false,
        lastUpdateTime: new Date().toLocaleString(),
        dataSource: 'default'
      }
      
      // 更新图表
      this.$nextTick(() => {
        this.updateCharts()
      })
    },
    
    // 显示空状态
    showEmptyState() {
      // 设置默认数据为0
      this.temperatureData = new Array(24).fill(0)
      this.humidityData = new Array(24).fill(0)
      this.pm25Data = new Array(24).fill(0)
      
      // 更新图表
      this.$nextTick(() => {
        this.updateCharts()
      })
    },
    processHistoryData(data) {
      // 初始化图表数据
      this.chartData = {
        temperature: [],
        humidity: [],
        pm: []
      }
      
      // 按时间排序
      const sortedData = data.sort((a, b) => {
        const timeA = new Date(a.createTime || a.timestamp || a.time)
        const timeB = new Date(b.createTime || b.timestamp || b.time)
        return timeA - timeB
      })
      
      // 处理每条数据
      sortedData.forEach(item => {
        const time = new Date(item.createTime || item.timestamp || item.time)
        const hour = time.getHours()
        const minute = time.getMinutes()
        
        // 计算在24小时数组中的索引位置
        let dataIndex
        if (this.queryMode === 'date') {
          // 按日期查询时，直接使用小时作为索引
          dataIndex = hour
        } else {
          // 默认查询时，需要计算相对于当前时间的位置（按小时计算）
          const now = new Date()
          const currentHour = now.getHours()
          
          // 计算时间差（小时）
          let timeDiff = currentHour - hour
          if (timeDiff < 0) {
            timeDiff += 24 // 跨天的情况
          }
          
          // 转换为数组索引（23表示24小时前，0表示当前时间）
          dataIndex = 23 - timeDiff
          
          
          if (dataIndex < 0 || dataIndex >= 24) {
            return // 超出范围的数据跳过
          }
        }
        
        // 处理温度数据 (wd是温度)
        const temperature = item.wd || item.temperature || item.temp || item.T
        if (temperature !== undefined && temperature !== null && temperature >= 0) {
          this.chartData.temperature.push({
            time: dataIndex,
            value: Number(temperature),
            timestamp: item.createTime || item.timestamp || item.time
          })
        }
        
        // 处理湿度数据 (sd是湿度)
        const humidity = item.sd || item.humidity || item.hum || item.H
        if (humidity !== undefined && humidity !== null && humidity >= 0) {
          this.chartData.humidity.push({
            time: dataIndex,
            value: Number(humidity),
            timestamp: item.createTime || item.timestamp || item.time
          })
        }
        
        // 处理PM数据 (支持多种字段名)
        const pm = item.pm || item.pm25 || item.pm2_5 || item.PM
        if (pm !== undefined && pm !== null && pm >= 0) {
          this.chartData.pm.push({
            time: dataIndex,
            value: Number(pm),
            timestamp: item.createTime || item.timestamp || item.time
          })
        }
      })
      
      
      // 重新绘制图表
      this.$nextTick(() => {
        this.updateChartsWithHistoryData()
      })
    },
    
    // 使用历史数据更新图表
    updateChartsWithHistoryData() {
      const xAxisLabels = this.generateXAxisLabels()
      
      // 处理温度数据
      if (this.chartData.temperature.length > 0) {
        const temperatureData = new Array(24).fill(0)
        this.chartData.temperature.forEach(item => {
          const dataIndex = Math.floor(item.time)
          if (dataIndex >= 0 && dataIndex < 24) {
            temperatureData[dataIndex] = item.value || 0
          }
        })
        this.temperatureData = temperatureData
        if (this.$refs.temperatureChartRef) {
          this.temperatureOption.xAxis.data = xAxisLabels
          this.temperatureOption.series[0].data = temperatureData
          this.$refs.temperatureChartRef.setOption(this.temperatureOption)
        }
      } else {
        // 没有温度数据时，使用0填充
        this.temperatureData = new Array(24).fill(0)
        if (this.$refs.temperatureChartRef) {
          this.temperatureOption.xAxis.data = xAxisLabels
          this.temperatureOption.series[0].data = this.temperatureData
          this.$refs.temperatureChartRef.setOption(this.temperatureOption)
        }
      }
      
      // 处理湿度数据
      if (this.chartData.humidity.length > 0) {
        const humidityData = new Array(24).fill(0)
        this.chartData.humidity.forEach(item => {
          const dataIndex = Math.floor(item.time)
          if (dataIndex >= 0 && dataIndex < 24) {
            humidityData[dataIndex] = item.value || 0
          }
        })
        this.humidityData = humidityData
        if (this.$refs.humidityChartRef) {
          this.humidityOption.xAxis.data = xAxisLabels
          this.humidityOption.series[0].data = humidityData
          this.$refs.humidityChartRef.setOption(this.humidityOption)
        }
      } else {
        // 没有湿度数据时，使用0填充
        this.humidityData = new Array(24).fill(0)
        if (this.$refs.humidityChartRef) {
          this.humidityOption.xAxis.data = xAxisLabels
          this.humidityOption.series[0].data = this.humidityData
          this.$refs.humidityChartRef.setOption(this.humidityOption)
        }
      }
      
      // 处理PM数据
      if (this.chartData.pm.length > 0) {
        const pmData = new Array(24).fill(0)
        this.chartData.pm.forEach(item => {
          const dataIndex = Math.floor(item.time)
          if (dataIndex >= 0 && dataIndex < 24) {
            pmData[dataIndex] = item.value || 0
          }
        })
        this.pm25Data = pmData
        if (this.$refs.pm25ChartRef) {
          this.pm25Option.xAxis.data = xAxisLabels
          this.pm25Option.series[0].data = pmData
          this.$refs.pm25ChartRef.setOption(this.pm25Option)
        }
      } else {
        // 没有PM数据时，使用0填充
        this.pm25Data = new Array(24).fill(0)
        if (this.$refs.pm25ChartRef) {
          this.pm25Option.xAxis.data = xAxisLabels
          this.pm25Option.series[0].data = this.pm25Data
          this.$refs.pm25ChartRef.setOption(this.pm25Option)
        }
      }
    },
    
    // 创建查询事件
    async createQueryEvent(status, dataCount) {
      // try {
      //   const currentTime = this.formatDateTime(new Date())
      //   const queryEvent = {
      //     eventType: "参数记录查询",
      //     eventTime: currentTime,
      //     status: this.getEventStatus(status),
      //     description: this.getEventDescription(status, dataCount),
      //     deviceId: "PARAMETER_QUERY_001"
      //   }

      //   console.log('📤 提交查询事件:', queryEvent)
      //   const response = await eventApi.create(queryEvent)
      //   console.log('✅ 查询事件创建成功:', response)
        
      // } catch (error) {
      //   console.error('❌ 查询事件创建失败:', error)
      // }
    },
    
    // 获取事件状态
    getEventStatus(status) {
      const statusMap = {
        'success': '已完成',
        'empty': '已完成',
        'error': '失败'
      };
      return statusMap[status] || '未知';
    },
    
    // 获取事件描述
    getEventDescription(status, dataCount) {
      const descriptions = {
        'success': `成功查询到${dataCount}条参数记录数据`,
        'empty': '查询参数记录，但未找到数据',
        'error': '查询参数记录时发生错误'
      };
      return descriptions[status] || '未知查询状态';
    },
    
    // 时间格式化函数
    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      
      const result = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      return result
    },
    
    // 格式化时间字符串（用于API请求）
    formatDateTimeString(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.parameter-record-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header-title {
  // font-size: 32rpx;
  // font-weight: bold;
  // color: #333;
  // text-align: center;
}

.tabbar-content {
  flex: 1;
  overflow-y: auto;
}

// 日期选择器容器样式
.date-picker-container {
  display: flex;
  align-items: center;
  // justify-content: center;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-bottom: 2rpx solid #e8eaed;
}

.date-picker {
  width: 100%;
  // max-width: 500rpx;
}

.picker-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 24rpx;
  background: #ffffff;
  border: 2rpx solid #dadce0;
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

.picker-input:active {
  border-color: #1a73e8;
  background: #f1f5ff;
}

.picker-text {
  font-size: 26rpx;
  color: #3c4043;
  flex: 1;
}

.picker-icon {
  font-size: 20rpx;
  color: #5f6368;
  margin-left: 12rpx;
}


.chart-card {
  background: white;
  border-radius: 8rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // margin-bottom: 30rpx; 
}

.chart-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.chart-subtitle {
  font-size: 22rpx;
  color: #666;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 6rpx;
  background-color: #e8f5e8;
  padding: 6rpx 12rpx;
  border-radius: 15rpx;
}

.status-dot {
  width: 8rpx;
  height: 8rpx;
  border-radius: 50%;
}

.temperature-dot {
  background-color: #ff6b35;
}

.humidity-dot {
  background-color: #4a90e2;
}

.pm25-dot {
  background-color: #7ed321;
}

.status-text {
  font-size: 20rpx;
  color: #4caf50;
}

.chart-container {
  width: 100%;
  // padding: 0 20rpx;
}

// 响应式设计 - 平板设备适配
@media (min-width: 768px) and (max-width: 1024px) {
  .date-picker-container {
    padding: 24rpx 32rpx;
  }
  
  .date-picker {
    max-width: 600rpx;
  }
  
  .picker-text {
    font-size: 28rpx;
  }
}

// 响应式设计 - 手机设备适配
@media (max-width: 750rpx) {
  .date-picker-container {
    padding: 16rpx 20rpx;
  }
  
  .date-picker {
    max-width: 100%;
  }
  
  .picker-text {
    font-size: 24rpx;
  }
}
</style>