<template>
  <div class="env-sensor">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">环境传感器</h2>
    </div>

    <!-- 概览信息栏 -->
    <a-row :gutter="[24, 24]">
      <a-col :xs="24" :sm="8">
        <a-card :bordered="false" class="sensor-card temp-card">
          <div class="sensor-content">
            <div class="sensor-icon">
              <FireOutlined />
            </div>
            <div class="sensor-info">
              <div class="sensor-label">温度</div>
              <div class="sensor-value">
                {{ sensorData.temperature !== null ? `${sensorData.temperature}°C` : '--' }}
              </div>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :xs="24" :sm="8">
        <a-card :bordered="false" class="sensor-card humidity-card">
          <div class="sensor-content">
            <div class="sensor-icon">
              <CloudOutlined />
            </div>
            <div class="sensor-info">
              <div class="sensor-label">湿度</div>
              <div class="sensor-value">
                {{ sensorData.humidity !== null ? `${sensorData.humidity}%` : '--' }}
              </div>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :xs="24" :sm="8">
        <a-card :bordered="false" class="sensor-card dtu-temp-card">
          <div class="sensor-content">
            <div class="sensor-icon">
              <DesktopOutlined />
            </div>
            <div class="sensor-info">
              <div class="sensor-label">DTU 主板温度</div>
              <div class="sensor-value">
                {{ sensorData.dtu_temperature !== null ? `${sensorData.dtu_temperature}°C` : '--' }}
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[24, 24]" style="margin-top: 24px">
      <a-col :xs="24" :sm="12">
        <a-card :bordered="false" class="sensor-card">
          <div class="sensor-content">
            <div class="sensor-icon">
              <DashboardOutlined />
            </div>
            <div class="sensor-info" style="width: 100%">
              <div class="sensor-label">CPU 使用率</div>
              <a-progress
                v-if="sensorData.cpu_usage !== null && sensorData.cpu_usage !== undefined"
                :percent="Math.round(sensorData.cpu_usage)"
                :status="sensorData.cpu_usage > 80 ? 'exception' : 'normal'"
              />
              <div v-else class="sensor-value">--</div>
            </div>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12">
        <a-card :bordered="false" class="sensor-card">
          <div class="sensor-content">
            <div class="sensor-icon">
              <DatabaseOutlined />
            </div>
            <div class="sensor-info" style="width: 100%">
              <div class="sensor-label">内存使用率</div>
              <a-progress
                v-if="sensorData.memory_usage !== null && sensorData.memory_usage !== undefined"
                :percent="Math.round(sensorData.memory_usage)"
                :status="sensorData.memory_usage > 80 ? 'exception' : 'normal'"
              />
              <div v-else class="sensor-value">--</div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 详细信息卡片 -->
    <a-card :bordered="false" class="detail-card">
      <template #title>
        <div class="card-header">
          <InfoCircleOutlined />
          <span>传感器详情</span>
        </div>
      </template>
      <template #extra>
        <a-button type="primary" @click="refreshData" :loading="loading">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </template>

      <a-descriptions :column="2" bordered size="small">
        <a-descriptions-item label="环境温度">
          <span :class="getTempClass(sensorData.temperature)">
            {{ sensorData.temperature !== null ? `${sensorData.temperature}°C` : '未连接' }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="环境湿度">
          <span :class="getHumidityClass(sensorData.humidity)">
            {{ sensorData.humidity !== null ? `${sensorData.humidity}%` : '未连接' }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="DTU 主板温度">
          <span :class="getDtuTempClass(sensorData.dtu_temperature)">
            {{ sensorData.dtu_temperature !== null ? `${sensorData.dtu_temperature}°C` : '未连接' }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="更新时间">
          {{ sensorData.update_time ? formatTime(sensorData.update_time) : '--' }}
        </a-descriptions-item>
        <a-descriptions-item label="传感器数据时间戳">
          {{ sensorData.sensor_update_time ? formatTime(sensorData.sensor_update_time) : '--' }}
        </a-descriptions-item>
        <a-descriptions-item label="连接状态">
          <a-tag :color="sensorData.connected ? 'green' : 'red'">
            {{ sensorData.connected ? '已连接' : '未连接' }}
          </a-tag>
        </a-descriptions-item>
      </a-descriptions>
    </a-card>

    <!-- 告警阈值设置 -->
    <a-card :bordered="false" class="threshold-card">
      <template #title>
        <div class="card-header">
          <WarningOutlined />
          <span>告警阈值设置</span>
        </div>
      </template>

      <a-form
        :model="thresholdForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 12 }"
        @finish="saveThreshold"
      >
        <a-form-item label="温度过高阈值" name="temp_high">
          <a-input-number
            v-model:value="thresholdForm.temp_high"
            :min="-40"
            :max="100"
            addon-after="°C"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="温度过低阈值" name="temp_low">
          <a-input-number
            v-model:value="thresholdForm.temp_low"
            :min="-40"
            :max="100"
            addon-after="°C"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="湿度过高阈值" name="humidity_high">
          <a-input-number
            v-model:value="thresholdForm.humidity_high"
            :min="0"
            :max="100"
            addon-after="%"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="湿度过低阈值" name="humidity_low">
          <a-input-number
            v-model:value="thresholdForm.humidity_low"
            :min="0"
            :max="100"
            addon-after="%"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="DTU温度过高阈值" name="dtu_temp_high">
          <a-input-number
            v-model:value="thresholdForm.dtu_temp_high"
            :min="0"
            :max="120"
            addon-after="°C"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 6, span: 12 }">
          <a-button type="primary" html-type="submit" :loading="saving">
            保存阈值
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 历史数据图表 -->
    <a-card :bordered="false" class="chart-card">
      <template #title>
        <div class="card-header">
          <LineChartOutlined />
          <span>历史数据</span>
        </div>
      </template>
      <template #extra>
        <a-segmented v-model:value="timeRange" :options="timeRangeOptions" @change="loadHistoryData" />
      </template>

      <div v-if="historyData.length > 0" class="chart-container">
        <div ref="chartRef" style="width: 100%; height: 300px;"></div>
      </div>
      <a-empty v-else description="暂无历史数据" />
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import {
  FireOutlined,
  CloudOutlined,
  DesktopOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  LineChartOutlined,
  ReloadOutlined,
  DashboardOutlined,
  DatabaseOutlined
} from '@ant-design/icons-vue'

const loading = ref(false)
const saving = ref(false)
const timeRange = ref('1h')
const timeRangeOptions = [
  { label: '1小时', value: '1h' },
  { label: '6小时', value: '6h' },
  { label: '24小时', value: '24h' },
  { label: '7天', value: '7d' }
]

const sensorData = ref({
  temperature: null,
  humidity: null,
  dtu_temperature: null,
  update_time: null,
  sensor_update_time: null,
  connected: false
})

const thresholdForm = reactive({
  temp_high: 50,
  temp_low: -10,
  humidity_high: 80,
  humidity_low: 20,
  dtu_temp_high: 70
})

const historyData = ref([])
const chartRef = ref(null)
let chartInstance = null
let pollInterval = null

const formatTime = (timestamp) => {
  if (!timestamp) return '--'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getTempClass = (temp) => {
  if (temp === null) return ''
  if (temp > thresholdForm.temp_high) return 'text-danger'
  if (temp < thresholdForm.temp_low) return 'text-warning'
  return 'text-success'
}

const getHumidityClass = (humidity) => {
  if (humidity === null) return ''
  if (humidity > thresholdForm.humidity_high) return 'text-danger'
  if (humidity < thresholdForm.humidity_low) return 'text-warning'
  return 'text-success'
}

const getDtuTempClass = (temp) => {
  if (temp === null) return ''
  if (temp > thresholdForm.dtu_temp_high) return 'text-danger'
  return 'text-success'
}

const fetchSensorData = async () => {
  try {
    const response = await fetch('/api/sensor/env')
    const result = await response.json()
    if (result.success) {
      sensorData.value = {
        temperature: result.data?.temperature,
        humidity: result.data?.humidity,
        dtu_temperature: result.data?.dtu_temperature,
        update_time: result.data?.update_time,
        sensor_update_time: result.data?.sensor_update_time,
        cpu_usage: result.data?.cpu_usage,
        memory_usage: result.data?.memory_usage,
        connected: result.data?.connected ?? (result.data?.temperature !== null)
      }
    }
  } catch (error) {
    console.error('获取传感器数据失败:', error)
  }
}

const fetchThresholds = async () => {
  try {
    const response = await fetch('/api/sensor/threshold')
    const result = await response.json()
    if (result.success && result.data) {
      Object.assign(thresholdForm, result.data)
    }
  } catch (error) {
    console.error('获取阈值失败:', error)
  }
}

const saveThreshold = async () => {
  saving.value = true
  try {
    const response = await fetch('/api/sensor/threshold', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(thresholdForm)
    })
    const result = await response.json()
    if (result.success) {
      message.success('阈值保存成功')
    } else {
      message.error(result.error || '保存失败')
    }
  } catch (error) {
    message.error('保存失败: ' + error.message)
  } finally {
    saving.value = false
  }
}

const loadHistoryData = async () => {
  try {
    const response = await fetch(`/api/sensor/history?range=${timeRange.value}`)
    const result = await response.json()
    if (result.success) {
      historyData.value = result.data || []
      await nextTick()
      renderChart()
    }
  } catch (error) {
    console.error('获取历史数据失败:', error)
  }
}

const renderChart = async () => {
  if (!chartRef.value || historyData.value.length === 0) return

  const ECharts = await import('echarts')
  if (!chartInstance) {
    chartInstance = ECharts.init(chartRef.value)
  }

  const times = historyData.value.map(d => d.update_time || d.timestamp)
  const temps = historyData.value.map(d => d.temperature)
  const humidities = historyData.value.map(d => d.humidity)
  const dtuTemps = historyData.value.map(d => d.dtu_temperature || d.dtu_temp)

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        let result = params[0].axisValueLabel + '<br/>'
        params.forEach(p => {
          result += `${p.marker} ${p.seriesName}: ${p.value ?? '--'}${p.seriesName.includes('温度') ? '°C' : '%'}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['环境温度', '环境湿度', 'DTU温度']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: times
    },
    yAxis: [
      {
        type: 'value',
        name: '温度 (°C)',
        position: 'left',
        axisLine: { show: true },
        axisLabel: { formatter: '{value}°C' }
      },
      {
        type: 'value',
        name: '湿度 (%)',
        min: 0,
        max: 100,
        position: 'right',
        axisLine: { show: true },
        axisLabel: { formatter: '{value}%' }
      }
    ],
    series: [
      {
        name: '环境温度',
        type: 'line',
        data: temps,
        smooth: true,
        lineStyle: { color: '#ff6b6b' },
        itemStyle: { color: '#ff6b6b' }
      },
      {
        name: 'DTU温度',
        type: 'line',
        data: dtuTemps,
        smooth: true,
        lineStyle: { color: '#ffa502' },
        itemStyle: { color: '#ffa502' }
      },
      {
        name: '环境湿度',
        type: 'line',
        yAxisIndex: 1,
        data: humidities,
        smooth: true,
        lineStyle: { color: '#74b9ff' },
        itemStyle: { color: '#74b9ff' }
      }
    ]
  }

  chartInstance.setOption(option)
}

const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([fetchSensorData(), fetchThresholds(), loadHistoryData()])
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await refreshData()

  // 定时刷新
  pollInterval = setInterval(fetchSensorData, 5000)

  // 窗口大小变化时重新调整图表
  window.addEventListener('resize', () => {
    chartInstance?.resize()
  })
})

onUnmounted(() => {
  if (pollInterval) {
    clearInterval(pollInterval)
  }
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
.env-sensor {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.sensor-card {
  text-align: center;
}

.sensor-card :deep(.ant-card-body) {
  padding: 24px;
}

.sensor-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.sensor-icon {
  font-size: 48px;
  padding: 16px;
  border-radius: 12px;
}

.temp-card .sensor-icon {
  color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
}

.humidity-card .sensor-icon {
  color: #74b9ff;
  background: rgba(116, 185, 255, 0.1);
}

.dtu-temp-card .sensor-icon {
  color: #ffa502;
  background: rgba(255, 165, 2, 0.1);
}

.sensor-info {
  text-align: left;
}

.sensor-label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 4px;
}

.sensor-value {
  font-size: 28px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
}

.detail-card,
.threshold-card,
.chart-card {
  margin-top: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.text-success {
  color: #52c41a;
}

.text-warning {
  color: #faad14;
}

.text-danger {
  color: #ff4d4f;
}

.chart-container {
  min-height: 300px;
}
</style>