<template>
  <el-row :gutter="24">
    <el-col :span="24">
      <el-card>
        <template #header>
          <div class="tit">
            <span>数据概览</span>
            <span class="time">数据更新：{{ newDate }}</span>
          </div>
        </template>
        <el-row :gutter="24" class="dataCon">
          <!-- 设备数量统计 -->
          <el-col :xs="24" :sm="12" :lg="8">
            <div class="data-item">
              <div class="data-header">
                <el-icon class="icon-device"><Monitor /></el-icon>
                <span class="title">设备数量</span>
              </div>
              <div class="data-content">
                <div class="total-number">{{ deviceData.total || 0 }}</div>
                <div class="sub-info">
                  <span class="online">
                    <el-icon><CircleCheck /></el-icon>
                    在线: {{ deviceData.online || 0 }}
                  </span>
                  <span class="offline">
                    <el-icon><CircleClose /></el-icon>
                    离线: {{ deviceData.offline || 0 }}
                  </span>
                </div>
              </div>
              <div id="deviceContainer" class="chart-container"></div>
            </div>
          </el-col>

          <!-- 累计按摩时长 -->
          <el-col :xs="24" :sm="12" :lg="8">
            <div class="data-item">
              <div class="data-header">
                <el-icon class="icon-time"><Timer /></el-icon>
                <span class="title">累计按摩时长</span>
              </div>
              <div class="data-content">
                <div class="total-number">
                  {{ formatDuration(massageData.totalDuration) }}
                  <span class="unit">小时</span>
                </div>
                <div class="sub-info">
                  <span>今日: {{ massageData.todayTimes || 0 }} 次</span>
                  <span>昨日: {{ massageData.yesterdayTimes || 0 }} 次</span>
                </div>
              </div>
              <div class="stats-info">
                <div class="stat-item">
                  <span class="label">日均次数</span>
                  <span class="value">{{ massageData.avgTimesPerDay || 0 }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">总次数</span>
                  <span class="value">{{ massageData.totalTimes || 0 }}</span>
                </div>
              </div>
            </div>
          </el-col>

          <!-- 活跃设备统计 -->
          <el-col :xs="24" :sm="12" :lg="8">
            <div class="data-item">
              <div class="data-header">
                <el-icon class="icon-active"><TrendCharts /></el-icon>
                <span class="title">设备活跃度</span>
              </div>
              <div class="data-content">
                <div class="activity-rate">
                  <span class="rate-number">{{ activityRate }}%</span>
                  <span class="rate-label">活跃率</span>
                </div>
              </div>
              <div id="activityContainer" class="chart-container"></div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import { onMounted, onUnmounted, computed, ref, nextTick, watch } from 'vue'
import { Monitor, Timer, TrendCharts, CircleCheck, CircleClose } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getDateInfo } from '@/utils/date'
import { getDeviceTotal } from '@/api/device/device'
import { getMassageStats } from '@/api/task/task'

const newDate = getDateInfo(new Date())

// 设备数据
const deviceData = ref({
  total: 0,
  online: 0,
  offline: 0
})

// 按摩数据
const massageData = ref({
  totalDuration: 0,
  avgTimesPerDay: 0,
  totalTimes: 0,
  todayTimes: 0,
  yesterdayTimes: 0,
  actDev: 0,
  inactDev: 0
})

// 图表实例
let deviceChart = null
let activityChart = null

// 计算活跃率
const activityRate = computed(() => {
  const total = massageData.value.actDev + massageData.value.inactDev
  if (total === 0) return 0
  return ((massageData.value.actDev / total) * 100).toFixed(1)
})

// 格式化时长
const formatDuration = (hours) => {
  if (!hours) return '0.0'
  return Number(hours).toFixed(1)
}

// 初始化设备饼图
const initDeviceChart = () => {
  const container = document.getElementById('deviceContainer')
  if (!container) return
  
  deviceChart = echarts.init(container)
  updateDeviceChart()
}

// 更新设备图表
const updateDeviceChart = () => {
  if (!deviceChart) return
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      bottom: 0,
      left: 'center',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '60%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: deviceData.value.online, name: '在线设备', itemStyle: { color: '#67C23A' } },
          { value: deviceData.value.offline, name: '离线设备', itemStyle: { color: '#F56C6C' } }
        ]
      }
    ]
  }
  deviceChart.setOption(option)
}

// 初始化活跃度饼图
const initActivityChart = () => {
  const container = document.getElementById('activityContainer')
  if (!container) return
  
  activityChart = echarts.init(container)
  updateActivityChart()
}

