<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <!-- 能耗监测标签页 -->
      <el-tab-pane label="列表监控" name="monitoring">
        <el-form :model="energyQuery" ref="energyQueryRef" :inline="true" label-width="80px">
          <el-form-item label="设备名称" prop="query">
            <el-input v-model="energyQuery.query" placeholder="请输入设备名称" clearable style="width: 200px;" />
          </el-form-item>
          <el-form-item label="设备类型" prop="device_type_id">
            <el-select v-model="energyQuery.device_type_id" placeholder="请选择设备类型" clearable style="width: 200px;">
              <el-option
                  v-for="deviceType in deviceTypeList"
                  :key="deviceType.devices_type_id"
                  :label="`${deviceType.devices_type_name} (${deviceType.total}台)`"
                  :value="deviceType.devices_type_id"
              >
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <span>{{ deviceType.devices_type_name }}</span>
                  <div style="font-size: 12px; color: #999;">
                    <el-tag :type="deviceType.category_name === '电表' ? 'danger' : deviceType.category_name === '水表' ? 'primary' : 'success'" size="small">
                      {{ deviceType.category_name }}
                    </el-tag>
                    <span style="margin-left: 8px;">{{ deviceType.total }}台</span>
                  </div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="网关" prop="gateway_id">
            <el-select v-model="energyQuery.gateway_id" placeholder="请选择网关" clearable style="width: 200px;">
              <el-option
                  v-for="gateway in gatewayList"
                  :key="gateway.gateway_id"
                  :label="gateway.gateway_name"
                  :value="gateway.gateway_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备状态" prop="devices_enabled">
            <el-select v-model="energyQuery.devices_enabled" placeholder="请选择设备状态" clearable style="width: 120px;">
              <el-option label="全部" :value="-1" />
              <el-option label="在线" :value="1" />
              <el-option label="离线" :value="0" />
            </el-select>
          </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="设备ID" prop="devices_id" width="80" />
          <el-table-column label="设备名称" prop="devices_name" min-width="180" show-overflow-tooltip />
          <el-table-column label="设备类型" min-width="160">
            <template #default="scope">
              <div class="device-type-cell">
                <span class="device-icon">{{ getDeviceTypeIcon(scope.row.devices_type_name) }}</span>
                <el-tag
                    :color="getDeviceTypeColor(scope.row.devices_type_name)"
                    effect="light"
                    class="device-type-tag"
                >
                  {{ scope.row.devices_type_name }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分类" width="80">
            <template #default="scope">
              <el-tag :type="getCategoryTag(scope.row.category_name)" size="small">
                {{ scope.row.category_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="位置信息" min-width="200">
            <template #default="scope">
              <div>{{ scope.row.full_region_name }}</div>
              <div class="text-gray-500" v-if="scope.row.room_name">{{ scope.row.room_name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="网关信息" min-width="180" show-overflow-tooltip>
            <template #default="scope">
              <div>{{ scope.row.gateway_name }}</div>
              <div class="text-gray-500 text-xs">{{ scope.row.gateway_code }}</div>
            </template>
          </el-table-column>
          <el-table-column label="设备状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.devices_enabled === 1 ? 'success' : 'danger'">
                {{ scope.row.devices_enabled === 1 ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="能耗数据" min-width="150">
            <template #default="scope">
              <div class="energy-data">
                <span v-if="getEnergyData(scope.row.devices_json_object).EPE">
                  {{ getEnergyData(scope.row.devices_json_object).EPE }} kWh
                </span>
                <span v-if="getEnergyData(scope.row.devices_json_object).total_water">
                  {{ getEnergyData(scope.row.devices_json_object).total_water }} m³
                </span>
                <span v-if="!getEnergyData(scope.row.devices_json_object).EPE && !getEnergyData(scope.row.devices_json_object).total_water">
                  0
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="请求间隔" width="100">
            <template #default="scope">
              <span>{{ scope.row.devices_req_interval }}s</span>
            </template>
          </el-table-column>
          <el-table-column label="最后请求时间" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.devices_last_request_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.devices_created) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120" align="center">
            <template #default="scope">
<!--              <el-button link type="success" icon="Document" @click="handleHistoryQuery(scope.row)">历史记录</el-button>-->
              <el-button size="small" type="primary" icon="View" @click="handleDeviceDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>

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

      <!-- 能耗统计标签页 -->
      <el-tab-pane label="能耗统计" name="statistics">
        <div v-loading="statisticsLoading" element-loading-text="正在加载统计数据...">
          <div style="margin-bottom: 20px; text-align: left;">
            <el-button type="primary" icon="Refresh" @click="refreshStatisticsData" :loading="statisticsLoading">
              刷新统计数据
            </el-button>
          </div>

          <!-- 统计概览卡片 -->
          <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.electricityDevices }}</div>
                  <div class="stat-card-unit">台</div>
                  <div class="stat-card-trend">
                    <span class="trend-up">在线: {{ statisticsData.electricityOnline }}</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.waterDevices }}</div>
                  <div class="stat-card-unit">台</div>
                  <div class="stat-card-trend">
                    <span class="trend-up">在线: {{ statisticsData.waterOnline }}</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.gasDevices }}</div>
                  <div class="stat-card-unit">台</div>
                  <div class="stat-card-trend">
                    <span class="trend-up">在线: {{ statisticsData.gasOnline }}</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.totalDevices }}</div>
                  <div class="stat-card-unit">台</div>
                  <div class="stat-card-trend">
                    <span class="trend-warning">在线率: {{ getOnlineRate() }}%</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="12">
              <el-card class="chart-card">
                <div class="chart-header">
                  <h3>设备类型分布</h3>
                </div>
                <div id="deviceTypeChart" style="width: 100%; height: 350px;" v-loading="chartLoading.deviceType"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card">
                <div class="chart-header">
                  <h3>设备状态分布</h3>
                </div>
                <div id="deviceStatusChart" style="width: 100%; height: 350px;" v-loading="chartLoading.deviceStatus"></div>
              </el-card>
            </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="gatewayChartType" size="small" @change="updateGatewayChart">
                    <el-radio-button label="count">设备数量</el-radio-button>
                    <el-radio-button label="online">在线率</el-radio-button>
                  </el-radio-group>
                </div>
                <div id="gatewayChart" style="width: 100%; height: 350px;" v-loading="chartLoading.gateway"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="chart-card">
                <div class="chart-header">
                  <h3>区域设备分布</h3>
                </div>
                <div id="regionChart" style="width: 100%; height: 350px;" v-loading="chartLoading.region"></div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 设备详情抽屉 -->
    <el-drawer
        v-model="detailVisible"
        title="设备详情"
        direction="rtl"
        size="50%"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备ID">{{ currentDevice.devices_id }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{ currentDevice.devices_name }}</el-descriptions-item>
        <el-descriptions-item label="设备UDID">{{ currentDevice.devices_udid }}</el-descriptions-item>
        <el-descriptions-item label="设备类型">{{ currentDevice.devices_type_name }}</el-descriptions-item>
        <el-descriptions-item label="设备分类">{{ currentDevice.category_name }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag :type="currentDevice.devices_enabled === 1 ? 'success' : 'danger'">
            {{ currentDevice.devices_enabled === 1 ? '在线' : '离线' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="请求间隔">{{ currentDevice.devices_req_interval }}秒</el-descriptions-item>
        <el-descriptions-item label="位置信息" :span="2">
          {{ currentDevice.full_region_name }}
          <span v-if="currentDevice.room_name"> - {{ currentDevice.room_name }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="网关名称" :span="2">{{ currentDevice.gateway_name }}</el-descriptions-item>
        <el-descriptions-item label="网关代码" :span="2">{{ currentDevice.gateway_code }}</el-descriptions-item>
        <el-descriptions-item label="网关描述" :span="2">{{ currentDevice.gateway_description || '无' }}</el-descriptions-item>
        <el-descriptions-item label="最后请求时间" :span="2">{{ parseTime(currentDevice.devices_last_request_time) }}</el-descriptions-item>
        <el-descriptions-item label="网关最后请求时间" :span="2">{{ parseTime(currentDevice.gateway_last_request_time) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ parseTime(currentDevice.devices_created) }}</el-descriptions-item>
        <el-descriptions-item label="设备描述" :span="2">{{ currentDevice.devices_description || '无' }}</el-descriptions-item>
        <el-descriptions-item label="JSON配置" :span="2">
          <el-input
              v-model="currentDevice.devices_json_object"
              type="textarea"
              :rows="3"
              readonly
          />
        </el-descriptions-item>
        <el-descriptions-item label="能耗数据" :span="2" v-if="getEnergyData(currentDevice.devices_json_object)">
          <div class="energy-data">
            <span v-if="getEnergyData(currentDevice.devices_json_object).EPE">
              电能: {{ getEnergyData(currentDevice.devices_json_object).EPE }} kWh
            </span>
            <span v-if="getEnergyData(currentDevice.devices_json_object).total_water">
              总水量: {{ getEnergyData(currentDevice.devices_json_object).total_water }} m³
            </span>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 历史记录查询抽屉 -->
    <el-drawer
        v-model="historyVisible"
        title="设备历史记录"
        direction="rtl"
        size="70%"
    >
      <div class="history-container">
        <!-- 查询条件 -->
        <el-form :model="historyQuery" :inline="true" style="margin-bottom: 20px">
          <el-form-item label="设备名称">
            <el-input :value="currentDevice.devices_name" readonly style="width: 200px;" />
          </el-form-item>
          <el-form-item label="设备UDID">
            <el-input :value="currentDevice.devices_udid" readonly style="width: 250px;" />
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
                v-model="historyQuery.startTime"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 180px;"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
                v-model="historyQuery.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 180px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getHistoryData" :loading="historyLoading">
              查询
            </el-button>
            <el-button icon="Refresh" @click="resetHistoryQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 历史记录表格 -->
        <el-table v-loading="historyLoading" :data="historyList" stripe border style="width: 100%">
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="设备名称" prop="devices_name" min-width="150" show-overflow-tooltip />
          <el-table-column label="设备类型" prop="devices_type_name" width="140" />
          <el-table-column label="分类" width="80">
            <template #default="scope">
              <el-tag :type="getCategoryTag(scope.row.category_name)" size="small">
                {{ scope.row.category_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="能耗数据" min-width="150">
            <template #default="scope">
              <div class="energy-data">
            <span v-if="getEnergyData(scope.row.devices_json_object).EPE">
              {{ getEnergyData(scope.row.devices_json_object).EPE }} kWh
            </span>
                <span v-if="getEnergyData(scope.row.devices_json_object).total_water">
              {{ getEnergyData(scope.row.devices_json_object).total_water }} m³
            </span>
                <span v-if="!getEnergyData(scope.row.devices_json_object).EPE && !getEnergyData(scope.row.devices_json_object).total_water">
              0
            </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="设备状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.devices_enabled === 1 ? 'success' : 'danger'">
                {{ scope.row.devices_enabled === 1 ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="位置信息" min-width="180">
            <template #default="scope">
              <div>{{ scope.row.full_region_name }}</div>
              <div class="text-gray-500" v-if="scope.row.room_name">{{ scope.row.room_name }}</div>
            </template>
          </el-table-column>
          <el-table-column label="网关信息" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <div>{{ scope.row.gateway_name }}</div>
              <div class="text-gray-500 text-xs">{{ scope.row.gateway_code }}</div>
            </template>
          </el-table-column>
          <el-table-column label="记录时间" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.devices_last_request_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button size="small" type="primary" icon="View" @click="handleDeviceDetail(scope.row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
            v-show="historyTotal > 0"
            :total="historyTotal"
            v-model:page="historyQuery.currentPage"
            v-model:limit="historyQuery.pageSize"
            @pagination="getHistoryData"
            style="margin-top: 20px;"
        />
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="Nygl">
import * as echarts from 'echarts'
import { ref, reactive, watch, onMounted, nextTick, onBeforeUnmount, getCurrentInstance } from 'vue'
import axios from 'axios'

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

// 加载状态
const statisticsLoading = ref(false)
const chartLoading = ref({
  deviceType: false,
  deviceStatus: false,
  gateway: false,
  region: false,
  energy: false,
  energyPie: false
})

// 缓存数据
const cachedDevicesData = ref([])
const dataCache = ref({
  statistics: null,
  lastUpdateTime: null
})

// 监听activeTab的变化
watch(activeTab, (newVal) => {
  if (newVal === 'statistics') {
    loadStatisticsData()
  } else {
    clearStatCharts()
  }
})

// 能耗监测查询相关
const energyQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  device_type_id: null,
  devices_enabled: -1,
  query: null,
  gateway_id: null,
  devices_udid: null
})

const energyList = ref([])
const energyTotal = ref(0)
const energyLoading = ref(false)
const gatewayList = ref([])

// 统计数据
const statisticsData = ref({
  electricityDevices: 0,
  electricityOnline: 0,
  waterDevices: 0,
  waterOnline: 0,
  gasDevices: 0,
  gasOnline: 0,
  totalDevices: 0,
  onlineDevices: 0
})

// 统计图表相关
const gatewayChartType = ref('count')
let deviceTypeChart = null
let deviceStatusChart = null
let gatewayChart = null
let regionChart = null

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


// 分类标签
const getCategoryTag = (categoryName) => {
  if (!categoryName) return 'info'
  if (categoryName === '电表') return 'danger'
  if (categoryName === '水表') return 'primary'
  if (categoryName === '气表') return 'success'
  return 'info'
}

// 计算在线率
const getOnlineRate = () => {
  if (statisticsData.value.totalDevices === 0) return 0
  return Math.round(statisticsData.value.onlineDevices / statisticsData.value.totalDevices * 100)
}

// 解析能耗数据
const getEnergyData = (jsonStr) => {
  try {
    return JSON.parse(jsonStr || '{}')
  } catch (e) {
    return {}
  }
}

// 设备类型判断函数
const getDeviceCategory = (device) => {
  const typeName = (device.devices_type_name || '').toLowerCase()
  const categoryName = (device.category_name || '').toLowerCase()

  if (categoryName.includes('电表') ||
      typeName.includes('电表') ||
      typeName.includes('electric') ||
      (typeName.includes('bacnet') && (typeName.includes('三项') || typeName.includes('单项')))) {
    return 'electricity'
  } else if (categoryName.includes('水表') ||
      typeName.includes('水表') ||
      typeName.includes('water') ||
      typeName.includes('lxsy')) {
    return 'water'
  } else if (categoryName.includes('气表') ||
      typeName.includes('气表') ||
      typeName.includes('gas')) {
    return 'gas'
  }
  return 'other'
}

// 查询能耗设备列表
async function getEnergyList() {
  energyLoading.value = true
  try {
    const formData = new FormData()
    formData.append('currentPage', energyQuery.currentPage)
    formData.append('pageSize', energyQuery.pageSize)
    formData.append('devices_enabled', energyQuery.devices_enabled)

    if (energyQuery.device_type_id) {
      formData.append('device_type_id', energyQuery.device_type_id)
    }
    if (energyQuery.query) {
      formData.append('query', energyQuery.query)
    }
    if (energyQuery.gateway_id) {
      formData.append('gateway_id', energyQuery.gateway_id)
    }
    if (energyQuery.devices_udid) {
      formData.append('devices_udid', energyQuery.devices_udid)
    }

    const response = await axios.post(`${__LOCAL_API__}/energy/getBaseecic`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 200) {
      energyList.value = response.data.data.devices
      energyTotal.value = response.data.data.count
    } else {
      proxy.$modal.msgError(response.data.message || '获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    proxy.$modal.msgError('获取设备列表失败')
  } finally {
    energyLoading.value = false
  }
}

// 网关接口
async function getGatewayListFromAPI() {
  try {
    const response = await axios.get(`${__LOCAL_API__}/energy/gatewayFind`) // 或者其他网关接口

    if (response.data.code === 200) {
      gatewayList.value = response.data.data.gatewayAndBacnet.map(gateway => ({
        gateway_id: gateway.id || gateway.gateway_id,
        gateway_name: gateway.name || gateway.gateway_name
      }))
    } else {
      // 如果专门接口失败，回退到从设备数据提取
      await getGatewayList()
    }
  } catch (error) {
    console.error('从专门接口获取网关列表失败，尝试从设备数据提取:', error)
    // 回退方案
    await getGatewayList()
  }
}

const deviceTypeList = ref([])

// 获取设备类型列表
async function getDeviceTypeList() {
  try {
    const response = await axios.get(`${__LOCAL_API__}/energy/categoryStatistics`)

    if (response.data.code === 200) {
      const categoryStats = response.data.data.category_statistics
      deviceTypeList.value = []

      // 遍历分类统计数据，提取设备类型
      categoryStats.forEach(category => {
        category.type_statistics.forEach(type => {
          deviceTypeList.value.push({
            devices_type_id: type.devices_type_id,
            devices_type_name: type.devices_type_name,
            category_name: category.category_name,
            total: type.total,
            on_line: type.on_line,
            off_line: type.off_line
          })
        })
      })
    } else {
      console.error('获取设备类型失败:', response.data.message)
    }
  } catch (error) {
    console.error('获取设备类型失败:', error)
  }
}

// 重置查询
function resetEnergyQuery() {
  Object.assign(energyQuery, {
    currentPage: 1,
    pageSize: 10,
    device_type_id: null,
    devices_enabled: -1,
    query: null,
    gateway_id: null,
    devices_udid: null
  })
  getEnergyList()
}

// 获取所有设备数据用于统计（分页获取）
async function getAllDevicesData() {
  try {
    // 检查缓存
    const now = Date.now()
    if (dataCache.value.statistics &&
        dataCache.value.lastUpdateTime &&
        (now - dataCache.value.lastUpdateTime) < 5 * 60 * 1000) {
      return dataCache.value.statistics
    }

    let allDevices = []
    let currentPage = 1
    const pageSize = 100
    let hasMoreData = true

    while (hasMoreData) {
      const formData = new FormData()
      formData.append('currentPage', currentPage)
      formData.append('pageSize', pageSize)
      formData.append('devices_enabled', -1) // 获取所有设备

      const response = await axios.post(`${__LOCAL_API__}/energy/getBaseecic`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (response.data.code === 200) {
        const devices = response.data.data.devices
        const totalCount = response.data.data.count

        allDevices = allDevices.concat(devices)

        if (allDevices.length >= totalCount || devices.length < pageSize) {
          hasMoreData = false
        } else {
          currentPage++
        }

        if (hasMoreData) {
          await new Promise(resolve => setTimeout(resolve, 100))
        }
      } else {
        console.error('获取设备数据失败:', response.data.message)
        hasMoreData = false
      }
    }

    // 缓存数据
    dataCache.value.statistics = allDevices
    dataCache.value.lastUpdateTime = now

    console.log(`成功获取 ${allDevices.length} 条设备数据`)
    return allDevices

  } catch (error) {
    console.error('获取设备数据失败:', error)
    return []
  }
}

// 计算统计数据（简化版本，只统计devices_enabled字段）
function calculateStatistics(devices) {
  const stats = {
    electricityDevices: 0,
    electricityOnline: 0,
    waterDevices: 0,
    waterOnline: 0,
    gasDevices: 0,
    gasOnline: 0,
    totalDevices: devices.length,
    onlineDevices: 0
  }

  devices.forEach(device => {
    const category = getDeviceCategory(device)
    const isOnline = device.devices_enabled === 1 // 只看devices_enabled字段

    // 按分类统计
    switch (category) {
      case 'electricity':
        stats.electricityDevices++
        if (isOnline) stats.electricityOnline++
        break
      case 'water':
        stats.waterDevices++
        if (isOnline) stats.waterOnline++
        break
      case 'gas':
        stats.gasDevices++
        if (isOnline) stats.gasOnline++
        break
    }

    // 在线设备统计
    if (isOnline) {
      stats.onlineDevices++
    }
  })

  console.log('统计数据计算完成:', stats)
  return stats
}

// 加载统计数据
async function loadStatisticsData() {
  if (statisticsLoading.value) return

  statisticsLoading.value = true
  try {
    const devices = await getAllDevicesData()
    cachedDevicesData.value = devices

    // 计算统计数据
    statisticsData.value = calculateStatistics(devices)

    // 延迟初始化图表
    await nextTick()
    setTimeout(() => {
      initStatCharts(devices)
    }, 100)

  } catch (error) {
    console.error('加载统计数据失败:', error)
    proxy.$modal.msgError('加载统计数据失败')
  } finally {
    statisticsLoading.value = false
  }
}

// Tab切换处理
function handleTabChange(tabName) {
  if (tabName === 'statistics') {
    loadStatisticsData()
  }
}

// 初始化统计图表
async function initStatCharts(devices = []) {
  if (!devices.length) return

  await initDeviceTypeChart(devices)
  await initDeviceStatusChart(devices)
  await initGatewayChart(devices)
  await initRegionChart(devices)

  window.addEventListener('resize', resizeCharts)
}

// 初始化设备类型分布图
async function initDeviceTypeChart(devices) {
  chartLoading.value.deviceType = true

  await nextTick()

  const deviceTypeChartDom = document.getElementById('deviceTypeChart')
  if (!deviceTypeChartDom) {
    chartLoading.value.deviceType = false
    return
  }

  if (deviceTypeChart) {
    deviceTypeChart.dispose()
  }

  deviceTypeChart = echarts.init(deviceTypeChartDom)

  // 统计设备类型
  const typeStats = {}
  devices.forEach(device => {
    const typeName = device.devices_type_name || '未知类型'
    if (!typeStats[typeName]) {
      typeStats[typeName] = { total: 0, online: 0 }
    }
    typeStats[typeName].total++
    if (device.devices_enabled === 1) {
      typeStats[typeName].online++
    }
  })

  const typeData = Object.entries(typeStats).map(([name, data]) => ({
    name,
    value: data.total,
    itemStyle: {
      color: name.includes('电表') ? '#ff6b6b' :
          name.includes('水表') ? '#4dabf7' :
              name.includes('气表') ? '#51cf66' : '#ffd43b'
    }
  }))

  const typeOption = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const data = typeStats[params.name]
        const onlineRate = data.total > 0 ? Math.round((data.online / data.total) * 100) : 0
        return `${params.name}<br/>总数: ${data.total}台<br/>在线: ${data.online}台<br/>在线率: ${onlineRate}%`
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 12
      }
    },
    series: [{
      name: '设备类型',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        position: 'outside',
        formatter: '{b}\n{c}台'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        }
      },
      data: typeData
    }]
  }

  deviceTypeChart.setOption(typeOption)
  chartLoading.value.deviceType = false
}

// 初始化设备状态分布图（简化版本）
async function initDeviceStatusChart(devices) {
  chartLoading.value.deviceStatus = true

  await nextTick()

  const deviceStatusChartDom = document.getElementById('deviceStatusChart')
  if (!deviceStatusChartDom) {
    chartLoading.value.deviceStatus = false
    return
  }

  if (deviceStatusChart) {
    deviceStatusChart.dispose()
  }

  deviceStatusChart = echarts.init(deviceStatusChartDom)

  // 只统计devices_enabled字段
  const onlineCount = devices.filter(d => d.devices_enabled === 1).length
  const offlineCount = devices.filter(d => d.devices_enabled === 0).length

  const statusOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{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: true,
        position: 'outside',
        formatter: '{b}\n{c}台'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 14,
          fontWeight: 'bold'
        }
      },
      data: [
        {
          name: '在线',
          value: onlineCount,
          itemStyle: { color: '#67c23a' }
        },
        {
          name: '离线',
          value: offlineCount,
          itemStyle: { color: '#f56c6c' }
        }
      ]
    }]
  }

  deviceStatusChart.setOption(statusOption)
  chartLoading.value.deviceStatus = false
}

