<template>
  <div class="home-page">
    <!-- 顶部导航栏 -->
    <div class="header-bg">
      <div class="user-section">
        <div class="avatar">
          {{ userInfo.nickName ? userInfo.nickName?.charAt(0) : "" }}
        </div>
        <div class="user-info">
          <div class="user-name">{{ userInfo.nickName }}</div>
          <div class="dept-name">{{ userInfo.departName }}</div>
        </div>
      </div>

      <!-- 当前位置 -->
      <div class="location" v-if="userInfo.workAddress">
        <van-icon name="location" class="location-icon" />
        <span>{{ userInfo.workAddress }}</span>
      </div>
    </div>

    <!-- 功能卡片 -->
    <div class="function-cards">
      <div v-for="(card, index) in functionCards" :key="index" class="card-item" :class="card.bgClass"
        @click="handleCardClick(card)">
        <!-- 装饰性背景图标 -->
        <div class="card-decor">
          <van-icon :name="card.icon" class="decor-icon" />
        </div>

        <!-- 内容 -->
        <div class="card-content">
          <div class="card-title">{{ card.label }}</div>
          <div class="card-subtitle">{{ card.subtitle }}</div>
          <div class="card-count">
            <span class="count-label">{{ card.countLabel }}</span>
            <span class="count-value">{{ card.count }}</span>
          </div>
          <div class="card-action">
            <span>前往处理</span>
            <van-icon name="arrow" class="action-icon" />
          </div>
        </div>
      </div>
    </div>

    <!-- 随手拍功能区 -->
    <div class="ssp-section" @click="goToReport">
      <div class="ssp-icon">
        <van-icon name="photograph" class="ssp-icon-inner" />
      </div>
      <div class="ssp-content">
        <div class="ssp-title">随手拍</div>
        <div class="ssp-desc">随时随地上报违规</div>
      </div>
    </div>

    <!-- 最新预警列表 -->
    <div class="alerts-section">
      <div class="section-header">
        <h2 class="section-title">拦截预警</h2>
        <div class="section-action" @click="goToAlertList">
          <span>查看全部</span>
          <span class="arrow">&gt;</span>
        </div>
      </div>

      <van-loading v-if="initLoading" class="loading-state" color="#2563eb"
        style="text-align:center;padding:20px;">加载中...</van-loading>
      <van-list v-else v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad"
        class="alerts-list">
        <div v-for="alert in alertList" :key="alert.id" class="alert-item" @click="handleAlertClick(alert)">
          <!-- 类型和等级 -->
          <div class="alert-header">
            <span class="alert-type">{{ alert.eventType }}</span>
            <span class="alert-priority" :class="getLevelClass(alert.eventLevel)">
              {{ getStatusText(alert.eventLevel) }}
            </span>
          </div>

          <!-- 违章预警显示车牌信息 -->
          <div class="alert-vehicle">
            <van-icon name="logistics"  />
            <span>{{ alert.plateNo }}</span>
            <span class="separator">|</span>
            <span>{{ alert.vehicleColor }}</span>
            <span class="separator">|</span>
            <span>{{ alert.vehicleType }}</span>
          </div>

          <!-- 检测点位 -->
          <div class="alert-location">
            <van-icon name="location-o" />
            <span class="label">检测点位：</span>
            <span>{{ alert.siteName }}</span>
          </div>

          <!-- 检测时间 -->
          <div class="alert-time">
            <van-icon name="clock-o" />
            <span class="label">检测时间：</span>
            <span>{{ alert.passTime }}</span>
          </div>
        </div>
      </van-list>
    </div>

    <!-- 底部导航栏 -->
    <BottomTabs :active-tab="'home'" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { List } from "vant";
import BottomTabs from "@/components/bottomTabs.vue";
import { countByTaskStatus, getInterceptWarnList } from "@/api/traffic";

const router = useRouter();

// 用户信息
const userInfo = ref({
  userName: '张警官',
  deptName: '交警支队一大队'
});
const userNameChar = computed(() => {
  const name = userInfo.value.userName || '张';
  return name.charAt(0);
});

// 随手拍待处理数量
const sspPendingCount = ref(12);