// 更新活跃度图表
const updateActivityChart = () => {
  if (!activityChart) return
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      bottom: 0,
      left: 'center',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '60%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: massageData.value.actDev, name: '活跃设备', itemStyle: { color: '#409EFF' } },
          { value: massageData.value.inactDev, name: '不活跃设备', itemStyle: { color: '#909399' } }
        ]
      }
    ]
  }
  activityChart.setOption(option)
}

// 加载设备数据
const loadDeviceData = async () => {
  try {
    const res = await getDeviceTotal()
    if (res.data) {
      deviceData.value.total = res.data.total || 0
      deviceData.value.online = 0
      deviceData.value.offline = 0
      res.data.data.forEach(item => {
        if (item.name === '在线设备') {
          deviceData.value.online = item.value || 0
        } else if (item.name === '离线设备') {
          deviceData.value.offline = item.value || 0
        }
      })
    }
  } catch (error) {
    console.error('加载设备数据失败:', error)
  }
}

// 加载按摩统计数据
const loadMassageStats = async () => {
  try {
    const res = await getMassageStats()
    if (res.code === 200 && res.data) {
      massageData.value = {
        totalDuration: res.data.totalDuration || 0,
        avgTimesPerDay: res.data.avgTimesPerDay || 0,
        totalTimes: res.data.totalTimes || 0,
        todayTimes: res.data.todayTimes || 0,
        yesterdayTimes: res.data.yesterdayTimes || 0,
        actDev: res.data.actDev || 0,
        inactDev: res.data.inactDev || 0
      }
    }
  } catch (error) {
    console.error('加载按摩统计数据失败:', error)
  }
}

// 窗口大小改变时重新渲染图表
const handleResize = () => {
  deviceChart?.resize()
  activityChart?.resize()
}

// 监听设备数据变化，更新图表
watch(deviceData, () => {
  updateDeviceChart()
}, { deep: true })

// 监听按摩数据变化，更新图表
watch(massageData, () => {
  updateActivityChart()
}, { deep: true })

onMounted(async () => {
  try {
    // 先加载设备数据
    await loadDeviceData()
    // 再加载按摩统计数据
    await loadMassageStats()
    
    // 初始化图表
    nextTick(() => {
      initDeviceChart()
      initActivityChart()
    })
  } catch (error) {
    console.error('数据加载失败:', error)
  }
  
  window.addEventListener('resize', handleResize)
})

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  deviceChart?.dispose()
  activityChart?.dispose()
})
</script>

<style lang="scss" scoped>
.tit {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .time {
    color: #909399;
    font-size: 14px;
  }
}

.dataCon {
  padding: 10px 0;
}

.data-item {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  height: 100%;
  min-height: 320px;
  display: flex;
  flex-direction: column;
  
  .data-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    
    .el-icon {
      font-size: 24px;
      margin-right: 10px;
      
      &.icon-device {
        color: #409EFF;
      }
      
      &.icon-time {
        color: #E6A23C;
      }
      
      &.icon-active {
        color: #67C23A;
      }
    }
    
    .title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }
  }
  
  .data-content {
    flex: 1;
    
    .total-number {
      font-size: 36px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 15px;
      
      .unit {
        font-size: 14px;
        font-weight: normal;
        color: #909399;
        margin-left: 5px;
      }
    }
    
    .sub-info {
      display: flex;
      gap: 20px;
      font-size: 14px;
      color: #606266;
      
      .online {
        color: #67C23A;
        display: flex;
        align-items: center;
        gap: 4px;
      }
      
      .offline {
        color: #F56C6C;
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
    
    .activity-rate {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px 0;
      
      .rate-number {
        font-size: 48px;
        font-weight: bold;
        color: #409EFF;
      }
      
      .rate-label {
        font-size: 14px;
        color: #909399;
        margin-top: 10px;
      }
    }
  }
  
  .stats-info {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #EBEEF5;
    
    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .label {
        font-size: 12px;
        color: #909399;
        margin-bottom: 5px;
      }
      
      .value {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
  
  .chart-container {
    width: 100%;
    height: 150px;
    margin-top: 10px;
  }
}

// 响应式布局
@media (max-width: 768px) {
  .data-item {
    min-height: 280px;
    
    .data-content {
      .total-number {
        font-size: 28px;
      }
      
      .activity-rate {
        .rate-number {
          font-size: 36px;
        }
      }
    }
    
    .chart-container {
      height: 120px;
    }
  }
}
</style>