<template>
  <div class="year-range-picker">
    <el-input
      v-model="displayValue"
      readonly
      clearable
      @click="toggleYearPanel"
      @clear="clearRange"
      placeholder="选择年份范围"
      class="year-input"
    >
      <template #suffix>
        <i class="el-icon-arrow-down" :class="{ 'is-reverse': panelVisible }"></i>
      </template>
    </el-input>

    <transition name="fade">
      <div class="year-panel" v-show="panelVisible">
        <div class="panel-header">
          <div class="year-type">
            <el-radio-group v-model="selectedType">
              <el-radio-button label="start">开始年份</el-radio-button>
              <el-radio-button label="end">结束年份</el-radio-button>
            </el-radio-group>
          </div>
          <div class="panel-actions">
            <el-button size="mini" @click="closePanel">取消</el-button>
            <el-button size="mini" type="primary" @click="confirmRange" :disabled="!isValidRange"
              >确定</el-button
            >
          </div>
        </div>

        <div class="year-grid">
          <div
            v-for="year in yearList"
            :key="year"
            :class="{
              'year-item': true,
              'is-selected': isSelectedYear(year),
              'is-disabled': isDisabledYear(year)
            }"
            @click="selectYear(year)"
          >
            {{ year }}年
          </div>
        </div>

        <div class="quick-options">
          <el-button size="small" @click="selectLastYear">近1年</el-button>
          <el-button size="small" @click="selectLast3Years">近3年</el-button>
          <el-button size="small" @click="selectLast5Years">近5年</el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, defineProps, defineEmits, nextTick } from 'vue'
import { ElInput, ElRadioGroup, ElRadioButton, ElButton } from 'element-plus'

const props = defineProps<{
  modelValue: [string, string] | []
  showQuickOptions: boolean
  yearRange: [number, number] // 可选年份范围 [开始年份, 结束年份]
}>()

const emits = defineEmits<{
  (event: 'update:modelValue', value: [string, string]): void
  (event: 'change', value: [string, string]): void
}>()

// 内部状态
const panelVisible = ref(false)
const selectedType = ref('start') // 当前选择的是开始还是结束年份
const startYear = ref<string | null>(props.modelValue[0] || null)
const endYear = ref<string | null>(props.modelValue[1] || null)

// 生成年份列表（默认可选范围：当前年份前后10年）
const yearRange = computed(() => {
  const [min, max] = props.yearRange || []
  const currentYear = new Date().getFullYear()
  const defaultMin = currentYear - 10
  const defaultMax = currentYear + 10

  return [min || defaultMin, max || defaultMax]
})

const yearList = computed(() => {
  const [min, max] = yearRange.value
  return Array.from({ length: max - min + 1 }, (_, i) => min + i)
})

// 显示值
const displayValue = computed(() => {
  if (startYear.value && endYear.value) {
    return `${startYear.value}年 - ${endYear.value}年`
  } else if (startYear.value) {
    return `${startYear.value}年 - 未选择结束年份`
  } else if (endYear.value) {
    return `未选择开始年份 - ${endYear.value}年`
  }
  return ''
})

// 判断年份是否已选择
const isSelectedYear = (year: number) => {
  if (selectedType.value === 'start') {
    return year.toString() === startYear.value
  } else {
    return year.toString() === endYear.value
  }
}

// 判断年份是否禁用
const isDisabledYear = (year: number) => {
  if (selectedType.value === 'start' && endYear.value) {
    return year > parseInt(endYear.value)
  } else if (selectedType.value === 'end' && startYear.value) {
    return year < parseInt(startYear.value)
  }
  return false
}

// 判断范围是否有效
const isValidRange = computed(() => {
  return !!(startYear.value && endYear.value && startYear.value <= endYear.value)
})

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    startYear.value = newVal[0] || null
    endYear.value = newVal[1] || null
  }
)

// 监听内部值变化，同步到外部
watch([startYear, endYear], ([newStart, newEnd]) => {
  if (newStart && newEnd && newStart <= newEnd) {
    emits('update:modelValue', [newStart, newEnd])
  }
})

// 切换年份面板显示
const toggleYearPanel = () => {
  panelVisible.value = !panelVisible.value
}

// 关闭面板
const closePanel = () => {
  panelVisible.value = false
}

// 确认选择
const confirmRange = () => {
  if (isValidRange.value) {
    emits('update:modelValue', [startYear.value!, endYear.value!])
    emits('change', [startYear.value!, endYear.value!])
    panelVisible.value = false
  }
}

// 选择年份
const selectYear = (year: number) => {
  if (selectedType.value === 'start') {
    startYear.value = year.toString()
    // 如果开始年份大于结束年份，清空结束年份
    if (endYear.value && startYear.value > endYear.value) {
      endYear.value = null
    }
  } else {
    endYear.value = year.toString()
  }
}

// 清空选择
const clearRange = () => {
  startYear.value = null
  endYear.value = null
  emits('update:modelValue', [])
}

// 快捷选择：近1年
const selectLastYear = () => {
  const currentYear = new Date().getFullYear().toString()
  const lastYear = (new Date().getFullYear() - 1).toString()
  startYear.value = lastYear
  endYear.value = currentYear
  confirmRange()
}

// 快捷选择：近3年
const selectLast3Years = () => {
  const currentYear = new Date().getFullYear().toString()
  const threeYearsAgo = (new Date().getFullYear() - 3).toString()
  startYear.value = threeYearsAgo
  endYear.value = currentYear
  confirmRange()
}

// 快捷选择：近5年
const selectLast5Years = () => {
  const currentYear = new Date().getFullYear().toString()
  const fiveYearsAgo = (new Date().getFullYear() - 5).toString()
  startYear.value = fiveYearsAgo
  endYear.value = currentYear
  confirmRange()
}

// 点击外部关闭面板
const clickOutside = (e: MouseEvent) => {
  const target = e.target as HTMLElement
  const pickerEl = document.querySelector('.year-range-picker') as HTMLElement

  if (pickerEl && !pickerEl.contains(target)) {
    panelVisible.value = false
  }
}

// 添加点击外部事件监听
onMounted(() => {
  document.addEventListener('click', clickOutside)
})

// 移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', clickOutside)
})
</script>

<style scoped lang="scss">
.year-range-picker {
  position: relative;

  .year-input {
    cursor: pointer;
  }

  .year-panel {
    position: absolute;
    top: 40px;
    left: 0;
    width: 300px;
    background: #000;
    border: 1px solid #dcdcdc;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    padding: 10px;

    .panel-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;

      .year-type {
        .el-radio-button__inner {
          padding: 6px 15px;
        }
      }

      .panel-actions {
        display: flex;
        gap: 10px;
      }
    }

    .year-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 8px;
      margin-bottom: 15px;

      .year-item {
        padding: 8px;
        text-align: center;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;

        &:hover:not(.is-disabled) {
          background-color: #f5f7fa;
        }

        &.is-selected {
          background-color: #409eff;
          color: #fff;
        }

        &.is-disabled {
          color: #c0c4cc;
          cursor: not-allowed;
        }
      }
    }

    .quick-options {
      display: flex;
      gap: 10px;
      margin-top: 10px;
    }
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s;
  }
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
}
</style>