// 初始化网关分布图
async function initGatewayChart(devices) {
  chartLoading.value.gateway = true

  await nextTick()

  const gatewayChartDom = document.getElementById('gatewayChart')
  if (!gatewayChartDom) {
    chartLoading.value.gateway = false
    return
  }

  if (gatewayChart) {
    gatewayChart.dispose()
  }

  gatewayChart = echarts.init(gatewayChartDom)
  updateGatewayChart(devices)
}

// 初始化区域分布图
async function initRegionChart(devices) {
  chartLoading.value.region = true

  await nextTick()

  const regionChartDom = document.getElementById('regionChart')
  if (!regionChartDom) {
    chartLoading.value.region = false
    return
  }

  if (regionChart) {
    regionChart.dispose()
  }

  regionChart = echarts.init(regionChartDom)

  // 统计区域分布
  const regionStats = {}
  devices.forEach(device => {
    const regionName = device.region_name || '未知区域'
    regionStats[regionName] = (regionStats[regionName] || 0) + 1
  })

  const regionData = Object.entries(regionStats)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 10)

  const regionOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: regionData.map(item => item[0]),
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    series: [{
      name: '设备数量',
      type: 'bar',
      data: regionData.map(item => item[1]),
      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}台'
      }
    }]
  }

  regionChart.setOption(regionOption)
  chartLoading.value.region = false
}

