<template>
  <div class="dashboard">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="welcome-banner__bg">
        <div class="welcome-banner__shape shape-1"></div>
        <div class="welcome-banner__shape shape-2"></div>
        <div class="welcome-banner__shape shape-3"></div>
      </div>
      <div class="welcome-banner__content">
        <h1 class="welcome-banner__title">
          <el-icon :size="32"><Monitor /></el-icon>
          <span>智能浇水管理系统</span>
        </h1>
        <p class="welcome-banner__desc">实时监控设备状态，高效管理 IoT 设备网络</p>
      </div>
    </div>

    <!-- 第一行统计：设备状态 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card stat-card--blue">
          <div class="stat-card__body">
            <div class="stat-card__icon">
              <el-icon :size="32"><Cpu /></el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__value">{{ stats.total }}</div>
              <div class="stat-card__label">设备总数</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card stat-card--green">
          <div class="stat-card__body">
            <div class="stat-card__icon">
              <el-icon :size="32"><Connection /></el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__value">{{ stats.working }}</div>
              <div class="stat-card__label">在线</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card stat-card--orange">
          <div class="stat-card__body">
            <div class="stat-card__icon">
              <el-icon :size="32"><VideoPause /></el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__value">{{ stats.standby }}</div>
              <div class="stat-card__label">待机</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card stat-card--red">
          <div class="stat-card__body">
            <div class="stat-card__icon">
              <el-icon :size="32"><WarningFilled /></el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__value">{{ stats.offline }}</div>
              <div class="stat-card__label">离线</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 第二行统计：故障 + 工作状态 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card stat-card--danger">
          <div class="stat-card__body">
            <div class="stat-card__icon">
              <el-icon :size="32"><CircleCloseFilled /></el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__value">{{ stats.fault }}</div>
              <div class="stat-card__label">故障</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card stat-card--teal">
          <div class="stat-card__body">
            <div class="stat-card__icon">
              <el-icon :size="32"><CircleCheck /></el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__value">{{ workStats.working }}</div>
              <div class="stat-card__label">工作中 </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card stat-card--slate">
          <div class="stat-card__body">
            <div class="stat-card__icon">
              <el-icon :size="32"><RemoveFilled /></el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__value">{{ workStats.idle }}</div>
              <div class="stat-card__label">空闲</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card stat-card--purple">
          <div class="stat-card__body">
            <div class="stat-card__icon">
              <el-icon :size="32"><UserFilled /></el-icon>
            </div>
            <div class="stat-card__info">
              <div class="stat-card__value">{{ workStats.unbound }}</div>
              <div class="stat-card__label">未绑定用户</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 快捷入口 -->
    <div class="section-header">
      <h3 class="section-header__title">
        <el-icon><Menu /></el-icon>
        快捷入口
      </h3>
    </div>
    <el-row :gutter="16" class="shortcuts-row">
      <el-col :xs="12" :sm="8" :lg="6">
        <div class="shortcut-card" @click="$router.push('/app/device')">
          <div class="shortcut-card__icon shortcut-card__icon--device">
            <el-icon :size="28"><Monitor /></el-icon>
          </div>
          <span class="shortcut-card__text">设备管理</span>
        </div>
      </el-col>
      <el-col :xs="12" :sm="8" :lg="6">
        <div class="shortcut-card" @click="$router.push('/app/bindDevice')">
          <div class="shortcut-card__icon shortcut-card__icon--bind">
            <el-icon :size="28"><Link /></el-icon>
          </div>
          <span class="shortcut-card__text">已绑定设备</span>
        </div>
      </el-col>
    </el-row>

    <!-- 设备列表 -->
    <div class="section-header">
      <h3 class="section-header__title">
        <el-icon><Cpu /></el-icon>
        设备列表
      </h3>
      <span class="section-header__sub">共 {{ stats.total }} 台设备</span>
    </div>
    <div class="device-table-card">
      <el-table :data="pagedDeviceList" stripe style="width: 100%" size="default">
        <el-table-column align="center" label="设备编号" prop="deviceNo" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.deviceNo || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="设备名称" prop="deviceName" min-width="140" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.deviceName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getDeviceStatusType(scope.row.status)">
              {{ getDeviceStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="工作状态" prop="workStatus" width="100">
          <template #default="scope">
            <el-tag :type="getWorkStatusType(scope.row.workStatus)">
              {{ getWorkStatusLabel(scope.row.workStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="电量" prop="powerLevel" width="160">
          <template #default="scope">
            <div v-if="scope.row.powerLevel !== undefined && scope.row.powerLevel !== null && scope.row.powerLevel !== ''" class="power-level">
              <svg class="power-level__icon" :class="getPowerLevelClass(scope.row.powerLevel)" viewBox="0 0 48 24" width="48" height="24">
                <rect x="0" y="2" width="42" height="20" rx="4" ry="4" fill="none" stroke="currentColor" stroke-width="2" />
                <rect x="42" y="8" width="4" height="8" rx="2" ry="2" fill="currentColor" />
                <rect x="3" y="5" :width="Math.max(36 * formatPowerLevel(scope.row.powerLevel) / 100, 0)" height="14" rx="2" ry="2" fill="currentColor" />
              </svg>
              <span class="power-level__text">{{ formatPowerLevel(scope.row.powerLevel) }}%</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="WiFi名称" prop="wifiName" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.wifiName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="固件版本" prop="fwVer" width="110">
          <template #default="scope">
            <el-tag v-if="scope.row.fwVer" size="small" effect="plain" type="info">{{ scope.row.fwVer }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="MAC地址" prop="macAddress" width="160">
          <template #default="scope">
            <span v-if="scope.row.macAddress" class="mac-address">{{ formatMacAddress(scope.row.macAddress) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="device-table-card__footer">
        <el-pagination
          v-model:current-page="deviceViewPage.pageNum"
          v-model:page-size="deviceViewPage.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          :total="deviceTotal"
          small
          background
          @size-change="fetchDeviceList"
          @current-change="fetchDeviceList"
        />
      </div>
    </div>
  </div>
</template>

<script setup name="Index" lang="ts">
import { onMounted, reactive, ref, computed } from 'vue';
import { listDevice, getDashboard } from '@/api/app/device';
import type { DeviceVO, DashboardVO } from '@/api/app/device/types';

interface DashboardStats {
  total: number;
  working: number;
  standby: number;
  offline: number;
  fault: number;
}

const stats = reactive<DashboardStats>({
  total: 0,
  working: 0,
  standby: 0,
  offline: 0,
  fault: 0
});

const workStats = reactive({
  working: 0,
  idle: 0,
  unbound: 0
});

// --- 设备列表 ---
const deviceList = ref<DeviceVO[]>([]);
const deviceTotal = ref(0);
const deviceViewPage = reactive({ pageNum: 1, pageSize: 10 });

const pagedDeviceList = computed(() => deviceList.value);

const deviceStatusMap: Record<string, { label: string; type: 'success' | 'info' | 'warning' | 'danger' }> = {
  '0': { label: '离线', type: 'info' },
  '1': { label: '工作中', type: 'success' },
  '2': { label: '待机', type: 'warning' },
  '3': { label: '故障', type: 'danger' }
};

const getDeviceStatusLabel = (status: string | number | undefined) => {
  if (status === undefined || status === null || status === '') return '-';
  return deviceStatusMap[String(status)]?.label ?? String(status);
};

const getDeviceStatusType = (status: string | number | undefined) => {
  return deviceStatusMap[String(status)]?.type ?? 'info';
};

const workStatusMap: Record<string, { label: string; type: 'success' | 'info' | 'warning' | 'danger' }> = {
  '0': { label: '空闲', type: 'info' },
  '1': { label: '工作中', type: 'success' },
  '2': { label: '未绑定用户', type: 'warning' }
};

const getWorkStatusLabel = (workStatus: string | number | undefined) => {
  if (workStatus === undefined || workStatus === null || workStatus === '') return '-';
  return workStatusMap[String(workStatus)]?.label ?? String(workStatus);
};

const getWorkStatusType = (workStatus: string | number | undefined) => {
  return workStatusMap[String(workStatus)]?.type ?? 'info';
};

const formatPowerLevel = (powerLevel: string | number | undefined) => {
  if (powerLevel === undefined || powerLevel === null || powerLevel === '') return 0;
  const num = Number(powerLevel);
  return isNaN(num) ? 0 : Math.round(num);
};

const getPowerLevelClass = (powerLevel: string | number | undefined) => {
  const value = formatPowerLevel(powerLevel);
  if (value <= 20) return 'power-level--low';
  if (value <= 50) return 'power-level--medium';
  return 'power-level--high';
};

const formatMacAddress = (mac: string) => {
  const cleaned = mac.replace(/[^0-9a-fA-F]/g, '');
  const parts = cleaned.match(/.{1,2}/g);
  return parts ? parts.join(':').toLowerCase() : mac;
};

const fetchDashboard = async () => {
  try {
    const res = await getDashboard();
    // 兼容两种情况：后端直接平铺字段，或嵌套在 data 内
    const data = ((res as any).data as DashboardVO) ?? (res as unknown as DashboardVO);

    stats.total = data.totalDevices ?? 0;
    stats.working = data.onlineDevices ?? 0;
    stats.standby = data.standbyDevices ?? 0;
    stats.offline = data.offlineDevices ?? 0;
    stats.fault = data.faultDevices ?? 0;

    workStats.working = data.workingDevices ?? 0;
    workStats.idle = data.idleDevices ?? 0;
    workStats.unbound = data.unboundDevices ?? 0;
  } catch {
    // 接口异常时保持默认值
  }
};

const fetchDeviceList = async () => {
  try {
    const res = await listDevice({
      pageNum: deviceViewPage.pageNum,
      pageSize: deviceViewPage.pageSize,
      orderByColumn: 'd.create_time',
      isAsc: 'desc'
    });
    deviceList.value = (res as any).rows || [];
    deviceTotal.value = (res as any).total || 0;
  } catch {
    deviceList.value = [];
    deviceTotal.value = 0;
  }
};

onMounted(() => {
  fetchDashboard();
  fetchDeviceList();
});
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 24px;
}

/* ====== 欢迎横幅 ====== */
.welcome-banner {
  position: relative;
  overflow: hidden;
  border-radius: 12px;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 140px;
}

.welcome-banner__bg {
  position: absolute;
  inset: 0;
  pointer-events: none;
}

.welcome-banner__shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.08);
}

.shape-1 {
  width: 200px;
  height: 200px;
  top: -60px;
  right: 40px;
}

.shape-2 {
  width: 120px;
  height: 120px;
  top: 20px;
  right: 200px;
}

.shape-3 {
  width: 80px;
  height: 80px;
  bottom: -20px;
  right: 120px;
}

.welcome-banner__content {
  position: relative;
  z-index: 1;
  padding: 28px 36px;
}

.welcome-banner__title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 0 8px;
  font-size: 26px;
  font-weight: 600;
  color: #fff;
  letter-spacing: 0.5px;
}

.welcome-banner__desc {
  margin: 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.82);
  letter-spacing: 0.3px;
}

/* ====== 统计卡片 ====== */
.stats-row {
  margin-bottom: 12px;
}

.stat-card {
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 16px;
  cursor: default;
  transition: transform 0.2s, box-shadow 0.2s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  }
}

.stat-card--blue {
  background: linear-gradient(135deg, #e8f0fe 0%, #d2e3fc 100%);
  .stat-card__icon { color: #4285f4; }
  .stat-card__value { color: #4285f4; }
}

.stat-card--green {
  background: linear-gradient(135deg, #e6f4ea 0%, #ceead6 100%);
  .stat-card__icon { color: #34a853; }
  .stat-card__value { color: #34a853; }
}

.stat-card--orange {
  background: linear-gradient(135deg, #fef7e0 0%, #fdecc8 100%);
  .stat-card__icon { color: #f9ab00; }
  .stat-card__value { color: #f9ab00; }
}

.stat-card--red {
  background: linear-gradient(135deg, #fce8e6 0%, #f8d7da 100%);
  .stat-card__icon { color: #ea4335; }
  .stat-card__value { color: #ea4335; }
}

.stat-card--danger {
  background: linear-gradient(135deg, #fce4ec 0%, #f8bbd0 100%);
  .stat-card__icon { color: #d81b60; }
  .stat-card__value { color: #d81b60; }
}

.stat-card--teal {
  background: linear-gradient(135deg, #e6f4f0 0%, #ceeae2 100%);
  .stat-card__icon { color: #009688; }
  .stat-card__value { color: #009688; }
}

.stat-card--slate {
  background: linear-gradient(135deg, #f1f3f4 0%, #e2e5e7 100%);
  .stat-card__icon { color: #5f6368; }
  .stat-card__value { color: #5f6368; }
}

.stat-card--purple {
  background: linear-gradient(135deg, #f3e8fd 0%, #e4ccfa 100%);
  .stat-card__icon { color: #9334e6; }
  .stat-card__value { color: #9334e6; }
}

.stat-card__body {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-card__icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.7);
  flex-shrink: 0;
}

.stat-card__value {
  font-size: 28px;
  font-weight: 700;
  line-height: 1;
  font-variant-numeric: tabular-nums;
}

.stat-card__label {
  font-size: 13px;
  color: #5f6368;
  margin-top: 4px;
}

/* ====== 区块标题 ====== */
.section-header {
  display: flex;
  align-items: center;
  margin: 28px 0 16px;
}

.section-header__title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #202124;
}

.section-header__sub {
  margin-left: 12px;
  font-size: 13px;
  color: #80868b;
  padding-top: 2px;
}

/* ====== 设备列表卡片 ====== */
.device-table-card {
  background: #fff;
  border-radius: 10px;
  border: 1px solid #f0f0f0;
  overflow: hidden;
  margin-bottom: 24px;
}

.device-table-card__footer {
  display: flex;
  justify-content: flex-end;
  padding: 12px 16px 16px;
}

/* ====== 电量 ====== */
.power-level {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.power-level__icon {
  flex-shrink: 0;
}

.power-level__text {
  font-weight: 600;
  font-variant-numeric: tabular-nums;
  min-width: 40px;
  text-align: left;
}

.power-level--high { color: #67c23a; }
.power-level--medium { color: #e6a23c; }
.power-level--low { color: #f56c6c; }

/* ====== MAC地址 ====== */
.mac-address {
  font-family: 'Consolas', 'Menlo', 'Courier New', monospace;
  font-size: 13px;
  letter-spacing: 0.5px;
}

/* ====== 快捷入口 ====== */
.shortcuts-row {
  margin-bottom: 8px;
}

.shortcut-card {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 18px 20px;
  border-radius: 10px;
  background: #fff;
  border: 1px solid #f0f0f0;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s, border-color 0.2s;
  margin-bottom: 12px;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
    border-color: #d2e3fc;
  }
}

.shortcut-card__icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.shortcut-card__icon--device {
  background: #e8f0fe;
  color: #4285f4;
}

.shortcut-card__icon--bind {
  background: #e6f4ea;
  color: #34a853;
}

.shortcut-card__text {
  font-size: 14px;
  font-weight: 500;
  color: #3c4043;
}
</style>
