<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <!-- 能耗监测标签页 -->
      <el-tab-pane label="能耗监测" name="monitoring">
        <el-form :model="energyQuery" ref="energyQueryRef" :inline="true" label-width="80px">
          <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="energyQuery.deviceCode" placeholder="请输入设备编码" clearable />
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="energyQuery.deviceName" placeholder="请输入设备名称" clearable />
          </el-form-item>
          <el-form-item label="能耗类型" prop="energyType">
            <el-select v-model="energyQuery.energyType" placeholder="请选择能耗类型" clearable style="width: 180px;">
              <el-option label="电" value="electricity" />
              <el-option label="水" value="water" />
              <el-option label="煤" value="coal" />
              <el-option label="气" value="gas" />
            </el-select>
          </el-form-item>
          <el-form-item label="楼栋" prop="building">
            <el-select v-model="energyQuery.building" placeholder="请选择楼栋" clearable style="width: 180px;">
              <el-option label="A栋" value="A" />
              <el-option label="B栋" value="B" />
              <el-option label="C栋" value="C" />
              <el-option label="D栋" value="D" />
            </el-select>
          </el-form-item>
          <el-form-item label="楼层" prop="floor">
            <el-input v-model="energyQuery.floor" placeholder="请输入楼层" clearable />
          </el-form-item>
          <el-form-item label="时间范围" prop="timeRange">
            <el-date-picker
                v-model="energyQuery.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getEnergyList">搜索</el-button>
            <el-button icon="Refresh" @click="resetEnergyQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="energyLoading" :data="energyList" stripe border>
          <el-table-column label="设备编码" prop="deviceCode"  />
          <el-table-column label="设备名称" prop="deviceName"  />
          <el-table-column label="能耗类型" prop="energyType" >
            <template #default="scope">
              <el-tag :type="getEnergyTypeTag(scope.row.energyType)">
                {{ getEnergyTypeText(scope.row.energyType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="位置信息" >
            <template #default="scope">
              <div>{{ scope.row.building }}栋-{{ scope.row.floor }}层</div>
              <div class="text-gray-500">{{ scope.row.roomNo }}</div>
            </template>
          </el-table-column>
          <el-table-column label="当前功率" prop="currentPower" >
            <template #default="scope">
              <span>{{ scope.row.currentPower }} kW</span>
            </template>
          </el-table-column>
          <el-table-column label="今日能耗" prop="dailyConsumption">
            <template #default="scope">
              <span>{{ scope.row.dailyConsumption }} {{ getUnit(scope.row.energyType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="月度能耗" prop="monthlyConsumption" >
            <template #default="scope">
              <span>{{ scope.row.monthlyConsumption }} {{ getUnit(scope.row.energyType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备状态" prop="deviceStatus" >
            <template #default="scope">
              <el-tag :type="scope.row.deviceStatus === 1 ? 'success' : scope.row.deviceStatus === 2 ? 'warning' : 'danger'">
                {{ getStatusText(scope.row.deviceStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updateTime" >
            <template #default="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作"  fixed="right" width="270px">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="handleEnergyDetail(scope.row)">详情</el-button>
              <el-button link type="success" icon="TrendCharts" @click="handleEnergyChart(scope.row)">能耗曲线</el-button>
              <el-button link type="warning" icon="Setting" @click="handleDeviceControl(scope.row)">设备控制</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="energyTotal > 0"
            :total="energyTotal"
            v-model:page="energyQuery.pageNum"
            v-model:limit="energyQuery.pageSize"
            @pagination="getEnergyList"
        />
      </el-tab-pane>

      <!-- 能耗统计标签页 -->
      <el-tab-pane label="能耗统计" name="statistics">
        <!-- 统计概览卡片 -->
        <el-row :gutter="20" class="stat-cards">
          <el-col :span="6">
            <div class="stat-card electricity-card">
              <div class="stat-card-icon">
                <svg viewBox="0 0 24 24" width="40" height="40">
                  <path fill="currentColor" d="M11 9L7 21L13 15H17L13 3L7 9H11Z"/>
                </svg>
              </div>
              <div class="stat-card-content">
                <div class="stat-card-title">今日用电</div>
                <div class="stat-card-value">{{ statisticsData.todayElectricity }}</div>
                <div class="stat-card-unit">kWh</div>
                <div class="stat-card-trend">
                  <span class="trend-up">↑ 12.5%</span>
                  <span class="trend-text">较昨日</span>
                </div>
              </div>
              <div class="stat-card-bg"></div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card water-card">
              <div class="stat-card-icon">
                <svg viewBox="0 0 24 24" width="40" height="40">
                  <path fill="currentColor" d="M12,20A6,6 0 0,1 6,14C6,10 12,3.25 12,3.25C12,3.25 18,10 18,14A6,6 0 0,1 12,20Z"/>
                </svg>
              </div>
              <div class="stat-card-content">
                <div class="stat-card-title">今日用水</div>
                <div class="stat-card-value">{{ statisticsData.todayWater }}</div>
                <div class="stat-card-unit">m³</div>
                <div class="stat-card-trend">
                  <span class="trend-down">↓ 8.3%</span>
                  <span class="trend-text">较昨日</span>
                </div>
              </div>
              <div class="stat-card-bg"></div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card gas-card">
              <div class="stat-card-icon">
                <svg viewBox="0 0 24 24" width="40" height="40">
                  <path fill="currentColor" d="M17.66 11.2C17.43 10.9 17.15 10.64 16.89 10.38C16.22 9.78 15.46 9.35 14.82 8.72C13.33 7.26 13 4.85 13.95 3C13 3.23 12.17 3.75 11.46 4.32C8.87 6.4 7.85 10.07 9.07 13.22C9.11 13.32 9.15 13.42 9.15 13.55C9.15 13.77 9 13.97 8.8 14.05C8.57 14.15 8.33 14.09 8.14 13.93C8.05 13.84 7.94 13.77 7.86 13.64C6.05 12.46 5.03 10.5 5.03 8.5A8.5 8.5 0 0 1 13.53 0C13.53 2.62 15.44 4.86 16.5 6.37C17.19 7.38 17.5 8.68 17.5 9.83C17.5 10.34 17.5 10.84 17.66 11.2Z"/>
                </svg>
              </div>
              <div class="stat-card-content">
                <div class="stat-card-title">今日用气</div>
                <div class="stat-card-value">{{ statisticsData.todayGas }}</div>
                <div class="stat-card-unit">m³</div>
                <div class="stat-card-trend">
                  <span class="trend-up">↑ 5.2%</span>
                  <span class="trend-text">较昨日</span>
                </div>
              </div>
              <div class="stat-card-bg"></div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card device-card">
              <div class="stat-card-icon">
                <svg viewBox="0 0 24 24" width="40" height="40">
                  <path fill="currentColor" d="M6,2L10,6V8L14,12V14L17.41,17.41C17.78,17.04 18.27,16.8 18.82,16.8C20.03,16.8 21,17.77 21,19C21,20.23 20.03,21.2 18.82,21.2C17.6,21.2 16.63,20.23 16.63,19C16.63,18.45 16.88,17.96 17.25,17.59L14,14.34V12.34L10,8.34V6.34L6.41,2.75C6.04,3.12 5.55,3.37 5,3.37C3.77,3.37 2.8,2.4 2.8,1.18C2.8,-0.03 3.77,-1 5,-1C6.23,-1 7.2,-0.03 7.2,1.18C7.2,1.74 6.96,2.23 6.59,2.59L6,2M5,0.2A1,1 0 0,0 4,1.2A1,1 0 0,0 5,2.2A1,1 0 0,0 6,1.2A1,1 0 0,0 5,0.2M18.82,18A1,1 0 0,0 17.82,19A1,1 0 0,0 18.82,20A1,1 0 0,0 19.82,19A1,1 0 0,0 18.82,18M3,7V9H7V7H3M3,11V13H7V11H3M3,15V17H7V15H3Z"/>
                </svg>
              </div>
              <div class="stat-card-content">
                <div class="stat-card-title">设备状态</div>
                <div class="stat-card-value">{{ statisticsData.onlineDevices }}/{{ statisticsData.totalDevices }}</div>
                <div class="stat-card-unit">在线率 {{ Math.round(statisticsData.onlineDevices / statisticsData.totalDevices * 100) }}%</div>
                <div class="stat-card-trend">
                  <span class="trend-warning">⚠ {{ statisticsData.alarmDevices }}</span>
                  <span class="trend-text">设备告警</span>
                </div>
              </div>
              <div class="stat-card-bg"></div>
            </div>
          </el-col>
        </el-row>

        <!-- 能耗趋势图表 -->
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="16">
            <el-card class="chart-card">
              <div class="chart-header">
                <h3>能耗趋势分析</h3>
                <el-radio-group v-model="trendTimeRange" size="small" @change="updateStatCharts">
                  <el-radio-button label="day">今日</el-radio-button>
                  <el-radio-button label="week">本周</el-radio-button>
                  <el-radio-button label="month">本月</el-radio-button>
                  <el-radio-button label="year">本年</el-radio-button>
                </el-radio-group>
              </div>
              <div id="trendChart" style="width: 100%; height: 350px;"></div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="chart-card">
              <div class="chart-header">
                <h3>能耗占比分析</h3>
              </div>
              <div id="ratioChart" style="width: 100%; height: 350px;"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 楼栋能耗排行 -->
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="12">
            <el-card class="chart-card">
              <div class="chart-header">
                <h3>楼栋能耗排行</h3>
                <el-link type="primary">查看详情 →</el-link>
              </div>
              <div id="buildingChart" style="width: 100%; height: 300px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <div class="chart-header">
                <h3>能耗费用分析</h3>
                <el-link type="primary">费用明细 →</el-link>
              </div>
              <div id="costChart" style="width: 100%; height: 300px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <!-- 能耗详情抽屉 -->
    <el-drawer
        v-model="detailVisible"
        title="设备能耗详情"
        direction="rtl"
        size="50%"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备编码">{{ currentDevice.deviceCode }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ currentDevice.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="能耗类型">{{ getEnergyTypeText(currentDevice.energyType) }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag :type="currentDevice.deviceStatus === 1 ? 'success' : currentDevice.deviceStatus === 2 ? 'warning' : 'danger'">
            {{ getStatusText(currentDevice.deviceStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="位置">{{ currentDevice.building }}栋-{{ currentDevice.floor }}层-{{ currentDevice.roomNo }}</el-descriptions-item>
        <el-descriptions-item label="当前功率">{{ currentDevice.currentPower }} kW</el-descriptions-item>
        <el-descriptions-item label="今日能耗">{{ currentDevice.dailyConsumption }} {{ getUnit(currentDevice.energyType) }}</el-descriptions-item>
        <el-descriptions-item label="月度能耗">{{ currentDevice.monthlyConsumption }} {{ getUnit(currentDevice.energyType) }}</el-descriptions-item>
        <el-descriptions-item label="年度能耗">{{ currentDevice.yearlyConsumption }} {{ getUnit(currentDevice.energyType) }}</el-descriptions-item>
        <el-descriptions-item label="额定功率">{{ currentDevice.ratedPower }} kW</el-descriptions-item>
        <el-descriptions-item label="负载率">{{ currentDevice.loadRate }}%</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(currentDevice.updateTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 能耗曲线图抽屉 -->
    <el-drawer
        v-model="chartVisible"
        title="能耗曲线分析"
        direction="rtl"
        size="60%"
    >
      <el-form :inline="true" style="margin-bottom: 20px">
        <el-form-item label="时间维度">
          <el-radio-group v-model="chartTimeType" @change="updateChart">
            <el-radio-button label="hour">小时</el-radio-button>
            <el-radio-button label="day">天</el-radio-button>
            <el-radio-button label="week">周</el-radio-button>
            <el-radio-button label="month">月</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数据类型">
          <el-radio-group v-model="chartDataType" @change="updateChart">
            <el-radio-button label="consumption">能耗量</el-radio-button>
            <el-radio-button label="power">功率</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div id="energyChart" style="width: 100%; height: 400px;"></div>
      <div id="energyPieChart" style="width: 100%; height: 300px; margin-top: 20px;"></div>
    </el-drawer>

    <!-- 设备控制抽屉 -->
    <el-drawer
        v-model="controlVisible"
        title="设备控制"
        direction="rtl"
        size="40%"
    >
      <el-form :model="controlForm" label-width="100px">
        <el-form-item label="设备名称">
          <el-input v-model="controlForm.deviceName" disabled />
        </el-form-item>
        <el-form-item label="设备状态">
          <el-radio-group v-model="controlForm.deviceStatus">
            <el-radio :label="1">启动</el-radio>
            <el-radio :label="0">停止</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="功率设置" v-if="controlForm.energyType === 'electricity'">
          <el-slider v-model="controlForm.powerSetting" :min="0" :max="100" show-input />
        </el-form-item>
        <el-form-item label="温度设置" v-if="controlForm.deviceType === 'air_conditioner'">
          <el-input-number v-model="controlForm.temperature" :min="16" :max="30" :step="1" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleDeviceControlSubmit">确认控制</el-button>
          <el-button @click="controlVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, reactive, watch, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { listEnergyDevices, getEnergyStatistics, controlDevice } from '@/api/subsystem/energy'


const { proxy } = getCurrentInstance()
const activeTab = ref('monitoring')

// 监听activeTab的变化
watch(activeTab, (newVal) => {
  if (newVal === 'statistics') {
    getStatisticsData()
  } else {
    // 清理统计图表
    if (trendChart) {
      trendChart.dispose()
      trendChart = null
    }
    if (ratioChart) {
      ratioChart.dispose()
      ratioChart = null
    }
    if (buildingChart) {
      buildingChart.dispose()
      buildingChart = null
    }
    if (costChart) {
      costChart.dispose()
      costChart = null
    }
  }
})

// 能耗监测查询相关
const energyQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  deviceCode: null,
  deviceName: null,
  energyType: null,
  building: null,
  floor: null,
  timeRange: []
})
const energyList = ref([])
const energyTotal = ref(0)
const energyLoading = ref(false)

// 统计数据
const statisticsData = ref({
  todayElectricity: 1256.8,
  todayWater: 234.5,
  todayGas: 89.3,
  monthElectricity: 38521.2,
  monthWater: 7023.6,
  monthGas: 2679.9,
  onlineDevices: 186,
  totalDevices: 200,
  alarmDevices: 3
})

// 统计图表相关
const trendTimeRange = ref('week')
let trendChart = null
let ratioChart = null
let buildingChart = null
let costChart = null

// 详情相关
const detailVisible = ref(false)
const currentDevice = ref({})

// 图表相关
const chartVisible = ref(false)
const chartTimeType = ref('day')
const chartDataType = ref('consumption')
let lineChart = null
let pieChart = null

// 控制相关
const controlVisible = ref(false)
const controlForm = ref({
  deviceCode: '',
  deviceName: '',
  deviceStatus: 1,
  powerSetting: 50,
  temperature: 24,
  energyType: '',
  deviceType: ''
})

// 能耗类型标签
const getEnergyTypeTag = (type) => {
  const tags = {
    'electricity': 'danger',
    'water': 'primary',
    'coal': 'info',
    'gas': 'success'
  }
  return tags[type] || 'info'
}

// 能耗类型文本
const getEnergyTypeText = (type) => {
  const texts = {
    'electricity': '电',
    'water': '水',
    'coal': '煤',
    'gas': '气'
  }
  return texts[type] || '未知'
}

// 单位
const getUnit = (type) => {
  const units = {
    'electricity': 'kWh',
    'water': 'm³',
    'coal': 't',
    'gas': 'm³'
  }
  return units[type] || ''
}

// 设备状态文本
const getStatusText = (status) => {
  const texts = ['离线', '在线', '故障', '维护']
  return texts[status] || '未知'
}

// 查询能耗设备列表
function getEnergyList() {
  energyLoading.value = true
  const params = {
    ...energyQuery,
    pageNum: energyQuery.pageNum,
    pageSize: energyQuery.pageSize
  }
  if (energyQuery.timeRange && energyQuery.timeRange.length === 2) {
    params.beginTime = energyQuery.timeRange[0]
    params.endTime = energyQuery.timeRange[1]
  }
  listEnergyDevices(params).then(response => {
    energyList.value = response.rows
    energyTotal.value = response.total
    energyLoading.value = false
  })
}

// 重置查询
function resetEnergyQuery() {
  proxy.resetForm('energyQueryRef')
  energyQuery.pageNum = 1
  getEnergyList()
}

// 获取统计数据
function getStatisticsData() {
  getEnergyStatistics().then(response => {
    statisticsData.value = response.data
    // 初始化统计图表
    initStatCharts()
  }).catch(() => {
    // 如果接口失败，使用默认数据
    statisticsData.value = {
      todayElectricity: 1256.8,
      todayWater: 234.5,
      todayGas: 89.3,
      monthElectricity: 38521.2,
      monthWater: 7023.6,
      monthGas: 2679.9,
      onlineDevices: 186,
      totalDevices: 200,
      alarmDevices: 3
    }
    initStatCharts()
  })
}

// 初始化统计图表
function initStatCharts() {
  nextTick(() => {
    // 趋势图
    const trendChartDom = document.getElementById('trendChart')
    if (trendChartDom) {
      trendChart = echarts.init(trendChartDom)
      const trendOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['电', '水', '气', '总费用'],
          bottom: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: generateTimeLabels(trendTimeRange.value),
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '能耗量',
            min: 0,
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '费用(元)',
            min: 0,
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '电',
            type: 'bar',
            data: generateRandomData(generateTimeLabels(trendTimeRange.value).length, 100, 300),
            itemStyle: {
              color: '#ff6b6b'
            }
          },
          {
            name: '水',
            type: 'bar',
            data: generateRandomData(generateTimeLabels(trendTimeRange.value).length, 30, 80),
            itemStyle: {
              color: '#4dabf7'
            }
          },
          {
            name: '气',
            type: 'bar',
            data: generateRandomData(generateTimeLabels(trendTimeRange.value).length, 20, 60),
            itemStyle: {
              color: '#51cf66'
            }
          },
          {
            name: '总费用',
            type: 'line',
            yAxisIndex: 1,
            data: generateRandomData(generateTimeLabels(trendTimeRange.value).length, 500, 1500),
            smooth: true,
            itemStyle: {
              color: '#ffd43b'
            }
          }
        ]
      }
      trendChart.setOption(trendOption)
    }

    // 占比图
    const ratioChartDom = document.getElementById('ratioChart')
    if (ratioChartDom) {
      ratioChart = echarts.init(ratioChartDom)
      const ratioOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
          {
            name: '能耗占比',
            type: 'pie',
            radius: ['45%', '75%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{d}%'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: [
              { value: 450, name: '电', itemStyle: { color: '#ff6b6b' } },
              { value: 150, name: '水', itemStyle: { color: '#4dabf7' } },
              { value: 100, name: '气', itemStyle: { color: '#51cf66' } }
            ]
          }
        ]
      }
      ratioChart.setOption(ratioOption)
    }

    // 楼栋排行图
    const buildingChartDom = document.getElementById('buildingChart')
    if (buildingChartDom) {
      buildingChart = echarts.init(buildingChartDom)
      const buildingOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.01]
        },
        yAxis: {
          type: 'category',
          data: ['D栋', 'C栋', 'B栋', 'A栋']
        },
        series: [
          {
            name: '能耗量',
            type: 'bar',
            data: [180, 230, 290, 330],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            label: {
              show: true,
              position: 'right',
              formatter: '{c} kWh'
            }
          }
        ]
      }
      buildingChart.setOption(buildingOption)
    }

    // 费用分析图
    const costChartDom = document.getElementById('costChart')
    if (costChartDom) {
      costChart = echarts.init(costChartDom)
      const costOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: ¥{c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['峰时', '平时', '谷时'],
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '费用(元)',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '费用',
            type: 'bar',
            barWidth: '60%',
            data: [
              {
                value: 1200,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#ff9999' },
                    { offset: 1, color: '#ff6666' }
                  ])
                }
              },
              {
                value: 800,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#66b3ff' },
                    { offset: 1, color: '#3399ff' }
                  ])
                }
              },
              {
                value: 400,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#90ee90' },
                    { offset: 1, color: '#66cc66' }
                  ])
                }
              }
            ],
            label: {
              show: true,
              position: 'top',
              formatter: '¥{c}'
            }
          }
        ]
      }
      costChart.setOption(costOption)
    }

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      trendChart && trendChart.resize()
      ratioChart && ratioChart.resize()
      buildingChart && buildingChart.resize()
      costChart && costChart.resize()
    })
  })
}

