<template>
  <div class="electric-warning-container">
    <!-- 顶部统计 -->
    <el-row :gutter="20" class="mb-20">
      <el-col :span="6">
        <vab-card shadow="hover" class="stat-card">
          <div class="stat-icon bg-danger">
            <vab-icon icon="alarm-warning-fill" />
          </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-warning">
            <vab-icon icon="fire-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">5</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-orange">
            <vab-icon icon="flashlight-fill" />
          </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-info">
            <vab-icon icon="shut-down-line" />
          </div>
          <div class="stat-info">
            <div class="stat-value">4</div>
            <div class="stat-label">长期未用电 (7天+)</div>
          </div>
        </vab-card>
      </el-col>
    </el-row>

    <!-- 图表与列表布局 -->
    <el-row :gutter="20">
      <el-col :span="16">
        <vab-card title="实时用电监控">
          <template #header>
            <div class="card-header">
              <vab-icon icon="broadcast-line" class="mr-5" />
              <span>实时监控列表</span>
              <el-tag type="danger" effect="dark" class="ml-10 animate-pulse">设备在线</el-tag>
            </div>
          </template>
          
          <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.type" placeholder="全部" clearable style="width: 140px">
                    <el-option label="恶性负载" value="malignant" />
                    <el-option label="功率超限" value="overload" />
                    <el-option label="长期未用电" value="inactive" />
                  </el-select>
                </el-form-item>
                <el-form-item label="楼宇/房间">
                  <el-input v-model="queryForm.keyword" placeholder="例如：一号书院 302" clearable style="width: 180px" />
                </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>

          <el-table v-loading="loading" :data="tableData" border stripe style="height: calc(100vh - 400px);">
            <el-table-column prop="time" label="预警时间" width="160" sortable />
            <el-table-column prop="roomName" label="位置" />
            <el-table-column prop="type" label="预警类型" width="120">
              <template #default="{ row }">
                <el-tag :type="getWarningType(row.type).tag" effect="dark">
                  {{ getWarningType(row.type).label }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="监测数值" width="120">
              <template #default="{ row }">
                <span class="font-bold">{{ row.value }}</span>
                <span class="text-xs text-gray ml-5">{{ row.unit }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'pending' ? 'danger' : 'success'" size="small">
                  {{ row.status === 'pending' ? '待处理' : '已处理' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <div v-if="row.status === 'pending'">
                  <el-button type="danger" size="small" plain @click="handlePowerOff(row)"> <vab-icon icon="shut-down-line" /> 断开</el-button>
                  <el-button type="primary" size="small" @click="handleProcess(row)"> <vab-icon icon="edit-line" /> 处理</el-button>
                </div>
                <span v-else class="text-gray text-xs">
                  处理结果: {{ row.result }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </vab-card>
      </el-col>

      <el-col :span="8" style="height: calc(100vh - 400px);">
        <!-- 违规电器排行榜 -->
        <vab-card class="mb-20" title="违规电器类型分布">
           <vab-chart style="height: 240px" :option="pieChartOption" height="240px" />
        </vab-card>
        
        <!-- 重点监控房间 -->
        <vab-card title="重点监控房间 (频繁违规)">
          <div class="focus-list">
            <div v-for="item in focusList" :key="item.id" class="focus-item">
              <div class="room-icon bg-warning">
                <vab-icon icon="home-4-line" />
              </div>
              <div class="info">
                <div class="name-row">
                  <span class="name">{{ item.room }}</span>
                  <el-tag size="small" type="danger">{{ item.count }}次违规</el-tag>
                </div>
                <div class="desc">最近一次: {{ item.lastTime }}</div>
              </div>
              <el-button type="text" icon="file-list-line" @click="handleDetail(item)"> <vab-icon icon="file-list-line" /> 详情</el-button>
            </div>
          </div>
        </vab-card>
      </el-col>
    </el-row>

    <!-- 处理弹窗 -->
    <ProcessDialog ref="processDialogRef" @success="handleProcessSuccess" />

    <!-- 详情抽屉 -->
    <RoomDetailDrawer ref="roomDetailDrawerRef" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProcessDialog from './components/ProcessDialog.vue'
import RoomDetailDrawer from './components/RoomDetailDrawer.vue'

defineOptions({
  name: 'ElectricWarning',
})

// --- Data ---
const queryForm = reactive({
  type: '',
  keyword: '',
})

const loading = ref(false)
const tableData = ref([])
const processDialogRef = ref(null)
const roomDetailDrawerRef = ref(null)

// Mock Focus List
const focusList = [
  { id: 1, room: '一号书院 302', count: 5, lastTime: '2026-01-23 10:00' },
  { id: 2, room: '三号书院 505', count: 3, lastTime: '2026-01-22 18:30' },
  { id: 3, room: '二号书院 101', count: 3, lastTime: '2026-01-21 21:15' },
]

// Mock Chart Option
const pieChartOption = ref({
  tooltip: { trigger: 'item' },
  legend: { top: '5%', left: 'center' },
  series: [
    {
      name: '违规类型',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: { show: false, position: 'center' },
      emphasis: {
        label: { show: true, fontSize: 20, fontWeight: 'bold' }
      },
      labelLine: { show: false },
      data: [
        { value: 48, name: '热得快' },
        { value: 35, name: '电磁炉' },
        { value: 17, name: '电热毯' },
        { value: 10, name: '其他' }
      ]
    }
  ]
})

// --- Helpers ---
const getWarningType = (type) => {
  const map = {
    malignant: { label: '恶性负载', tag: 'danger' },
    overload: { label: '功率超限', tag: 'warning' },
    inactive: { label: '长期未用电', tag: 'info' },
  }
  return map[type] || { label: '未知', tag: '' }
}

// --- Methods ---
const generateMockData = () => {
  return [
    {
      id: 1,
      time: '2026-01-23 10:00:15',
      roomName: '一号书院 302',
      type: 'malignant',
      value: '800',
      unit: 'W',
      status: 'pending',
    },
    {
      id: 2,
      time: '2026-01-23 09:15:30',
      roomName: '二号书院 205',
      type: 'overload',
      value: '3500',
      unit: 'W',
      status: 'pending',
    },
    {
      id: 3,
      time: '2026-01-22 14:00:00',
      roomName: '三号书院 101',
      type: 'inactive',
      value: '0',
      unit: 'kWh',
      status: 'pending',
    },
    {
      id: 4,
      time: '2026-01-22 20:30:00',
      roomName: '一号书院 405',
      type: 'malignant',
      value: '1200',
      unit: 'W',
      status: 'processed',
      result: '已没收',
      operator: '管理员B'
    }
  ]
}

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

const handlePowerOff = (row) => {
  ElMessageBox.confirm(
    `确定要对 ${row.roomName} 执行远程断电操作吗？`,
    '高危操作提示',
    {
      confirmButtonText: '确定断电',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      ElMessage.success('断电指令下发成功')
    })
    .catch(() => {})
}

const handleProcess = (row) => {
  processDialogRef.value.open(row)
}

const handleProcessSuccess = ({ id, action }) => {
  const item = tableData.value.find(i => i.id === id)
  if (item) {
    item.status = 'processed'
    item.result = action === 'confiscate' ? '已没收' : (action === 'restore' ? '已恢复' : '已教育')
  }
}

const handleDetail = (item) => {
  roomDetailDrawerRef.value.open(item)
}

onMounted(() => {
  handleQuery()
})
</script>

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

  // 脉冲动画
  .animate-pulse {
    animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
  }
  @keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: .5; }
  }

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

    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      font-size: 24px;
      color: #fff;
      &.bg-danger { background: #f56c6c; }
      &.bg-warning { background: #e6a23c; }
      &.bg-orange { background: #ff9900; }
      &.bg-info { background: #909399; }
    }

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

  .focus-list {
    .focus-item {
      display: flex;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child { border-bottom: none; }

      .room-icon {
        width: 40px;
        height: 40px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        &.bg-warning { background-color: #e6a23c; }
      }

      .info {
        flex: 1;
        margin-left: 12px;
        
        .name-row {
          display: flex;
          align-items: center;
          gap: 8px;
          .name { font-weight: bold; font-size: 14px; }
        }
        
        .desc {
          font-size: 12px;
          color: #999;
          margin-top: 4px;
        }
      }
    }
  }
}
</style>