// 更新网关图表
function updateGatewayChart(devices = null) {
  if (!gatewayChart) return

  const dataSource = devices || cachedDevicesData.value

  // 统计网关数据
  const gatewayStats = {}
  dataSource.forEach(device => {
    const gatewayName = device.gateway_name || '未知网关'
    if (!gatewayStats[gatewayName]) {
      gatewayStats[gatewayName] = {
        total: 0,
        online: 0
      }
    }
    gatewayStats[gatewayName].total++
    if (device.devices_enabled === 1) { // 只看devices_enabled字段
      gatewayStats[gatewayName].online++
    }
  })

  const gatewayData = Object.entries(gatewayStats)
      .sort((a, b) => b[1].total - a[1].total)
      .slice(0, 10)

  let seriesData, yAxisName
  if (gatewayChartType.value === 'count') {
    seriesData = gatewayData.map(item => item[1].total)
    yAxisName = '设备数量'
  } else {
    seriesData = gatewayData.map(item =>
        item[1].total > 0 ? Math.round(item[1].online / item[1].total * 100) : 0
    )
    yAxisName = '在线率(%)'
  }

  const gatewayOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const dataIndex = params[0].dataIndex
        const gatewayName = gatewayData[dataIndex][0]
        const stats = gatewayData[dataIndex][1]
        if (gatewayChartType.value === 'count') {
          return `${gatewayName}<br/>设备总数: ${stats.total}台<br/>在线设备: ${stats.online}台`
        } else {
          return `${gatewayName}<br/>在线率: ${params[0].value}%<br/>在线设备: ${stats.online}/${stats.total}台`
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: gatewayData.map(item => item[0]),
      axisLabel: {
        interval: 0,
        rotate: 45,
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      name: yAxisName
    },
    series: [{
      name: yAxisName,
      type: 'bar',
      data: seriesData,
      itemStyle: {
        color: gatewayChartType.value === 'count' ?
            new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 1, color: '#188df0' }
            ]) :
            new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#51cf66' },
              { offset: 1, color: '#40c057' }
            ])
      },
      label: {
        show: true,
        position: 'top',
        formatter: gatewayChartType.value === 'count' ? '{c}台' : '{c}%'
      }
    }]
  }

  gatewayChart.setOption(gatewayOption)
  chartLoading.value.gateway = false
}