// 生成时间标签
function generateTimeLabels(type) {
  const now = new Date()
  const labels = []

  switch (type) {
    case 'day':
      for (let i = 0; i < 24; i++) {
        labels.push(`${i}:00`)
      }
      break
    case 'week':
      const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      return days
    case 'month':
      const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate()
      for (let i = 1; i <= daysInMonth; i++) {
        labels.push(`${i}日`)
      }
      break
    case 'year':
      for (let i = 1; i <= 12; i++) {
        labels.push(`${i}月`)
      }
      break
  }

  return labels
}

// 生成随机数据
function generateRandomData(count, min, max) {
  const data = []
  for (let i = 0; i < count; i++) {
    data.push(Math.floor(Math.random() * (max - min + 1)) + min)
  }
  return data
}

// 更新统计图表
function updateStatCharts() {
  if (trendChart) {
    const labels = generateTimeLabels(trendTimeRange.value)
    const dataCount = labels.length

    trendChart.setOption({
      xAxis: [{
        data: labels
      }],
      series: [
        {
          name: '电',
          data: generateRandomData(dataCount, 100, 300)
        },
        {
          name: '水',
          data: generateRandomData(dataCount, 30, 80)
        },
        {
          name: '气',
          data: generateRandomData(dataCount, 20, 60)
        },
        {
          name: '总费用',
          data: generateRandomData(dataCount, 500, 1500)
        }
      ]
    })
  }
}