// 当前位置
const currentLocation = ref("");

// 功能卡片数据
const functionCards = ref([
  {
    icon: "warning",
    label: "路况任务",
    subtitle: "应急处理数据信息",
    count: 0,
    countLabel: "未执行",
    bgClass: "bg-traffic",
    route: "/traffic-alerts",
    type: "traffic"
  },
  {
    icon: "todo-list",
    label: "违规任务",
    subtitle: "违章车辆数据信息",
    count: 0,
    countLabel: "未执行",
    bgClass: "bg-violation",
    route: "/violation-alerts",
    type: "violation"
  }
]);

// 分页相关状态
const alertList = ref([]);
const loading = ref(false);
const finished = ref(false);
const initLoading = ref(false);
const pageSize = 5;
const currentPage = ref(0);

// 过滤未执行的预警（接口直接返回未执行数据，此处无需过滤）
const filteredAlerts = computed(() => {
  return alertList.value;
});
onMounted(() => {
  userInfo.value = JSON.parse(localStorage.getItem('userInfo')) || {};
  fetchTaskStats();
})

// 加载拦截预警列表
async function onLoad() {
  initLoading.value = true;
  loading.value = true;
  const userId = userInfo.value?.id;
  if (!userId) {
    finished.value = true;
    loading.value = false;
    initLoading.value = false;
    return;
  }

  try {
    const res = await getInterceptWarnList({
      userId,
      status: 0,
      pageSize,
      page: currentPage.value + 1
    });
    console.log('拦截预警列表:', res);
    if (res && res.content) {
      const records = res.content || [];
      if (currentPage.value === 0) {
        alertList.value = records;
      } else {
        alertList.value.push(...records);
      }
      currentPage.value++;

      const totalPages = res.content.totalPages || res.content.pages || 1;
      if (currentPage.value >= totalPages) {
        finished.value = true;
      }
    } else if (res && Array.isArray(res)) {
      alertList.value = res;
      finished.value = true;
    } else {
      alertList.value = [];
      finished.value = true;
    }
  } catch (error) {
    console.error("获取拦截预警列表失败:", error);
    alertList.value = [];
    finished.value = true;
  } finally {
    loading.value = false;
    initLoading.value = false;
  }
}

// 跳转到随手拍上报页面
function goToReport() {
  router.push("/ssp-report");
}

// 跳转到预警列表
function goToAlertList() {
  router.push("/warningList");
}

// 处理卡片点击
function handleCardClick(card) {
  router.push(card.route);
}

// 处理预警项点击
function handleAlertClick(alert) {
  if (alert.alertType === "traffic") {
    router.push({
      path: "/traffic-alert-detail",
      query: { id: alert.id, status: alert.status }
    });
  } else {
    router.push({
      path: "/violation-detail",
      query: { id: alert.taskId, status: alert.status }
    });
  }
}

// 获取任务统计数据
async function fetchTaskStats() {
  const userId = userInfo.value?.id;
  if (!userId) return;

  try {
    const res = await countByTaskStatus({
      userId: userId,
      startTime: "",
      endTime: ""
    });
    if (res && Array.isArray(res)) {
      res.forEach(item => {
        const total = item.statusList.reduce((sum, s) => sum + (s.count || 0), 0);
        if (item.eventCategory === 1) {
          functionCards.value[0].count = total;
        } else if (item.eventCategory === 2) {
          functionCards.value[1].count = total;
        }
      });
    }
  } catch (error) {
    console.error("获取任务统计数据失败:", error);
  }
}

// 等级样式
function getLevelClass(level) {
  const map = {
    1: "level-red",
    2: "level-orange",
    // 3: "level-yellow",
    3: "level-blue",
  };
  return map[level] || "level-blue";
}

// 状态样式
function getStatusText(status) {
  const map = {
    1: "一级",
    2: "二级",
    3: "三级",
  };
  return map[status] || "三级";
}
</script>

<style lang="scss" scoped>
.home-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