// 刷新统计数据
function refreshStatisticsData() {
  dataCache.value.statistics = null
  dataCache.value.lastUpdateTime = null
  loadStatisticsData()
}

// 清理统计图表
function clearStatCharts() {
  if (deviceTypeChart) {
    deviceTypeChart.dispose()
    deviceTypeChart = null
  }
  if (deviceStatusChart) {
    deviceStatusChart.dispose()
    deviceStatusChart = null
  }
  if (gatewayChart) {
    gatewayChart.dispose()
    gatewayChart = null
  }
  if (regionChart) {
    regionChart.dispose()
    regionChart = null
  }
}

// 图表大小调整
function resizeCharts() {
  deviceTypeChart && deviceTypeChart.resize()
  deviceStatusChart && deviceStatusChart.resize()
  gatewayChart && gatewayChart.resize()
  regionChart && regionChart.resize()
  lineChart && lineChart.resize()
  pieChart && pieChart.resize()
}

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

// 查看历史数据
const historyVisible = ref(false)
const historyLoading = ref(false)
const historyList = ref([])
const historyTotal = ref(0)
const historyQuery = reactive({
  currentPage: 1,
  pageSize: 20,
  dev_udid: '',
  startTime: '',
  endTime: ''
})

// 获取当前月初到当前日期的默认时间范围
function getDefaultTimeRange() {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth()

  const startTime = new Date(year, month, 1) // 当前月初
  const endTime = now // 当前日期

  // 设置结束时间为当天的 23:59:59
  endTime.setHours(23, 59, 59, 999)

  return {
    startTime: formatDateTime(startTime, true), // true 表示开始时间设为 00:00:00
    endTime: formatDateTime(endTime, false)     // false 表示结束时间保持 23:59:59
  }
}

