<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { getLatestDevices } from '@/api/device'
import { Stomp } from '@stomp/stompjs'
import SockJS from 'sockjs-client'
const chart = ref(null)
let chartInstance = null
const deviceList = ref([])
const latestDevice = ref(null)
const stompClient = ref(null)

// 颜色计算
const getTempColor = (temp) => {
  if (!temp) return '#333'
  if (temp > 30) return '#f56c6c' // 高温红色
  if (temp < 15) return '#409eff' // 低温蓝色
  return '#67c23a' // 正常绿色
}

const getHumidityColor = (humidity) => {
  if (!humidity) return '#333'
  if (humidity > 70 || humidity < 30) return '#f56c6c' // 异常红色
  return '#67c23a' // 正常绿色
}

// 时间格式化
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleString()
}

// 初始化图表
const initChart = () => {
  chartInstance = echarts.init(chart.value)
  updateChart()
}

// 更新图表数据
const updateChart = () => {
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const date = new Date(params[0].value[0])
        return `${date.toLocaleTimeString()}<br/>
                温度: ${params[0].value[1]}°C<br/>
                湿度: ${params[1].value[2]}%`
      }
    },
    legend: {
      data: ['温度', '湿度']
    },
    xAxis: {
      type: 'time'
    },
    yAxis: [
      {
        name: '温度(℃)',
        type: 'value',
        min: 10,
        max: 40
      },
      {
        name: '湿度(%)',
        type: 'value',
        min: 20,
        max: 80
      }
    ],
    series: [
      {
        name: '温度',
        type: 'line',
        showSymbol: false,
        data: deviceList.value.map((item) => [
          item.timestamp,
          item.temperature
        ]),
        lineStyle: {
          color: '#ff6384'
        }
      },
      {
        name: '湿度',
        type: 'line',
        showSymbol: false,
        yAxisIndex: 1,
        data: deviceList.value.map((item) => [item.timestamp, item.humidity]),
        lineStyle: {
          color: '#36a2eb'
        }
      }
    ]
  }
  chartInstance.setOption(option)
}

// 连接WebSocket
const connectWebSocket = () => {
  const socket = new SockJS('http://119.29.191.232:9020/api/ws')
  stompClient.value = Stomp.over(socket)

  stompClient.value.connect({}, () => {
    stompClient.value.subscribe('/topic/devices', (message) => {
      const newDevice = JSON.parse(message.body)
      latestDevice.value = newDevice
      deviceList.value.unshift(newDevice)

      // 保持列表长度
      if (deviceList.value.length > 50) {
        deviceList.value.pop()
      }

      updateChart()
    })
  })
}

// 获取初始数据
const fetchInitialData = async () => {
  const {
    data: { data }
  } = await getLatestDevices()
  deviceList.value = data.reverse()
  if (deviceList.value.length > 0) {
    latestDevice.value = deviceList.value[0]
  }
  updateChart()
}

onMounted(() => {
  initChart()
  fetchInitialData()
  connectWebSocket()
})

onBeforeUnmount(() => {
  if (stompClient.value) {
    stompClient.value.disconnect()
  }
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>
<template>
  <div class="dashboard-container">
    <!-- 状态概览卡片 -->
    <div class="status-cards">
      <el-card class="status-card" shadow="hover">
        <div class="card-title">当前温度</div>
        <div
          class="card-value"
          :style="{ color: getTempColor(latestDevice?.temperature) }"
        >
          {{ latestDevice?.temperature?.toFixed(1) || '--' }}°C
        </div>
      </el-card>

      <el-card class="status-card" shadow="hover">
        <div class="card-title">当前湿度</div>
        <div
          class="card-value"
          :style="{ color: getHumidityColor(latestDevice?.humidity) }"
        >
          {{ latestDevice?.humidity?.toFixed(1) || '--' }}%
        </div>
      </el-card>

      <el-card class="status-card" shadow="hover">
        <div class="card-title">风扇状态</div>
        <div class="card-value">
          <el-tag :type="latestDevice?.fanStatus ? 'success' : 'info'">
            {{ latestDevice?.fanStatus ? '运行中' : '已关闭' }}
          </el-tag>
        </div>
      </el-card>

      <el-card class="status-card" shadow="hover">
        <div class="card-title">设备状态</div>
        <div class="card-value">
          <el-tag :type="latestDevice?.warningStatus ? 'danger' : 'success'">
            {{ latestDevice?.warningStatus ? '异常' : '正常' }}
          </el-tag>
        </div>
      </el-card>
    </div>

    <!-- 数据图表 -->
    <div class="chart-container">
      <el-card shadow="never">
        <div ref="chart" style="width: 100%; height: 400px"></div>
      </el-card>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-card shadow="never">
        <el-table :data="deviceList" style="width: 100%" height="400">
          <el-table-column prop="timestamp" label="时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column label="温度(℃)" width="120">
            <template #default="{ row }">
              <span :style="{ color: getTempColor(row.temperature) }">
                {{ row.temperature.toFixed(1) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="湿度(%)" width="120">
            <template #default="{ row }">
              <span :style="{ color: getHumidityColor(row.humidity) }">
                {{ row.humidity.toFixed(1) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="风扇状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.fanStatus ? 'success' : 'info'">
                {{ row.fanStatus ? '运行中' : '已关闭' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="警告状态">
            <template #default="{ row }">
              <el-tag :type="row.warningStatus ? 'danger' : 'success'">
                {{ row.warningStatus ? '异常' : '正常' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.status-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.status-card {
  border-radius: 8px;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
}

.chart-container,
.table-container {
  margin-bottom: 20px;
}

.el-card {
  border-radius: 8px;
}
</style>