// 清理图表
onBeforeUnmount(() => {
  // 清理能耗监测图表
  if (lineChart) {
    lineChart.dispose()
    lineChart = null
  }
  if (pieChart) {
    pieChart.dispose()
    pieChart = null
  }
  // 清理统计图表
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
  if (ratioChart) {
    ratioChart.dispose()
    ratioChart = null
  }
  if (buildingChart) {
    buildingChart.dispose()
    buildingChart = null
  }
  if (costChart) {
    costChart.dispose()
    costChart = null
  }
})

// 查看详情
function handleEnergyDetail(row) {
  currentDevice.value = row
  detailVisible.value = true
}

// 生成模拟数据
function generateChartData(timeType, dataType, energyType) {
  const now = new Date()
  const data = []
  let count = 0
  let dateFormat = ''

  switch (timeType) {
    case 'hour':
      count = 24
      dateFormat = (i) => {
        const date = new Date(now)
        date.setHours(now.getHours() - (23 - i))
        return `${date.getHours()}:00`
      }
      break
    case 'day':
      count = 30
      dateFormat = (i) => {
        const date = new Date(now)
        date.setDate(now.getDate() - (29 - i))
        return `${date.getMonth() + 1}-${date.getDate()}`
      }
      break
    case 'week':
      count = 12
      dateFormat = (i) => `第${i + 1}周`
      break
    case 'month':
      count = 12
      dateFormat = (i) => `${i + 1}月`
      break
  }

  // 根据能耗类型生成基础值
  const baseValues = {
    electricity: { consumption: 100, power: 50 },
    water: { consumption: 50, power: 20 },
    gas: { consumption: 30, power: 15 },
    coal: { consumption: 10, power: 5 }
  }

  const base = baseValues[energyType] || baseValues.electricity
  const baseValue = dataType === 'consumption' ? base.consumption : base.power

  for (let i = 0; i < count; i++) {
    const randomFactor = 0.5 + Math.random() * 1
    const value = (baseValue * randomFactor).toFixed(2)
    data.push({
      time: dateFormat(i),
      value: parseFloat(value)
    })
  }

  return data
}

