<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧树形选择器 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="areaName"
            placeholder="请输入区域名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
            @input="filterTree"
          />
        </div>
        <div class="head-container tree-container">
          <el-tree
            :data="areaOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="tree-node"
                   :class="{ 'device-node': data.type === 'device', 'area-node': data.type === 'area' }"
              >
                <i v-if="data.type === 'area'" class="el-icon-folder node-icon area-icon"></i>
                <i v-if="data.type === 'device'" class="el-icon-monitor node-icon device-icon"></i>
                <span class="node-label">{{ data.label }}</span>
              </div>
            </template>
          </el-tree>
        </div>
      </el-col>

      <!-- 右侧内容区域 -->
      <el-col :span="20" :xs="24">
        <!-- Tab切换 -->
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="电表读数" name="first"></el-tab-pane>
          <el-tab-pane label="水表读数" name="second"></el-tab-pane>
        </el-tabs>

        <!-- 查询表单 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="80px"
        >
          <el-form-item label="抄表周期">
            <el-date-picker
              v-model="daterangeRecordTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              @change="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>

        <!-- 用电统计卡片 -->
        <div v-if="activeTab === 'first' && numElecMeterHData">
          <!-- 汇总统计区域 -->
          <div class="summary-container">
            <!-- 总量统计卡片 -->
            <div class="summary-row">
              <el-card class="summary-inline-card">
                <div class="inline-card-content">
                  <div class="inline-card-left">
                    <i class="el-icon-lightning inline-icon elec-icon"></i>
                    <span class="inline-label">总用电量</span>
                  </div>
                  <div class="inline-card-right">
                    <span class="inline-value">{{ formatNumber(numElecMeterHData && numElecMeterHData.total ? numElecMeterHData.total.quantity : 0) }}</span>
                    <span class="inline-unit">kWh</span>
                  </div>
                </div>
              </el-card>

              <el-card class="summary-inline-card">
                <div class="inline-card-content">
                  <div class="inline-card-left">
                    <i class="el-icon-money inline-icon cost-icon"></i>
                    <span class="inline-label">总电费</span>
                  </div>
                  <div class="inline-card-right">
                    <span class="inline-value">{{ formatNumber(numElecMeterHData && numElecMeterHData.total ? numElecMeterHData.total.useCost : 0, 2) }}</span>
                    <span class="inline-unit">元</span>
                  </div>
                </div>
              </el-card>
            </div>

            <!-- 动态峰谷电统计卡片 - 仅在有数据时显示 -->
            <div v-if="supportedMeterTypes && supportedMeterTypes.length > 0" class="peak-valley-row">
              <el-card
                v-for="meterType in supportedMeterTypes"
                :key="meterType.value"
                class="peak-inline-card"
              >
                <div class="peak-inline-content">
                  <div class="peak-inline-header">
                    <span class="peak-type-badge" :class="meterType.tagClass">{{ meterType.tagName }}</span>
                  </div>
                  <div class="peak-inline-body">
                    <div class="peak-inline-info">
                      <span class="peak-label">电量</span>
                      <span class="peak-value">{{ formatNumber(getMeterTypeData(meterType.value, 'quantity')) }}</span>
                      <span class="peak-unit">kWh</span>
                    </div>

                    <div class="peak-percentage">
                      占比 {{
                        numElecMeterHData && numElecMeterHData.total && numElecMeterHData.total.quantity > 0 ? calculatePercentage(getMeterTypeData(meterType.value, 'quantity'), numElecMeterHData.total.quantity) : '0.0'
                      }}%
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>

        <!-- 用水统计卡片 -->
        <div v-if="activeTab === 'second'">
          <!-- 汇总统计区域 -->
          <div class="summary-container">
            <div class="summary-row">
              <el-card class="summary-inline-card">
                <div class="inline-card-content">
                  <div class="inline-card-left">
                    <i class="el-icon-set-up inline-icon water-icon"></i>
                    <span class="inline-label">总用水量</span>
                  </div>
                  <div class="inline-card-right">
                    <span class="inline-value">{{ formatNumber(getWaterTotal('quantity')) }}</span>
                    <span class="inline-unit">m³</span>
                  </div>
                </div>
              </el-card>

              <el-card class="summary-inline-card">
                <div class="inline-card-content">
                  <div class="inline-card-left">
                    <i class="el-icon-money inline-icon cost-icon"></i>
                    <span class="inline-label">总水费</span>
                  </div>
                  <div class="inline-card-right">
                    <span class="inline-value">{{ formatNumber(getWaterTotal('useCost'), 2) }}</span>
                    <span class="inline-unit">元</span>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>

        <!-- 电表数据表格 -->
        <el-table v-if="activeTab === 'first'" v-loading="loading" :data="elecMeterHList" style="margin-top: 20px">
          <el-table-column label="表计名称" align="left" prop="deviceName" width="250px"/>
          <el-table-column label="表计编号" align="left" prop="deviceCode"/>
          <el-table-column label="抄表时间" align="center" prop="recordTime" width="180">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.recordTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计量时段" align="center" prop="meterType">
            <template slot-scope="scope">
              <el-tag :type="getMeterTypeTagType(scope.row.meterType)" size="small">
                {{ getElecMeterType(scope.row.meterType) }}
              </el-tag>
              <span style="margin-left: 5px; color: #909399;">{{
                  formatNumber(scope.row.meterUnitPrice, 2)
                }} 元/kWh</span>
            </template>
          </el-table-column>
          <el-table-column label="用电量(kWh)" align="center" prop="elecQuantity">
            <template slot-scope="scope">
              <span>{{ formatNumber(scope.row.elecQuantity) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="小时电费(元)" align="center" prop="useElecCost">
            <template slot-scope="scope">
              <span>{{ formatNumber(scope.row.useElecCost, 2) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 水表数据表格 -->
        <el-table v-if="activeTab === 'second'" v-loading="loading" :data="waterMeterHList" style="margin-top: 20px">
          <el-table-column label="表计名称" align="left" prop="deviceName" width="250"/>
          <el-table-column label="表计编号" align="left" prop="deviceCode"/>
          <el-table-column label="抄表时间" align="center" prop="recordTime" width="180">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.recordTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用水量(m³)" align="center" prop="waterQuantity">
            <template slot-scope="scope">
              <span>{{ formatNumber(scope.row.waterQuantity) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="小时水费(元)" align="center" prop="useWaterCost">
            <template slot-scope="scope">
              <span>{{ formatNumber(scope.row.useWaterCost, 2) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getDeviceTree } from '@/api/device/meterDevice'
import { getElechourTypes, getElecMdevHourList, getElecMdevHourSummary, getWaterMdevHourList, getWaterMdevHourSummary } from '@/api/device/energyConsumption'

export default {
  name: 'MeterReading',
  data() {
    return {
      // 存储用电统计数据
      numElecMeterHData: null,
      // 存储用水统计数据
      numWaterMeterHData: null,
      // 当前激活的标签页
      activeTab: 'first',
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用电计量-小时表格数据
      elecMeterHList: [],
      // 用水计量-小时表格数据
      waterMeterHList: [],
      // 小时电费时间范围
      daterangeRecordTime: [],
      // 支持的电量类型
      supportedMeterTypes: [],
      // 电量类型映射
      meterTypeMap: {
        '-2': {
          name: '深谷电量',
          tagName: '深谷',
          tagClass: 'deep-valley-tag',
          field: 'deepValleyElec'
        },
        '-1': {
          name: '谷段电量',
          tagName: '谷段',
          tagClass: 'valley-tag',
          field: 'lowElec'
        },
        '0': {
          name: '平段电量',
          tagName: '平段',
          tagClass: 'normal-tag',
          field: 'normalElec'
        },
        '1': {
          name: '峰段电量',
          tagName: '峰段',
          tagClass: 'high-peak-tag',
          field: 'highElec'
        },
        '2': {
          name: '尖峰电量',
          tagName: '尖峰',
          tagClass: 'peak-tag',
          field: 'peakElec'
        }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaCode: null,
        deviceCode: null,
        recordTime: null,
        startRecTime: null,
        endRecTime: null,
        meterCls: 45,
        orderFlag: 'desc'
      },
      // 区域名称
      areaName: undefined,
      areaOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 日期选择器配置
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  created() {
    this.initDefaultDateRange()
    this.getAreaTreeSelect().then(() => {
      const firstValidNode = this.findFirstValidNode(this.areaOptions)
      if (firstValidNode) {
        this.queryParams.deviceCode = firstValidNode.id
        this.handleQuery()
      } else {
        this.getList()
      }
    })
  },
  methods: {
    // 初始化默认查询时间范围：当月1号到今天
    initDefaultDateRange() {
      const today = new Date()
      const currentYear = today.getFullYear()
      const currentMonth = today.getMonth()
      const startDate = new Date(currentYear, currentMonth, 1)
      const endDate = new Date(today)

      const formatDate = (date) => {
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        return `${year}-${month}-${day}`
      }

      this.daterangeRecordTime = [formatDate(startDate), formatDate(endDate)]
    },

    // 加载支持的电量类型
    async loadSupportedMeterTypes() {
      if (this.activeTab !== 'first' || !this.queryParams.deviceCode) {
        this.supportedMeterTypes = []
        return
      }

      try {
        const query = {
          objCode: this.queryParams.deviceCode,
          objType: 2, // 设备类型
          startRecTime: this.queryParams.startRecTime,
          endRecTime: this.queryParams.endRecTime
        }

        // 尝试获取支持的电量类型
        const response = await getElechourTypes(query)

        if (response.data && Array.isArray(response.data)) {
          const types = response.data
            .filter(type => type !== null && type !== undefined && this.meterTypeMap[type])
            .sort((a, b) => Number(b) - Number(a))
            .map(type => ({
              value: type,
              ...this.meterTypeMap[type]
            }))

          this.supportedMeterTypes = types.length > 0 ? types : this.getDefaultMeterTypes()
        } else {
          this.supportedMeterTypes = this.getDefaultMeterTypes()
        }
      } catch (error) {
        console.error('加载电量类型失败:', error)
        this.supportedMeterTypes = this.getDefaultMeterTypes()
      }
    },

    // 获取默认的电量类型
    getDefaultMeterTypes() {
      // 根据已有数据判断支持的类型
      const availableTypes = []
      if (this.numElecMeterHData) {
        // 尖峰电量
        if (this.numElecMeterHData.peakElec && this.numElecMeterHData.peakElec.quantity > 0) {
          availableTypes.push('2')
        }
        // 峰段电量
        if (this.numElecMeterHData.highElec && this.numElecMeterHData.highElec.quantity > 0) {
          availableTypes.push('1')
        }
        // 平段电量
        if (this.numElecMeterHData.normalElec && this.numElecMeterHData.normalElec.quantity > 0) {
          availableTypes.push('0')
        }
        // 谷段电量
        if (this.numElecMeterHData.lowElec && this.numElecMeterHData.lowElec.quantity > 0) {
          availableTypes.push('-1')
        }
        // 深谷电量
        if (this.numElecMeterHData.deepValleyElec && this.numElecMeterHData.deepValleyElec.quantity > 0) {
          availableTypes.push('-2')
        }
      }

      // 如果没有任何数据，返回空数组
      return availableTypes.length > 0
        ? availableTypes.map(type => ({ value: type, ...this.meterTypeMap[type] }))
        : []
    },

    // 获取指定类型的电量数据
    getMeterTypeData(meterType, field) {
      if (!this.numElecMeterHData) return 0
      const typeMapping = {
        '-2': 'deepValleyElec',
        '-1': 'lowElec',
        '0': 'normalElec',
        '1': 'highElec',
        '2': 'peakElec'
      }
      const typeName = typeMapping[meterType]
      return typeName && this.numElecMeterHData[typeName]
        ? (this.numElecMeterHData[typeName][field] || 0)
        : 0
    },

    // Tab切换处理
    handleTabChange() {
      // 清空之前的数据，防止数据污染
      this.elecMeterHList = []
      this.waterMeterHList = []
      this.numElecMeterHData = null
      this.numWaterMeterHData = null
      this.supportedMeterTypes = []
      this.total = 0

      if (this.activeTab === 'first') {
        this.queryParams.meterCls = '45'
      } else if (this.activeTab === 'second') {
        this.queryParams.meterCls = '70'
      }

      this.getAreaTreeSelect().then(() => {
        const firstValidNode = this.findFirstValidNode(this.areaOptions)
        if (firstValidNode) {
          this.queryParams.deviceCode = firstValidNode.id
          this.handleQuery()
        } else {
          this.getList()
        }
      })
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // 过滤树节点
    filterTree() {
      this.$refs.tree.filter(this.areaName)
    },

    // 节点单击事件
    handleNodeClick(data) {
      // 仅处理设备节点
      if (data.type === 'device') {
        this.queryParams.deviceCode = data.id
        this.handleQuery()
      }
    },

    // 查找第一个设备节点
    findFirstValidNode(nodes) {
      for (const node of nodes) {
        if (node.type === 'device') {
          return node
        }
        if (node.children && node.children.length > 0) {
          const foundNode = this.findFirstValidNode(node.children)
          if (foundNode) return foundNode
        }
      }
      return null
    },

    // 树结构加载
    async getAreaTreeSelect() {
      await getDeviceTree(0, this.queryParams.meterCls, 0).then(response => {
        this.areaOptions = response.data
      })
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },

    // 获取列表数据
    getList() {
      if (this.activeTab === 'first') {
        this.getElecList()
      } else {
        this.getWaterList()
      }
    },

    // 查询用电计量-小时列表
    getElecList() {
      this.loading = true
      getElecMdevHourList(this.queryParams).then(response => {
        this.elecMeterHList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 查询用水计量-小时列表
    getWaterList() {
      this.loading = true
      listWaterMeterH(this.queryParams).then(response => {
        this.waterMeterHList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 搜索按钮操作
    async handleQuery() {
      // 处理日期范围
      if (this.daterangeRecordTime && this.daterangeRecordTime.length === 2) {
        this.queryParams.startRecTime = this.daterangeRecordTime[0] + ' 00:00:00'
        this.queryParams.endRecTime = this.daterangeRecordTime[1] + ' 23:59:59'
      } else {
        this.queryParams.startRecTime = null
        this.queryParams.endRecTime = null
      }

      if (this.activeTab === 'first') {
        this.queryParams.meterCls = '45'
        await this.loadSupportedMeterTypes()
        this.getElecList()
        this.getElecMdevHourSummary()
      } else if (this.activeTab === 'second') {
        this.queryParams.meterCls = '70'
        this.getWaterList()
        this.getNumWaterMeterH()
      }
    },

    // 获取用电统计数据
    async getElecMdevHourSummary() {
      const query = {
        deviceCode: this.queryParams.deviceCode,
        startRecTime: this.queryParams.startRecTime,
        endRecTime: this.queryParams.endRecTime
      }
      try {
        const response = await getElecMdevHourSummary(query)
        // 处理空数据情况
        if (!response.data || (typeof response.data === 'object' && Object.keys(response.data).length === 0)) {
          this.numElecMeterHData = {
            total: {
              quantity: 0,
              useCost: 0
            },
            deepValleyElec: { quantity: 0, useCost: 0 },
            lowElec: { quantity: 0, useCost: 0 },
            normalElec: { quantity: 0, useCost: 0 },
            highElec: { quantity: 0, useCost: 0 },
            peakElec: { quantity: 0, useCost: 0 }
          }
        } else {
          const flatData = response.data

          // 将扁平数据转换为原来的嵌套结构
          this.numElecMeterHData = {
            total: {
              areaCode: flatData.areaCode,
              objType: flatData.objType,
              objCode: flatData.objCode,
              objName: flatData.objName,
              quantity: flatData.totalElecQuantity || 0,
              useCost: flatData.totalElecCost || 0
            },
            deepValleyElec: {
              areaCode: flatData.areaCode,
              objType: flatData.objType,
              objCode: '-2',
              objName: 'deepValleyElec',
              quantity: flatData.deepValleyQuantity || 0,
              useCost: 0 // 深谷费用暂时无法直接从新接口获取，设置为0
            },
            lowElec: {
              areaCode: flatData.areaCode,
              objType: flatData.objType,
              objCode: '-1',
              objName: 'lowElec',
              quantity: flatData.valleyQuantity || 0,
              useCost: 0 // 谷段费用暂时无法直接从新接口获取，设置为0
            },
            normalElec: {
              areaCode: flatData.areaCode,
              objType: flatData.objType,
              objCode: '0',
              objName: 'normalElec',
              quantity: flatData.normalQuantity || 0,
              useCost: 0 // 平段费用暂时无法直接从新接口获取，设置为0
            },
            highElec: {
              areaCode: flatData.areaCode,
              objType: flatData.objType,
              objCode: '1',
              objName: 'highElec',
              quantity: flatData.peakQuantity || 0,
              useCost: 0 // 峰段费用暂时无法直接从新接口获取，设置为0
            },
            peakElec: {
              areaCode: flatData.areaCode,
              objType: flatData.objType,
              objCode: '2',
              objName: 'peakElec',
              quantity: flatData.sharpPeakQuantity || 0,
              useCost: 0 // 尖峰费用暂时无法直接从新接口获取，设置为0
            }
          }
        }

        // 重新加载支持的电量类型
        await this.loadSupportedMeterTypes()
      } catch (error) {
        // 出错时设置默认空数据结构
        this.numElecMeterHData = {
          total: { quantity: 0, useCost: 0 },
          deepValleyElec: { quantity: 0, useCost: 0 },
          lowElec: { quantity: 0, useCost: 0 },
          normalElec: { quantity: 0, useCost: 0 },
          highElec: { quantity: 0, useCost: 0 },
          peakElec: { quantity: 0, useCost: 0 }
        }
        this.$message.error('获取用电统计数据失败')
      }
    },

    // 获取用水统计数据
    async getNumWaterMeterH() {
      const query = {
        deviceCode: this.queryParams.deviceCode,
        startRecTime: this.queryParams.startRecTime,
        endRecTime: this.queryParams.endRecTime
      }
      try {
        const response = await getWaterMdevHourSummary(query)
        // 处理空数据情况
        if (!response.data || (typeof response.data === 'object' && Object.keys(response.data).length === 0)) {
          this.numWaterMeterHData = {
            quantity: 0,
            useCost: 0
          }
        } else {
          // 修改字段映射：使用新的字段名
          this.numWaterMeterHData = {
            quantity: response.data.totalWaterQuantity || 0,
            useCost: response.data.totalWaterCost || 0
          }
        }
      } catch (error) {
        // 出错时设置默认空数据结构
        this.numWaterMeterHData = {
          quantity: 0,
          useCost: 0
        }
        this.$message.error('获取用水统计数据失败')
      }
    },

    // 重置按钮操作
    resetQuery() {
      this.daterangeRecordTime = []
      this.resetForm('queryForm')
      this.initDefaultDateRange()
      this.handleQuery()
    },

    // 导出按钮操作
    handleExport() {
      const filename = this.activeTab === 'first'
        ? `电表读数_${new Date().getTime()}.xlsx`
        : `水表读数_${new Date().getTime()}.xlsx`

      const url = this.activeTab === 'first'
        ? 'ems/consumption/mdev/elec/hour/export'
        : 'ems/consumption/mdev/water/hour/export'

      this.download(url, { ...this.queryParams }, filename)
    },

    // 获取电表类型名称
    getElecMeterType(meterType) {
      const meterTypeMap = {
        '-2': '深谷',
        '-1': '谷段',
        '0': '平段',
        '1': '峰段',
        '2': '尖峰'
      }
      return meterTypeMap[meterType] || '未知'
    },

    // 获取电表类型标签颜色
    getMeterTypeTagType(meterType) {
      const typeMap = {
        '-2': 'primary',
        '-1': 'success',
        '0': 'info',
        '1': 'warning',
        '2': 'danger'
      }
      return typeMap[meterType] || 'info'
    },

    // 计算百分比
    calculatePercentage(value, total) {
      if (!value || !total || total === 0) {
        return '0.0'
      }
      const percentage = (value / total) * 100
      return percentage.toFixed(1)
    },

    // 获取用水总计数据
    getWaterTotal(field) {
      if (this.numWaterMeterHData && this.numWaterMeterHData[field] !== undefined) {
        return this.numWaterMeterHData[field]
      }
      // 如果没有统计数据，尝试从列表数据计算
      if (this.waterMeterHList && this.waterMeterHList.length > 0) {
        if (field === 'quantity') {
          return this.waterMeterHList.reduce((sum, item) => sum + (item.waterQuantity || 0), 0)
        } else if (field === 'useCost') {
          return this.waterMeterHList.reduce((sum, item) => sum + (item.useWaterCost || 0), 0)
        }
      }
      return 0
    },

    // 格式化数字
    formatNumber(num, decimals = 2) {
      if (num === null || num === undefined || isNaN(num)) {
        return '0.' + '0'.repeat(decimals)
      }
      return Number(num).toFixed(decimals)
    },

    // 查询用电计量-小时列表
    getElecList() {
      this.loading = true
      getElecMdevHourList(this.queryParams).then(response => {
        // 处理空数据情况
        this.elecMeterHList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取用电列表失败:', error)
        this.elecMeterHList = []
        this.total = 0
        this.loading = false
      })
    },

    // 查询用水计量-小时列表
    getWaterList() {
      this.loading = true
      getWaterMdevHourList(this.queryParams).then(response => {
        // 处理空数据情况
        this.waterMeterHList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        console.error('获取用水列表失败:', error)
        this.waterMeterHList = []
        this.total = 0
        this.loading = false
      })
    },

    // 树结构加载
    async getAreaTreeSelect() {
      try {
        await getDeviceTree(0, this.queryParams.meterCls, 0).then(response => {
          // 处理空数据情况
          this.areaOptions = response.data || []
        })
      } catch (error) {
        console.error('加载设备树失败:', error)
        this.areaOptions = []
      }
    }
  }
}
</script>

<style scoped>
/* 树容器样式 */
.tree-container {
  height: calc(100vh - 200px);
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 10px;
  background-color: #fafafa;
}

/* 树节点样式 */
.tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 2px 0;
  transition: all 0.3s;
}

.node-icon {
  margin-right: 8px;
  font-size: 16px;
  transition: color 0.3s;
}

.area-icon {
  color: #909399;
}

.device-icon {
  color: #409EFF;
}

.node-label {
  flex: 1;
  font-size: 14px;
}

/* 区域节点样式 - 不可点击 */
.area-node {
  cursor: not-allowed;
  opacity: 0.7;
}

.area-node:hover {
  background-color: transparent !important;
}

.area-node:hover .area-icon {
  color: #909399;
}

/* 设备节点样式 - 可点击 */
.device-node {
  cursor: pointer;
}

.device-node:hover {
  background-color: #f0f7ff;
  border-radius: 4px;
  padding-left: 4px;
}

.device-node:hover .device-icon {
  color: #2b7bff;
  transform: scale(1.1);
}

/* 高亮当前选中的节点 */
.el-tree-node.is-current > .el-tree-node__content .device-node {
  background-color: #e6f7ff;
  border-radius: 4px;
  padding-left: 4px;
}

.el-tree-node.is-current > .el-tree-node__content .device-icon {
  color: #1890ff;
}

/* 压缩卡片高度 */
.compact-card {
  min-height: auto !important;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.compact-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.compact-card .el-card__header {
  padding: 12px 15px !important;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(to right, #f7f8fa, #ffffff);
}

.compact-card .el-card__body {
  padding: 20px 15px !important;
}

/* 新的汇总统计容器 */
.summary-container {
  margin-bottom: 20px;
}

.summary-row {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

/* 横向紧凑卡片样式 */
.summary-inline-card {
  flex: 1;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.summary-inline-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.summary-inline-card .el-card__body {
  padding: 12px 20px !important;
}

.inline-card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.inline-card-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.inline-icon {
  font-size: 24px;
}

.elec-icon {
  color: #409EFF;
}

.water-icon {
  color: #67C23A;
}

.cost-icon {
  color: #E6A23C;
}

.inline-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.inline-card-right {
  display: flex;
  align-items: baseline;
  gap: 5px;
}

.inline-value {
  font-size: 24px;
  font-weight: bold;
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.inline-unit {
  font-size: 12px;
  color: #909399;
}

/* 峰谷电横向紧凑卡片 */
.peak-valley-row {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.peak-inline-card {
  flex: 1;
  min-width: 200px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
}

.peak-inline-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.peak-inline-card .el-card__body {
  padding: 10px 15px !important;
}

.peak-inline-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.peak-inline-header {
  flex-shrink: 0;
}

.peak-type-badge {
  display: inline-block;
  padding: 4px 10px;
  font-size: 12px;
  border-radius: 4px;
  color: white;
  font-weight: 500;
  min-width: 40px;
  text-align: center;
}

/* 峰谷电类型标签样式 */
.deep-valley-tag {
  background: linear-gradient(135deg, #409EFF 0%, #1976D2 100%);
}

.valley-tag {
  background: linear-gradient(135deg, #67C23A 0%, #4CAF50 100%);
}

.normal-tag {
  background: linear-gradient(135deg, #909399 0%, #606266 100%);
}

.high-peak-tag {
  background: linear-gradient(135deg, #E6A23C 0%, #FF9800 100%);
}

.peak-tag {
  background: linear-gradient(135deg, #F56C6C 0%, #f44336 100%);
}

.peak-inline-body {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 20px;
}

.peak-inline-info {
  display: flex;
  align-items: baseline;
  gap: 5px;
}

.peak-label {
  font-size: 12px;
  color: #909399;
}

.peak-value {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.peak-unit {
  font-size: 11px;
  color: #909399;
}

.peak-percentage {
  margin-left: auto;
  font-size: 12px;
  color: #909399;
  padding: 2px 8px;
  background-color: #f4f4f5;
  border-radius: 12px;
  white-space: nowrap;
}

/* 汇总卡片样式 - 已删除 */

/* 峰谷电卡片样式 - 已删除旧样式 */

/* 响应式布局 */
@media (max-width: 1680px) {
  .inline-value {
    font-size: 20px;
  }

  .peak-value {
    font-size: 14px;
  }
}

@media (max-width: 1366px) {
  .peak-valley-row .peak-inline-card {
    flex: 1 1 calc(50% - 6px);
  }

  .inline-value {
    font-size: 18px;
  }

  .peak-inline-body {
    gap: 15px;
  }
}

@media (max-width: 768px) {
  .summary-row {
    flex-direction: column;
  }

  .peak-valley-row .peak-inline-card {
    flex: 1 1 100%;
  }

  .peak-inline-body {
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .inline-card-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .peak-inline-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .peak-inline-body {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .peak-percentage {
    margin-left: 0;
    margin-top: 5px;
  }
}

/* 过渡动画 */
.el-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 加载动画优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.9);
}
</style>
