<template>
  <div class="year-selector">
    <el-icon class="prev-year" :class="{ disabled: currentYear === props.years[0] }" @click="prevYear"
      ><CaretLeft
    /></el-icon>
    <span class="current-year">{{ currentYear }}</span>
    <el-icon
      class="next-year"
      :class="{ disabled: currentYear === props.years[props.years.length - 1] }"
      @click="nextYear"
      ><CaretRight
    /></el-icon>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { ElIcon } from 'element-plus';
  import { CaretLeft, CaretRight } from '@element-plus/icons-vue';

  interface Props {
    years: number[]; // 年份数组
    defaultYear: number | undefined; // 默认年份
  }

  const props = withDefaults(defineProps<Props>(), {
    years: () => [],
    defaultYear: 0,
  });

  const emit = defineEmits<{
    (event: 'year-change', year: number): void;
  }>();

  const currentIndex = ref<number>(0); // 当前索引
  const currentYear = ref<number>(props.defaultYear); // 当前年份

  // 初始化当前索引
  watch(
    () => props.years,
    (newYears) => {
      if (newYears.length > 0) {
        const initialIndex = newYears.indexOf(props.defaultYear);
        if (initialIndex !== -1) {
          currentIndex.value = initialIndex;
          currentYear.value = props.defaultYear;
        } else {
          currentIndex.value = 0;
          currentYear.value = newYears[0];
        }
      }
    },
    { immediate: true },
  );

  // 切换年份逻辑
  function prevYear() {
    if (currentIndex.value > 0) {
      currentIndex.value--;
      currentYear.value = props.years[currentIndex.value];
      notifyParent(currentYear.value);
    }
  }

  function nextYear() {
    if (currentIndex.value < props.years.length - 1) {
      currentIndex.value++;
      currentYear.value = props.years[currentIndex.value];
      notifyParent(currentYear.value);
    }
  }

  function notifyParent(year: number) {
    emit('year-change', year);
  }
</script>

<style scoped lang="scss">
  .year-selector {
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 0 5px;
    border-radius: 4px;
    border: 1px solid #1777ff;
  }

  .prev-year,
  .next-year {
    cursor: pointer;
    color: #1777ff;
    font-size: 14px;
  }

  .prev-year:hover,
  .next-year:hover {
    color: #0056b3;
  }

  .disabled {
    color: #d9d9d9;
    cursor: not-allowed;
  }

  .disabled:hover {
    color: #d9d9d9;
  }

  .current-year {
    font-weight: 400;
    font-size: 14px;
    color: #1777ff;
  }
</style>