// 格式化日期时间
function formatDateTime(date, isStartTime = false) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  if (isStartTime) {
    return `${year}-${month}-${day} 00:00:00`
  } else {
    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}`
  }
}

// 查询历史记录
async function getHistoryData() {
  historyLoading.value = true
  try {
    const params = {
      currentPage: historyQuery.currentPage,
      pageSize: historyQuery.pageSize,
      dev_udid: historyQuery.dev_udid,
      start_time: historyQuery.startTime,
      end_time: historyQuery.endTime
    }

    const response = await axios.get(`${__LOCAL_API__}/energy/getHisData`, {
      params: params
    })

    if (response.data.code === 200) {
      historyList.value = response.data.data
      historyTotal.value = response.data.count
    } else {
      proxy.$modal.msgError(response.data.message || '获取历史记录失败')
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    proxy.$modal.msgError('获取历史记录失败')
  } finally {
    historyLoading.value = false
  }
}

// 处理历史记录查询
function handleHistoryQuery(row) {
  currentDevice.value = { ...row }

  // 设置默认时间范围
  const timeRange = getDefaultTimeRange()
  historyQuery.dev_udid = row.devices_udid
  historyQuery.startTime = timeRange.startTime
  historyQuery.endTime = timeRange.endTime
  historyQuery.currentPage = 1

  historyVisible.value = true

  // 查询历史数据
  getHistoryData()
}

// 重置历史记录查询
function resetHistoryQuery() {
  const timeRange = getDefaultTimeRange()
  Object.assign(historyQuery, {
    currentPage: 1,
    pageSize: 20,
    startTime: timeRange.startTime,
    endTime: timeRange.endTime
  })
  getHistoryData()
}

// 防抖函数
function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 设备类型标签类型
const getDeviceTypeTag = (typeName) => {
  if (!typeName) return 'info'
  if (typeName.includes('电表')) return ''
  if (typeName.includes('水表')) return ''
  if (typeName.includes('气表')) return ''
  return 'info'
}

// 设备类型颜色
const getDeviceTypeColor = (typeName) => {
  if (!typeName) return '#909399'

  // 电表类型 - 红色系
  if (typeName.includes('电表') || typeName.includes('bacnet')) {
    if (typeName.includes('三项')) return '#ff4757' // 深红色
    if (typeName.includes('单项')) return '#ff6b9a' // 浅红色
    return '#ff5722' // 默认红色
  }

  // 水表类型 - 蓝色系
  if (typeName.includes('水表') || typeName.includes('LXSY')) {
    return '#2196f3' // 蓝色
  }

  // 气表类型 - 绿色系
  if (typeName.includes('气表')) {
    return '#4caf50' // 绿色
  }

  // 其他类型 - 灰色
  return '#909399'
}

// 获取设备类型图标
const getDeviceTypeIcon = (typeName) => {
  if (!typeName) return '📱'

  if (typeName.includes('电表') || typeName.includes('bacnet')) {
    return '⚡'
  }

  if (typeName.includes('水表') || typeName.includes('LXSY')) {
    return '💧'
  }

  if (typeName.includes('气表')) {
    return '🔥'
  }

  return '📱'
}

// 防抖的图表大小调整
const debouncedResize = debounce(resizeCharts, 300)

// 清理所有图表
onBeforeUnmount(() => {
  clearEnergyCharts()
  clearStatCharts()
  window.removeEventListener('resize', debouncedResize)
})

// 初始化
onMounted(() => {
  // 获取设备类型列表
  getDeviceTypeList()
  // 先获取网关列表
  getGatewayListFromAPI()
  // 然后获取设备列表
  getEnergyList()
  // 添加窗口大小变化监听
  window.addEventListener('resize', debouncedResize)
})
</script>

<style scoped>
/* 保持原有样式不变 */
.app-container {
  padding: 20px;
}

.text-gray-500 {
  color: #6b7280;
}

.text-xs {
  font-size: 0.75rem;
}

.energy-data {
  display: flex;
  flex-direction: column;
  gap: 4px;
  background: #f8f9fa;
  padding: 8px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  min-height: 40px;
  justify-content: center;
}

.energy-data span {
  display: inline-block;
  margin: 2px 4px 2px 0;
  padding: 4px 8px;
  background: #fff;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  font-size: 11px;
  color: #495057;
  white-space: nowrap;
}

/* 统计卡片样式 */
.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;
  height: 140px;
}

.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;
  font-weight: 500;
}

.stat-card-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 4px;
  line-height: 1;
  transition: all 0.3s ease;
}

.stat-card:hover .stat-card-value {
  transform: scale(1.05);
}

.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: #67c23a;
  font-weight: bold;
}

.trend-warning {
  color: #e6a23c;
  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);
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.chart-card :deep(.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 :deep(.el-radio-button__inner) {
  padding: 6px 16px;
  border: none;
  background: transparent;
  font-size: 12px;
}

.chart-header :deep(.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;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 抽屉样式优化 */
:deep(.el-drawer) {
  border-radius: 12px 0 0 12px;
}

:deep(.el-drawer__header) {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-drawer__title) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

:deep(.el-drawer__body) {
  padding: 20px;
}

/* 描述列表样式 */
:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #333;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__body) {
  background: #fff;
}

:deep(.el-descriptions__table) {
  border-radius: 8px;
  overflow: hidden;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  font-size: 12px;
}

:deep(.el-tag.el-tag--success) {
  background-color: #f0f9ff;
  border-color: #67c23a;
  color: #67c23a;
}

:deep(.el-tag.el-tag--danger) {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

:deep(.el-tag.el-tag--warning) {
  background-color: #fdf6ec;
  border-color: #e6a23c;
  color: #e6a23c;
}

:deep(.el-tag.el-tag--primary) {
  background-color: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}

/* 按钮样式 */
:deep(.el-button--small) {
  padding: 5px 11px;
  font-size: 12px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #3a8ee6 0%, #337ecc 100%);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

:deep(.el-table .el-button + .el-button) {
  margin-left: 8px;
}

/* 分页样式 */
:deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px 0;
  margin-top: 20px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 6px;
  margin: 0 2px;
}

:deep(.el-pagination .el-pager li.active) {
  background: linear-gradient(135deg, #409eff 0%, #3a8ee6 100%);
  color: #fff;
}

/* 搜索表单样式 */
:deep(.el-form--inline .el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

/* 加载状态 */
.el-loading-mask {
  border-radius: 8px;
}

/* 动画效果 */
@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;
}

/* Tab样式优化 */
:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__nav-wrap::after) {
  background-color: #e4e7ed;
}

:deep(.el-tabs__active-bar) {
  background-color: #409eff;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

/* 图表容器优化 */
#deviceTypeChart,
#deviceStatusChart,
#gatewayChart,
#regionChart,
#energyChart,
#energyPieChart {
  min-height: 300px;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 表格固定列阴影 */
:deep(.el-table__fixed-right) {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
}

/* 抽屉内表单样式 */
:deep(.el-drawer .el-form) {
  padding: 0 20px;
}

:deep(.el-drawer .el-form-item__label) {
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stat-card {
    height: 120px;
  }

  .stat-card-value {
    font-size: 28px;
  }
}

@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  .stat-card {
    margin-bottom: 16px;
    height: 100px;
  }

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

  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  :deep(.el-form--inline .el-form-item) {
    display: block;
    margin-right: 0;
    margin-bottom: 16px;
  }

  :deep(.el-table) {
    font-size: 12px;
  }

  :deep(.el-drawer) {
    width: 90% !important;
  }

  :deep(.el-table .el-table__cell) {
    padding: 8px 4px;
    align:center;
  }

  :deep(.el-table .el-button--small) {
    padding: 3px 8px;
    font-size: 11px;
  }
}

@media (max-width: 480px) {
  .stat-cards :deep(.el-col) {
    width: 100%;
    margin-bottom: 10px;
  }

  .chart-card {
    margin-bottom: 10px;
  }

  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}

/* 图表响应式 */
@media (max-width: 1200px) {
  #deviceTypeChart,
  #deviceStatusChart,
  #gatewayChart,
  #regionChart {
    height: 300px !important;
  }
}

@media (max-width: 768px) {
  #deviceTypeChart,
  #deviceStatusChart,
  #gatewayChart,
  #regionChart {
    height: 250px !important;
  }

  #energyChart {
    height: 300px !important;
  }

  #energyPieChart {
    height: 250px !important;
  }
}
/* 设备类型单元格样式 */
.device-type-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.device-icon {
  font-size: 16px;
  width: 20px;
  text-align: center;
}

.device-type-tag {
  border: none !important;
  font-weight: 500;
  font-size: 11px;
  padding: 4px 8px;
  border-radius: 6px;
}

/* 自定义设备类型标签样式 */
.device-type-tag.el-tag {
  color: #fff !important;
}

/* 电表类型样式 */
.device-type-tag[style*="#ff4757"] {
  background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%) !important;
  box-shadow: 0 2px 8px rgba(255, 71, 87, 0.3);
}

.device-type-tag[style*="#ff6b7a"] {
  background: linear-gradient(135deg, #ff6b7a 0%, #ff5722 100%) !important;
  box-shadow: 0 2px 8px rgba(255, 107, 122, 0.3);
}

.device-type-tag[style*="#ff5722"] {
  background: linear-gradient(135deg, #ff5722 0%, #e64a19 100%) !important;
  box-shadow: 0 2px 8px rgba(255, 87, 34, 0.3);
}

/* 水表类型样式 */
.device-type-tag[style*="#2196f3"] {
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%) !important;
  box-shadow: 0 2px 8px rgba(33, 150, 243, 0.3);
}

/* 气表类型样式 */
.device-type-tag[style*="#4caf50"] {
  background: linear-gradient(135deg, #4caf50 0%, #388e3c 100%) !important;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

/* 默认类型样式 */
.device-type-tag[style*="#909399"] {
  background: linear-gradient(135deg, #909399 0%, #606266 100%) !important;
  box-shadow: 0 2px 8px rgba(144, 147, 153, 0.3);
}

/* 悬停效果 */
.device-type-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  transition: all 0.3s ease;
}

.history-container {
  padding: 20px;
}

.history-container .el-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.history-container .el-table {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table .el-table__cell) {
  text-align:center;
}
</style>