// 初始化图表
function initChart() {
  nextTick(() => {
    // 初始化折线图
    const lineChartDom = document.getElementById('energyChart')
    if (lineChartDom) {
      lineChart = echarts.init(lineChartDom)

      const data = generateChartData(chartTimeType.value, chartDataType.value, currentDevice.value.energyType)
      const unit = chartDataType.value === 'consumption' ? getUnit(currentDevice.value.energyType) : 'kW'

      const option = {
        title: {
          text: `${currentDevice.value.deviceName} - ${chartDataType.value === 'consumption' ? '能耗趋势' : '功率变化'}`,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            return `${params[0].name}<br/>${params[0].marker} ${params[0].value} ${unit}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.map(item => item.time),
          axisLabel: {
            rotate: chartTimeType.value === 'hour' ? 45 : 0
          }
        },
        yAxis: {
          type: 'value',
          name: unit,
          axisLabel: {
            formatter: `{value} ${unit}`
          }
        },
        series: [{
          name: chartDataType.value === 'consumption' ? '能耗量' : '功率',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          sampling: 'average',
          itemStyle: {
            color: '#5470c6'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
              { offset: 1, color: 'rgba(84, 112, 198, 0.05)' }
            ])
          },
          data: data.map(item => item.value)
        }]
      }

      lineChart.setOption(option)
    }

    // 初始化饼图（能耗构成分析）
    const pieChartDom = document.getElementById('energyPieChart')
    if (pieChartDom) {
      pieChart = echarts.init(pieChartDom)

      const pieOption = {
        title: {
          text: '能耗时段分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '时段分布',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 335, name: '高峰时段' },
            { value: 310, name: '平峰时段' },
            { value: 234, name: '低谷时段' }
          ]
        }]
      }

      pieChart.setOption(pieOption)
    }

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      lineChart && lineChart.resize()
      pieChart && pieChart.resize()
    })
  })
}

// 更新图表
function updateChart() {
  if (lineChart && currentDevice.value) {
    const data = generateChartData(chartTimeType.value, chartDataType.value, currentDevice.value.energyType)
    const unit = chartDataType.value === 'consumption' ? getUnit(currentDevice.value.energyType) : 'kW'

    lineChart.setOption({
      title: {
        text: `${currentDevice.value.deviceName} - ${chartDataType.value === 'consumption' ? '能耗趋势' : '功率变化'}`
      },
      xAxis: {
        data: data.map(item => item.time)
      },
      yAxis: {
        name: unit,
        axisLabel: {
          formatter: `{value} ${unit}`
        }
      },
      series: [{
        name: chartDataType.value === 'consumption' ? '能耗量' : '功率',
        data: data.map(item => item.value)
      }]
    })
  }
}

// 查看能耗曲线
function handleEnergyChart(row) {
  currentDevice.value = row
  chartVisible.value = true
  // 重置图表选项
  chartTimeType.value = 'day'
  chartDataType.value = 'consumption'
  // 初始化图表
  initChart()
}

// 设备控制
function handleDeviceControl(row) {
  controlForm.value = {
    deviceCode: row.deviceCode,
    deviceName: row.deviceName,
    deviceStatus: row.deviceStatus,
    powerSetting: row.powerSetting || 50,
    temperature: row.temperature || 24,
    energyType: row.energyType,
    deviceType: row.deviceType
  }
  controlVisible.value = true
}

// 提交设备控制
function handleDeviceControlSubmit() {
  controlDevice(controlForm.value).then(response => {
    proxy.$modal.msgSuccess('设备控制指令发送成功')
    controlVisible.value = false
    getEnergyList()
  })
}

// 清理图表
watch(chartVisible, (newVal) => {
  if (!newVal) {
    if (lineChart) {
      lineChart.dispose()
      lineChart = null
    }
    if (pieChart) {
      pieChart.dispose()
      pieChart = null
    }
  }
})

// 初始化
onMounted(() => {
  getEnergyList()
  getStatisticsData()
})
</script>

<style scoped>
.energy-stat {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.energy-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.device-stat {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-text {
  font-size: 14px;
  color: #666;
}

.box-card {
  margin-bottom: 20px;
}

/* 统计卡片样式 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  padding: 20px;
  border-radius: 16px;
  background: #fff;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stat-card-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  opacity: 0.2;
  transition: all 0.3s ease;
}

.stat-card:hover .stat-card-icon {
  opacity: 0.3;
  transform: scale(1.1);
}

.stat-card-content {
  position: relative;
  z-index: 1;
}

.stat-card-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-card-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-card-unit {
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
}

.stat-card-trend {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}

.trend-up {
  color: #ff6b6b;
  font-weight: bold;
}

.trend-down {
  color: #51cf66;
  font-weight: bold;
}

.trend-warning {
  color: #ffd43b;
  font-weight: bold;
}

.trend-text {
  color: #999;
}

.stat-card-bg {
  position: absolute;
  bottom: -20px;
  right: -20px;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  opacity: 0.05;
}

/* 不同类型卡片的颜色主题 */
.electricity-card {
  background: linear-gradient(135deg, #fff5f5 0%, #ffe0e0 100%);
}

.electricity-card .stat-card-value {
  color: #ff6b6b;
}

.electricity-card .stat-card-icon {
  color: #ff6b6b;
}

.electricity-card .stat-card-bg {
  background: #ff6b6b;
}

.water-card {
  background: linear-gradient(135deg, #f0f8ff 0%, #e0f2ff 100%);
}

.water-card .stat-card-value {
  color: #4dabf7;
}

.water-card .stat-card-icon {
  color: #4dabf7;
}

.water-card .stat-card-bg {
  background: #4dabf7;
}

.gas-card {
  background: linear-gradient(135deg, #f0fff4 0%, #e6fcf5 100%);
}

.gas-card .stat-card-value {
  color: #51cf66;
}

.gas-card .stat-card-icon {
  color: #51cf66;
}

.gas-card .stat-card-bg {
  background: #51cf66;
}

.device-card {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.device-card .stat-card-value {
  color: #495057;
}

.device-card .stat-card-icon {
  color: #495057;
}

.device-card .stat-card-bg {
  background: #495057;
}

/* 图表卡片样式 */
.chart-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.chart-card .el-card__body {
  padding: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.chart-header .el-radio-group {
  background: #f5f7fa;
  padding: 2px;
  border-radius: 6px;
}

.chart-header .el-radio-button__inner {
  padding: 6px 16px;
  border: none;
  background: transparent;
}

.chart-header .el-radio-button.is-active .el-radio-button__inner {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card {
  animation: fadeInUp 0.6s ease-out;
}

.stat-card:nth-child(1) {
  animation-delay: 0.1s;
}

.stat-card:nth-child(2) {
  animation-delay: 0.2s;
}

.stat-card:nth-child(3) {
  animation-delay: 0.3s;
}

.stat-card:nth-child(4) {
  animation-delay: 0.4s;
}
</style>
