<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>
              <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>
              <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">
          <el-col :span="6">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>今日总能耗</span>
              </div>
              <div class="text item">
                <div class="energy-stat">
                  <div class="energy-item">
                    <i class="el-icon-lightning" style="color: #f56c6c;"></i>
                    <span>电: {{ statisticsData.todayElectricity }} kWh</span>
                  </div>
                  <div class="energy-item">
                    <i class="el-icon-water" style="color: #409eff;"></i>
                    <span>水: {{ statisticsData.todayWater }} m³</span>
                  </div>
                  <div class="energy-item">
                    <i class="el-icon-fire" style="color: #67c23a;"></i>
                    <span>气: {{ statisticsData.todayGas }} m³</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>本月总能耗</span>
              </div>
              <div class="text item">
                <div class="energy-stat">
                  <div class="energy-item">
                    <i class="el-icon-lightning" style="color: #f56c6c;"></i>
                    <span>电: {{ statisticsData.monthElectricity }} kWh</span>
                  </div>
                  <div class="energy-item">
                    <i class="el-icon-water" style="color: #409eff;"></i>
                    <span>水: {{ statisticsData.monthWater }} m³</span>
                  </div>
                  <div class="energy-item">
                    <i class="el-icon-fire" style="color: #67c23a;"></i>
                    <span>气: {{ statisticsData.monthGas }} m³</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>在线设备数</span>
              </div>
              <div class="text item">
                <div class="device-stat">
                  <div class="stat-number">{{ statisticsData.onlineDevices }}</div>
                  <div class="stat-text">/ {{ statisticsData.totalDevices }} 台</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>告警设备数</span>
              </div>
              <div class="text item">
                <div class="device-stat">
                  <div class="stat-number" style="color: #f56c6c;">{{ statisticsData.alarmDevices }}</div>
                  <div class="stat-text">台设备异常</div>
                </div>
              </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%"
    >
      <div id="energyChart" style="width: 100%; height: 400px;"></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 { ref, reactive, watch, onMounted } 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()
  }
})

// 能耗监测查询相关
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: 0,
  todayWater: 0,
  todayGas: 0,
  monthElectricity: 0,
  monthWater: 0,
  monthGas: 0,
  onlineDevices: 0,
  totalDevices: 0,
  alarmDevices: 0
})

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

// 图表相关
const chartVisible = ref(false)

// 控制相关
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
  })
}

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

// 查看能耗曲线
function handleEnergyChart(row) {
  currentDevice.value = row
  chartVisible.value = true
  // 这里可以集成图表库如ECharts来显示能耗曲线
}

// 设备控制
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()
  })
}

// 初始化
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;
}
</style>