<template>
  <div class="electric-meter-container">
    <el-row :gutter="20">
      <!-- 左侧楼宇树 -->
      <el-col :span="4">
        <vab-card class="tree-card">
          <el-input v-model="filterText" placeholder="搜索楼宇/房间" prefix-icon="search-line" class="mb-10" />
          <el-tree
            ref="treeRef"
            class="filter-tree"
            :data="treeData"
            :props="defaultProps"
            default-expand-all
            :filter-node-method="filterNode"
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <vab-icon v-if="data.children" icon="building-2-line" />
                <vab-icon v-else icon="home-4-line" />
                <span class="ml-5">{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </vab-card>
      </el-col>

      <!-- 右侧内容区 -->
      <el-col :span="20">
        <!-- 统计面板 -->
        <el-row :gutter="20" class="mb-20">
          <el-col :span="6">
            <vab-card shadow="hover" class="stat-card">
              <div class="stat-icon bg-primary"><vab-icon icon="flashlight-line" style="font-size: 24px; color: #fff;" /></div>
              <div class="stat-info">
                <div class="stat-value">1,245.8</div>
                <div class="stat-label">今日总耗能 (kWh)</div>
              </div>
            </vab-card>
          </el-col>
          <el-col :span="6">
            <vab-card shadow="hover" class="stat-card">
              <div class="stat-icon bg-danger"><vab-icon icon="alarm-warning-line" style="font-size: 24px; color: #fff;" /></div>
              <div class="stat-info">
                <div class="stat-value">3</div>
                <div class="stat-label">异常设备数</div>
              </div>
            </vab-card>
          </el-col>
          <el-col :span="6">
            <vab-card shadow="hover" class="stat-card">
              <div class="stat-icon bg-warning"><vab-icon icon="money-cny-circle-line" style="font-size: 24px; color: #fff;" /></div>
              <div class="stat-info">
                <div class="stat-value">12</div>
                <div class="stat-label">低余额预警</div>
              </div>
            </vab-card>
          </el-col>
          <el-col :span="6">
            <vab-card shadow="hover" class="stat-card">
              <div class="stat-icon bg-success"><vab-icon icon="wifi-line" style="font-size: 24px; color: #fff;" /></div>
              <div class="stat-info">
                <div class="stat-value">99.8%</div>
                <div class="stat-label">设备在线率</div>
              </div>
            </vab-card>
          </el-col>
        </el-row>

        <vab-card>
          <vab-query-form>
            <vab-query-form-left-panel>
              <el-form :inline="true" :model="queryForm" @submit.prevent>
                <el-form-item label="设备状态">
                  <el-select v-model="queryForm.status" placeholder="全部" clearable style="width: 120px">
                    <el-option label="在线" value="online" />
                    <el-option label="离线" value="offline" />
                    <el-option label="故障" value="error" />
                  </el-select>
                </el-form-item>
                <el-form-item label="通断状态">
                  <el-select v-model="queryForm.switch" placeholder="全部" clearable style="width: 120px">
                    <el-option label="合闸" value="on" />
                    <el-option label="拉闸" value="off" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery"> <vab-icon icon="search-line" /> 查询</el-button>
                </el-form-item>
              </el-form>
            </vab-query-form-left-panel>
            <vab-query-form-right-panel>
              <el-button type="primary" @click="handleAdd"> <vab-icon icon="add-line" /> 设备注册</el-button>
              <el-button type="danger" @click="handleBatchOff"> <vab-icon icon="shut-down-line" /> 批量拉闸</el-button>
            </vab-query-form-right-panel>
          </vab-query-form>

          <el-table v-loading="loading" :data="tableData" border stripe height="calc(100vh - 400px)">
            <el-table-column prop="roomName" label="房间号" width="120" fixed />
            <el-table-column prop="deviceId" label="设备ID" width="150" show-overflow-tooltip />
            <el-table-column prop="status" label="通讯状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'online' ? 'success' : 'info'">
                  {{ row.status === 'online' ? '在线' : '离线' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="switchStatus" label="开关状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.switchStatus === 'on' ? 'success' : 'danger'" effect="dark">
                  {{ row.switchStatus === 'on' ? '合闸' : '拉闸' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="balance" label="剩余电量(kWh)" width="150" sortable>
              <template #default="{ row }">
                <span :class="{ 'text-danger': row.balance < 10, 'text-warning': row.balance < 30 }">
                  {{ row.balance.toFixed(2) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="实时数据" min-width="200">
              <template #default="{ row }">
                <div class="real-time-data">
                  <span><vab-icon icon="flashlight-line" /> {{ row.voltage }}V</span>
                  <span><vab-icon icon="pulse-line" /> {{ row.current }}A</span>
                  <span><vab-icon icon="dashboard-3-line" /> {{ row.power }}W</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right" align="center">
              <template #default="{ row }">
                <el-button-group>
                  <el-button 
                    :type="row.switchStatus === 'on' ? 'danger' : 'success'" 
                    size="small" 
                    style="margin-right: 5px;"
                    @click="handleSwitch(row)"
                    :loading="row.loading"
                  >
                    <vab-icon icon="shut-down-line" /> {{ row.switchStatus === 'on' ? '拉闸' : '合闸' }}
                  </el-button>
                  <el-button type="primary" size="small" @click="handleRecharge(row)"> <vab-icon icon="credit-card-line" /> 充值</el-button>
                  <el-button style="margin-top: 5px;" size="small" @click="handleDetail(row)"> <vab-icon icon="file-list-line" /> 查看详情</el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

          <vab-pagination
            :current-page="queryForm.pageNo"
            :page-size="queryForm.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </vab-card>
      </el-col>
    </el-row>

    <RechargeDialog ref="rechargeDialogRef" />
    <!-- 设备注册弹窗 -->
    <MeterRegisterDialog ref="registerDialogRef" />
    <!-- 详情抽屉 -->
    <MeterDetailDrawer ref="detailDrawerRef" />



  </div>
</template>

<script setup>
  import RechargeDialog from './components/RechargeDialog.vue'
  import MeterRegisterDialog from './components/MeterRegisterDialog.vue'
  import MeterDetailDrawer from './components/MeterDetailDrawer.vue'

defineOptions({
  name: 'ElectricMeter',
})

// --- Tree Logic ---
const filterText = ref('')
const treeRef = ref()
const defaultProps = {
  children: 'children',
  label: 'label',
}
const treeData = [
  {
    label: '北区1号楼',
    children: [
      { label: '101', id: '1-101' },
      { label: '102', id: '1-102' },
      { label: '201', id: '1-201' },
    ],
  },
  {
    label: '南区A栋',
    children: [
      { label: '305', id: '3-305' },
      { label: '306', id: '3-306' },
    ],
  },
]

watch(filterText, (val) => {
  treeRef.value.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}

const handleNodeClick = (data) => {
  console.log(data)
}

// --- Table Logic ---
const queryForm = reactive({
  status: '',
  switch: '',
  pageNo: 1,
  pageSize: 10,
})
const loading = ref(false)
const total = ref(100)
const tableData = ref([])
let timer = null

// Mock Data Generator
const generateMockData = () => {
  const data = []
  for (let i = 0; i < 10; i++) {
    const isOnline = Math.random() > 0.1
    const isOn = Math.random() > 0.2
    data.push({
      id: i,
      roomName: `北区1号楼-${101 + i}`,
      deviceId: `EM2026${String(i).padStart(6, '0')}`,
      status: isOnline ? 'online' : 'offline',
      switchStatus: isOn ? 'on' : 'off',
      balance: parseFloat((Math.random() * 100).toFixed(2)),
      voltage: isOnline && isOn ? (220 + Math.random() * 5 - 2.5).toFixed(1) : 0,
      current: isOnline && isOn ? (Math.random() * 10).toFixed(2) : 0,
      power: 0, // Calculated later
      loading: false
    })
  }
  return data
}

// Real-time Simulation
const updateRealTimeData = () => {
  tableData.value.forEach(item => {
    if (item.status === 'online' && item.switchStatus === 'on') {
      // 模拟电压波动
      item.voltage = (220 + Math.random() * 5 - 2.5).toFixed(1)
      // 模拟电流波动
      const baseCurrent = parseFloat(item.current)
      const change = (Math.random() - 0.5) * 0.5
      let newCurrent = baseCurrent + change
      if (newCurrent < 0) newCurrent = 0
      if (newCurrent > 15) newCurrent = 15 // Limit
      item.current = newCurrent.toFixed(2)
      // 计算功率
      item.power = Math.floor(parseFloat(item.voltage) * parseFloat(item.current))
    } else {
      item.voltage = 0
      item.current = 0
      item.power = 0
    }
  })
}

const handleQuery = () => {
  loading.value = true
  // Mock API call
  setTimeout(() => {
    tableData.value = generateMockData()
    loading.value = false
  }, 500)
}

// --- Control Logic ---
const handleSwitch = (row) => {
  const action = row.switchStatus === 'on' ? '拉闸' : '合闸'
  ElMessageBox.confirm(
    `确定要对 ${row.roomName} 进行远程【${action}】操作吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    row.loading = true
    // Simulate Hardware Delay
    setTimeout(() => {
      row.switchStatus = row.switchStatus === 'on' ? 'off' : 'on'
      row.loading = false
      ElMessage.success(`指令发送成功：${action}已执行`)
    }, 1500)
  })
}

const handleBatchOff = () => {
  ElMessageBox.confirm('确定要对当前列表所有设备进行批量拉闸吗？', '危险操作', {
    type: 'error'
  }).then(() => {
    ElMessage.success('批量指令已发送队列')
  })
}

// --- Recharge Logic ---
const rechargeDialogRef = ref(null)
const detailDrawerRef = ref(null)
const registerDialogRef = ref(null)

const handleRecharge = (row) => {
  rechargeDialogRef.value.open(row)
}

const handleAdd = () => {
  registerDialogRef.value.open()
}

  const handleDetail = (row) => {
    console.log('handleDetail clicked', row)
    if (detailDrawerRef.value) {
      detailDrawerRef.value.open(row)
    } else {
      console.error('detailDrawerRef is null')
    }
  }

const handleCurrentChange = (val) => {
  queryForm.pageNo = val
  handleQuery()
}
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  handleQuery()
}

// Lifecycle
onMounted(() => {
  handleQuery()
  // Start Real-time Simulation Loop
  timer = setInterval(updateRealTimeData, 2000)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>

<style lang="scss" scoped>
.electric-meter-container {
  .mb-10 { margin-bottom: 10px; }
  .mb-20 { margin-bottom: 20px; }
  .ml-5 { margin-left: 5px; }
  .ml-10 { margin-left: 10px; }
  .text-danger { color: var(--el-color-danger); font-weight: bold; }
  .text-warning { color: var(--el-color-warning); font-weight: bold; }
  .text-primary { color: var(--el-color-primary); }
  .text-gray { color: #909399; }
  .text-xs { font-size: 12px; }
  .font-bold { font-weight: bold; }

  .tree-card {
    height: calc(100vh - 140px);
    overflow-y: auto;
  }

  .stat-card {
    :deep(.el-card__body) {
      display: flex;
      align-items: center;
      padding: 15px;
    }

    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      .vab-icon { font-size: 24px; color: #fff; }
      &.bg-primary { background: #409eff; }
      &.bg-danger { background: #f56c6c; }
      &.bg-warning { background: #e6a23c; }
      &.bg-success { background: #67c23a; }
    }

    .stat-info {
      .stat-value { font-size: 24px; font-weight: bold; color: #303133; }
      .stat-label { font-size: 12px; color: #909399; }
    }
  }

  .real-time-data {
    display: flex;
    gap: 10px;
    font-size: 12px;
    color: #606266;
    
    span {
      display: flex;
      align-items: center;
      gap: 3px;
      background: #f5f7fa;
      padding: 2px 6px;
      border-radius: 4px;
      
      .vab-icon { font-size: 14px; color: #909399; }
    }
  }
}
</style>