.header-bg {
  background: linear-gradient(135deg, #2563eb, #1d4ed8);
  padding: 48px 24px 32px;
  border-radius: 0 0 24px 24px;
}

.user-section {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  background: rgba(96, 165, 250, 1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.user-info {
  .user-name {
    color: white;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 4px;
  }

  .dept-name {
    color: rgba(255, 255, 255, 0.7);
    font-size: 14px;
  }
}

.location {
  display: flex;
  align-items: center;
  gap: 6px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;

  .location-icon {
    font-size: 16px;
  }
}

.function-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  padding: 16px;
}

.ssp-section {
  margin: 12px 16px;
  background: linear-gradient(135deg, #34c759, #28a745);
  border-radius: 12px;
  padding: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 14px;
  box-shadow: 0 2px 12px rgba(40, 167, 69, 0.3);
  cursor: pointer;

  &:active {
    transform: scale(0.98);
  }
}

.ssp-icon {
  .ssp-icon-inner {
    font-size: 24px;
    color: white;
  }
}

.ssp-content {
  display: flex;
  align-items: center;
  gap: 8px;

  .ssp-title {
    color: white;
    font-size: 17px;
    font-weight: 600;
  }

  .ssp-desc {
    color: rgba(255, 255, 255, 0.85);
    font-size: 14px;
  }
}

.ssp-badge {
  background: #fff;
  border-radius: 50%;
  min-width: 22px;
  height: 22px;
  padding: 0 6px;
  display: flex;
  align-items: center;
  justify-content: center;

  .ssp-badge-num {
    color: #34c759;
    font-size: 12px;
    font-weight: 600;
  }
}

.card-item {
  position: relative;
  border-radius: 20px;
  padding: 20px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  transition: box-shadow 0.2s;

  &:active {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  &.bg-traffic {
    background: linear-gradient(135deg, #4A9FF5, #1E88E5);
  }

  &.bg-violation {
    background: linear-gradient(135deg, #FF7043, #F4511E);
  }
}

.card-decor {
  position: absolute;
  right: 8px;
  bottom: 8px;
  opacity: 0.2;

  .decor-icon {
    font-size: 96px;
    color: white;
  }
}

.card-content {
  position: relative;
  z-index: 1;
}

.card-title {
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 4px;
}

.card-subtitle {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  margin-bottom: 6px;
}

.card-count {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 12px;

  .count-label {
    color: rgba(255, 255, 255, 0.9);
    font-size: 14px;
  }

  .count-value {
    color: white;
    font-size: 36px;
    font-weight: bold;
  }
}

.card-action {
  display: flex;
  align-items: center;
  gap: 4px;
  color: white;
  font-size: 14px;

  .action-icon {
    font-size: 16px;
  }
}

.alerts-section {
  padding: 0 16px;
  margin-top: 8px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 0 4px;

  .section-title {
    color: #333;
    font-size: 16px;
    font-weight: 600;
  }

  .section-action {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #2563eb;
    font-size: 14px;

    .arrow {
      font-size: 16px;
    }
  }
}

.alerts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-bottom: 16px;

  :deep(.van-list__loading) {
    padding: 16px 0;
  }

  :deep(.van-list__finished-text) {
    color: #9ca3af;
    font-size: 14px;
    text-align: center;
    padding: 16px 0;
  }
}

.alert-item {
  background: white;
  border-radius: 20px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  cursor: pointer;

  &:active {
    background: #fafafa;
  }
}

.alert-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;

  .alert-type {
    color: #333;
    font-size: 16px;
    font-weight: 500;
  }

  .alert-priority {
    padding: 2px 8px;
    border-radius: 8px;
    font-size: 12px;

    &.priority-high {
      background: #fee2e2;
      color: #dc2626;
    }
    &.level-red {
      background: #ffe2e2;
      color: #e8101a;
    }
    &.level-orange {
      background: #fff3e0;
      color: #ff9800;
    }
    &.level-yellow {
      background: #fffde7;
      color: #ffc107;
    }
    &.level-blue {
      background: #e3f2fd;
      color: #2196f3;
    }
  }
}

.alert-vehicle {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;

  .vehicle-icon {
    font-size: 16px;
    color: #999;
  }

  .separator {
    color: #ddd;
  }
}

.alert-location,
.alert-time {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;

  .info-icon {
    font-size: 16px;
    color: #999;
  }

  .label {
    color: #999;
  }
}
</style>