<template>
  <div class="traffic-alerts-page">
    <!-- 顶部导航栏 -->
    <div class="nav-bar">
      <van-icon name="arrow-left" class="nav-back" @click="goBack" />
      <h1 class="nav-title">路况任务</h1>
      <van-icon name="filter-o" class="nav-filter" />
    </div>

    <!-- 标签栏 -->
    <div class="tabs-bar">
      <button v-for="tab in tabs" :key="tab.id" class="tab-item" :class="{ active: activeTab === tab.id }"
        @click="activeTab = tab.id">
        {{ tab.label }}
      </button>
    </div>

    <!-- 预警列表 -->
    <div class="alerts-list" ref="listRef">
      <!-- 列表内容 -->
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoadMore">
        <div v-for="alert in filteredAlerts" :key="alert.id" class="alert-card">
          <!-- 等级、标题和状态标签 -->
          <div class="card-header">
            <span class="status-tag" :class="getStatusClass(alert.taskStatus)">
              {{ statusMap[alert.taskStatus] }}
            </span>
          </div>
          <!-- 图片 -->
          <div class="card-image">
            <van-image :src="alert.imgUrl" fit="cover" class="alert-img" />
          </div>
         
          
          <div class="card-title-row">
            <span class="level-tag" :class="getLevelClass(alert.eventLevel)">
              {{ levelMap[alert.eventLevel] }}
            </span>
            <span class="alert-title">{{ alert.eventType }}</span>
          </div>


          <!-- 详细信息 -->
          <div class="card-details">
            <div class="detail-item">
              <van-icon name="location-o" class="detail-icon" />
              <span class="label">检测点位：</span>
              <span class="value">{{ alert.siteName }}</span>
            </div>
            <div class="detail-item">
              <van-icon name="clock-o" class="detail-icon" />
              <span class="label">检测时间：</span>
              <span class="value">{{ alert.eventTime }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="card-actions">
            <!-- 待执行/执行中/已完成 - 显示查看详情 -->
            <van-button block round type="primary" class="action-btn" @click="handleDetail(alert)">
              查看详情
            </van-button>

            <!-- 待派发 - 显示定位打卡 -->
            <!-- <van-button
              block
              round
              type="primary"
              class="action-btn"
              @click="handleCheckIn(alert)"
            >
              定位打卡
            </van-button> -->
          </div>
        </div>
      </van-list>

      <!-- 空状态 -->
      <van-empty v-if="filteredAlerts.length === 0 " description="暂无数据" class="empty-state" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { getTrafficEventList } from "@/api/traffic";

const router = useRouter();
const filteredAlerts = ref([]);
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')))
// 状态
const activeTab = ref("all");
const loading = ref(false);
const finished = ref(false);

// 标签栏
const tabs = ref([
  { id: "all", label: "全部" },
  { id: "not-executed", label: "未执行" },
  { id: "processing", label: "执行中" },
  { id: "completed", label: "已完成" },
]);

const listQuery = ref({
  eventCategory: '1',
  page: 1,
  pageSize: 10,
  taskStatus: "",
  userId: "4"
  // userId:userInfo.value.id
});

// 分类映射：tabId -> status
const categoryMap = {
  "all": null,
  "not-executed": 0,     // 待派发
  "processing": 1,       // 执行中
  "completed": 2        // 已完成
};

// 状态文本映射
const statusMap = {
  0: "待执行",
  1: "执行中",
  2: "已完成",
};

// 等级映射
const levelMap = {
  0: "一级",
  1: "二级",
  2: "三级",
  3: "四级"
};

// 重置列表
function resetList() {
  filteredAlerts.value = [];
  listQuery.value.page = 1;
  finished.value = false;
}

// 获取列表数据
const fetchAlerts = async (isLoadMore = false) => {
  if (isLoadMore) loading.value = true;

  try {
    // 根据标签添加状态筛选
    listQuery.value.taskStatus = categoryMap[activeTab.value];
    const res = await getTrafficEventList(listQuery.value);
    console.log(res, 'res');
    if (res && res.content) {
      const records = res.content || [];
      if (isLoadMore) {
        filteredAlerts.value.push(...records);
      } else {
        filteredAlerts.value = records;
      }

      // 判断是否加载完成
      const totalPages = res.content.totalPages || res.content.pages || 1;
      const currentPage = res.content.pageNum || res.content.current || listQuery.value.page;
      if (currentPage >= totalPages) {
        finished.value = true;
      }
    } else if (res && Array.isArray(res)) {
      if (isLoadMore) {
        filteredAlerts.value.push(...res);
      } else {
        filteredAlerts.value = res;
      }
      finished.value = true;
    } else {
      filteredAlerts.value = [];
      finished.value = true;
    }
  } catch (error) {
    console.error("获取交通预警列表失败:", error);
    if (!isLoadMore) filteredAlerts.value = [];
    finished.value = true;
  } finally {
    loading.value = false;
  }
};

// 加载更多
function onLoadMore() {
  listQuery.value.page++;
  fetchAlerts(true);
}

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

// 状态样式
function getStatusClass(status) {
  const map = {
    0: "status-gray",
    1: "status-blue",
    2: "status-green",
  };
  return map[status] || "status-gray";
}

// 返回
function goBack() {
  router.back();
}

// 查看详情
function handleDetail(alert) {
  router.push({
    path: "/traffic-alert-detail",
    query: { id: alert.id, status: alert.status }
  });
}

// 定位打卡
function handleCheckIn(alert) {
  router.push({
    path: "/checkInPage",
    query: { id: alert.id }
  });
}

// 切换标签时重新加载
watch(activeTab, () => {
  resetList();
  fetchAlerts();
});

// 页面初始化
onMounted(() => {
  fetchAlerts();
});
</script>

<style lang="scss" scoped>
.traffic-alerts-page {
  min-height: 100vh;
  background: #f1f5f9;
  padding-bottom: 20px;
}

.nav-bar {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  border-bottom: 1px solid #e5e5e5;
  padding: 12px 16px;

  .nav-back {
    font-size: 24px;
    color: #333;
  }

  .nav-title {
    font-size: 17px;
    font-weight: 600;
    color: #333;
  }

  .nav-filter {
    font-size: 24px;
    color: #333;
  }
}

.tabs-bar {
  display: flex;
  gap: 16px;
  background: white;
  padding: 12px 16px;
  overflow-x: auto;

  .tab-item {
    flex-shrink: 0;
    padding: 6px 16px;
    font-size: 14px;
    font-weight: 500;
    color: #64748b;
    background: #f1f5f9;
    border-radius: 20px;
    transition: all 0.2s;
    white-space: nowrap;
    border: none;

    &.active {
      background: #2563eb;
      color: white;
    }
  }
}

.alerts-list {
  padding: 16px;
}

.alert-card {
  background: white;
  border-radius: 20px;
  overflow: hidden;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.card-header {
  text-align: right;
  padding: 12px 16px 0;
}

.status-tag {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;

  &.status-gray {
    background: #f1f5f9;
    color: #64748b;
    border: 1px solid #e2e8f0;
  }

  &.status-blue {
    background: #eff6ff;
    color: #2563eb;
    border: 1px solid #bfdbfe;
  }

  &.status-green {
    background: #f0fdf4;
    color: #16a34a;
    border: 1px solid #bbf7d0;
  }

  &.status-orange {
    background: #fff7ed;
    color: #ea580c;
    border: 1px solid #fed7aa;
  }
}

.card-image {
  padding: 12px 16px;

  .alert-img {
    width: 100%;
    height: 180px;
    border-radius: 12px;
  }
}

.card-title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 16px;
  margin-bottom: 10px;

  .level-tag {
    padding: 4px 8px;
    border-radius: 8px;
    font-size: 12px;

    &.level-red {
      background: #fee2e2;
      color: #dc2626;
    }

    &.level-orange {
      background: #ffedd5;
      color: #ea580c;
    }

    &.level-blue {
      background: #dbeafe;
      color: #2563eb;
    }
  }

  .alert-title {
    font-size: 15px;
    font-weight: 500;
    color: #333;
  }
}

.card-details {
  padding: 0 16px 12px;

  .detail-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    font-size: 14px;

    &:last-child {
      margin-bottom: 0;
    }

    .detail-icon {
      font-size: 16px;
      color: #2563eb;
      margin-right: 8px;
    }

    .label {
      color: #94a3b8;
      margin-right: 4px;
    }

    .value {
      color: #475569;
    }
  }
}

.card-actions {
  padding: 8px 16px 16px;

  .action-btn {
    height: 44px;
    background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
    border: none;
    border-radius: 12px;
    font-size: 15px;
    font-weight: 500;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
  }
}

.empty-state {
  padding: 60px 0;
}
</style>