<template>
  <div class="emergency-procedure-container">
    <div class="container-title">
      <span class="line"></span>
      <span class="title">应急处置</span>
    </div>
    <YearSelector class="year-selector" :years="yearsList" :defaultYear="defaultYear" @year-change="handleYearChange" />
    <div class="event-counts">
      <div v-if="yearSelected === defaultYear">
        <span>本月应急事件</span>
        <span class="event-count">{{ monthCount }}</span>
      </div>
      <div>
        <span>本年应急事件</span>
        <span class="event-count">{{ yearCount }}</span>
      </div>
    </div>
    <EmergencyEventsChart class="events-echarts" />
    <div class="container-title">
      <span class="line"></span>
      <span class="title">应急事件</span>
    </div>
    <div class="events-list">
      <div class="event-item" v-for="(item, index) in eventsList" :key="index">
        <div class="event-name">{{ item.name }}</div>
        <div class="event-time">{{ item.time }}</div>
        <div class="event-status" v-if="item.status">{{ item.status }}</div>
      </div>

      <!-- 哨兵 -->
      <div ref="sentinelRef" style="height: 1px"></div>

      <div v-if="isLoading" class="loading">
        <span>加载中...</span>
      </div>
      <div v-if="!hasMore && eventsList.length > 0" class="no-more">
        <span>暂无更多应急预案</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import YearSelector from './YearSelector.vue';
  import EmergencyEventsChart from './EmergencyEventsChart.vue';
  import { useInfiniteScroll } from '../hooks/useInfiniteScroll';

  interface EventItem {
    name: string;
    time: string;
    status?: string; // 是否是启动中状态
  }

  const defaultYear = ref<number>(new Date().getFullYear()); // 默认为当前年份
  const yearsList = ref<number[]>([2021, 2022, 2023, 2024, 2025]);
  const yearSelected = ref<number>(defaultYear.value);

  const monthCount = ref<number>(0);
  const yearCount = ref<number>(0);

  const eventsList = ref<EventItem[]>([]);
  const page = ref<number>(1);
  const pageSize = ref<number>(10);
  const hasMore = ref<boolean>(true);
  const isLoading = ref<boolean>(false);
  const sentinelRef = ref<HTMLElement | null>(null); // 哨兵元素引用

  const params = ref({
    year: yearSelected.value,
    page: page.value,
    pageSize: pageSize.value,
  });

  // 请求后端接口获取数据
  const fetchExerciseData = async () => {
    if (isLoading.value || !hasMore.value) return;

    isLoading.value = true;

    try {
      // TODO: 替换为实际的 API 请求
      // const res = await axios.get('/api/items', params.value);
      const res = {
        data: {
          items: [
            { name: '事件1', time: '2023-10-10', status: '启动中' },
            { name: '事件2', time: '2023-10-10', status: '启动中' },
            { name: '事件3', time: '2023-10-10', status: '启动中' },
            { name: '事件4', time: '2023-10-10', status: '启动中' },
            { name: '事件5', time: '2023-10-10' },
            { name: '事件6', time: '2023-10-10' },
            { name: '事件7', time: '2023-10-10' },
            { name: '事件8', time: '2023-10-10' },
            { name: '事件9', time: '2023-10-10' },
            { name: '事件10', time: '2023-10-10' },
            { name: '事件11', time: '2023-10-10' },
            { name: '事件12', time: '2023-10-10' },
          ],
        },
      };

      // TODO: 赋值：本月应急事件，本年应急事件，事件列表，折线图
      const newItems = res.data.items as EventItem[];

      if (newItems.length === 0) {
        hasMore.value = false;
      } else {
        eventsList.value.push(...newItems);
        page.value++;
      }
    } catch (error) {
      console.error('请求失败:', error);
    } finally {
      isLoading.value = false;
    }
  };

  // 切换年份的状态重置
  const resetStateAndFetchData = () => {
    hasMore.value = true;
    page.value = 1;
    eventsList.value = []; // 清空当前列表
    monthCount.value = 0;
    yearCount.value = 0;
    console.log('params', params.value);
    fetchExerciseData();
  };

  const handleYearChange = (year: number) => {
    yearSelected.value = year;
    resetStateAndFetchData();
  };

  onMounted(() => {
    fetchExerciseData();
    useInfiniteScroll(sentinelRef, fetchExerciseData);
  });
</script>

<style scoped lang="scss">
  .container-title {
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 16px;
    color: #000000;

    .line {
      width: 3px;
      height: 16px;
      background: #1777ff;
      margin-right: 10px;
    }

    .title {
      margin-right: 12px;
    }
  }

  .emergency-procedure-container {
    width: 100%;
    height: 100%;
    padding: 10px 0;
    position: relative;

    .year-selector {
      position: absolute;
      top: 11px;
      right: 16px;
    }

    .event-counts {
      display: flex;
      justify-content: space-around;
      align-items: center;
      margin: 20px 7px 10px 7px;
      padding: 12px 0px;
      background: #e7f1ff;
      border-radius: 8px;
      font-weight: 400;
      font-size: 16px;
      color: rgba(0, 0, 0, 0.65);

      .event-count {
        color: #1777ff;
        margin-left: 4px;
      }
    }

    .events-echarts {
      margin: 15px 10px;
    }

    .events-list {
      width: 100%;
      height: calc(100% - 387px);
      margin-top: 15px;
      padding: 0 10px;
      overflow: auto;

      .event-item {
        width: 100%;
        height: 82px;
        margin-bottom: 10px;
        background: #dcfaff;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 0 16px;
        position: relative;

        .event-name {
          font-weight: 500;
          font-size: 16px;
          color: #333333;
          margin-bottom: 8px;
        }

        .event-time {
          font-size: 14px;
          color: #666666;
        }

        .event-status {
          position: absolute;
          top: 0;
          right: 0;
          background: #ff4d4f;
          border-radius: 0px 8px 0px 8px;
          font-size: 10px;
          color: #ffffff;
          padding: 2px 6px;
        }
      }
    }
  }
</style>
