<template>
  <!-- 保持原有模板不变 -->
  <div class="date-range-selector">
    <!-- 日期类型选择框 -->
    <el-select
      v-model="dateType"
      placeholder="请选择日期类型"
      class="type-select"
      @change="handleDateTypeChange"
      clearable
      @clear="handleDateTypeClear"
    >
      <el-option
        v-for="item in dateTypeOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>

    <!-- 时间选择弹窗 -->
    <el-popover
      v-model:visible="timePopoverVisible"
      placement="bottom"
      width="300"
      trigger="click"
      :disabled="!dateType"
    >
      <div class="time-select-content">
        <div class="time-control-bar">
          <el-button
            @click="handlePrev"
            size="small"
          ><</el-button>
          <span class="current-label">{{ currentRangeLabel }}</span>
          <el-button
            @click="handleNext"
            size="small"
           >></el-button>
        </div>
        <div
          class="time-option-list"
          :class="{
            'multi-col-list': dateType === '20' || dateType === '50'
          }"
        >
          <div
            v-for="(item, idx) in currentTimeOptions"
            :key="idx"
            class="time-option-item"
            :class="{
              'multi-col-item': dateType === '20' || dateType === '50'
            }"
            @click="handleTimeSelect(item)"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
      <template #reference>
        <div class="time-select-trigger" @click.stop>
          <span v-if="selectedTime.label" class="selected-label">{{ selectedTime.label }}</span>
          <span v-else class="placeholder">请选择时间</span>
          <i
            v-if="selectedTime.label"
            class="el-icon-circle-close time-clear-icon"
            @click.stop="handleTimeClear"
          />
          <i class="el-icon-arrow-down" />
        </div>
      </template>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import type { Ref } from 'vue';

// 日期类型选项
const dateTypeOptions = [
  { label: '周', value: '10' },
  { label: '月', value: '20' },
  { label: '季度', value: '30' },
  { label: '半年度', value: '40' },
  { label: '年度', value: '50' },
];

// 显式声明 props
const props = defineProps<{
  defaultDateType?: string;
  defaultSelectedTime?: { label: string; value: any };
}>();

// 响应式数据
const dateType = ref<string>('');
const timePopoverVisible = ref<boolean>(false);
const selectedTime = ref<{ label: string; value: any }>({ label: '', value: null });

// 切换基准值
const baseInfo = ref({
  year: new Date().getFullYear(),
  month: new Date().getMonth() + 1,
  decadeStart: Math.floor(new Date().getFullYear() / 10) * 10,
});

// 监听日期类型变化
const handleDateTypeChange = () => {
  if (selectedTime.value.label) {
    selectedTime.value = { label: '', value: null };
  }
  baseInfo.value = {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    decadeStart: Math.floor(new Date().getFullYear() / 10) * 10,
  };
  emit('change', { type: dateType.value });
};

// 日期类型清空逻辑
const handleDateTypeClear = () => {
  selectedTime.value = { label: '', value: null };
  emit('change', null);
};

// 时间选择清空逻辑
const handleTimeClear = () => {
  selectedTime.value = { label: '', value: null };
  emit('change', { type: dateType.value });
  timePopoverVisible.value = false;
};

// 当前范围标签
const currentRangeLabel = computed(() => {
  switch (dateType.value) {
    case '10':
      return `${baseInfo.value.year}年${baseInfo.value.month}月`;
    case '20':
    case '30':
    case '40':
      return `${baseInfo.value.year}年`;
    case '50':
      return `${baseInfo.value.decadeStart}~${baseInfo.value.decadeStart + 9}`;
    default:
      return '';
  }
});

// 当前时间选项列表
const currentTimeOptions = computed(() => {
  const options = [];
  const { year, month, decadeStart } = baseInfo.value;

  switch (dateType.value) {
    case '10':
      const weekCount = getMonthWeekCount(year, month);
      for (let i = 1; i <= weekCount; i++) {
        const weekRange = getWeekRange(year, month, i);
        options.push({
          label: `第${i}周（${weekRange.start}~${weekRange.end}）`,
          value: {
            type: '10',
            year,
            month,
            week: i,
            start: weekRange.start,
            end: weekRange.end,
          },
        });
      }
      break;
    case '20':
      for (let i = 1; i <= 12; i++) {
        options.push({
          label: `${i}月`,
          value: { type: '20', year, month: i },
        });
      }
      break;
    case '30':
      const quarterLabels = ['第一季度', '第二季度', '第三季度', '第四季度'];
      const quarterMonthRanges = ['1-3月', '4-6月', '7-9月', '10-12月'];
      for (let i = 0; i < 4; i++) {
        options.push({
          label: `${quarterLabels[i]}（${quarterMonthRanges[i]}）`,
          value: { type: '30', year, quarter: i + 1 },
        });
      }
      break;
    case '40':
      options.push(
        { label: '上半年（1-6月）', value: { type: '40', year, halfYear: 1 } },
        { label: '下半年（7-12月）', value: { type: '40', year, halfYear: 2 } }
      );
      break;
    case '50':
      for (let i = 0; i < 10; i++) {
        const currentYear = decadeStart + i;
        options.push({ label: `${currentYear}年`, value: { type: '50', year: currentYear } });
      }
      break;
    default:
      break;
  }
  return options;
});

// 上一页切换
const handlePrev = () => {
  switch (dateType.value) {
    case '10':
      if (baseInfo.value.month <= 1) {
        baseInfo.value.year -= 1;
        baseInfo.value.month = 12;
      } else {
        baseInfo.value.month -= 1;
      }
      break;
    case '20':
    case '30':
    case '40':
      baseInfo.value.year -= 1;
      break;
    case '50':
      baseInfo.value.decadeStart -= 10;
      break;
    default:
      break;
  }
};

// 下一页切换
const handleNext = () => {
  switch (dateType.value) {
    case '10':
      if (baseInfo.value.month >= 12) {
        baseInfo.value.year += 1;
        baseInfo.value.month = 1;
      } else {
        baseInfo.value.month += 1;
      }
      break;
    case '20':
    case '30':
    case '40':
      baseInfo.value.year += 1;
      break;
    case '50':
      baseInfo.value.decadeStart += 10;
      break;
    default:
      break;
  }
};

// 选择时间
const handleTimeSelect = (item: { label: string; value: any }) => {
  selectedTime.value = item;
  timePopoverVisible.value = false;
  emit('change', item.value);
};

// 工具函数：获取当月周数
const getMonthWeekCount = (year: number, month: number): number => {
  const firstDay = new Date(year, month - 1, 1).getDay() || 7;
  const monthDays = new Date(year, month, 0).getDate();
  return Math.ceil((firstDay + monthDays - 1) / 7);
};

// 工具函数：获取周范围
const getWeekRange = (year: number, month: number, week: number): { start: string; end: string } => {
  const firstDay = new Date(year, month - 1, 1);
  const firstDayWeek = firstDay.getDay() || 7;
  const firstWeekStart = new Date(firstDay);
  firstWeekStart.setDate(firstDay.getDate() - (firstDayWeek - 1));
  const targetWeekStart = new Date(firstWeekStart);
  targetWeekStart.setDate(firstWeekStart.getDate() + (week - 1) * 7);
  const targetWeekEnd = new Date(targetWeekStart);
  targetWeekEnd.setDate(targetWeekStart.getDate() + 6);

  const formatDate = (date: Date) => {
    const m = date.getMonth() + 1;
    const d = date.getDate();
    return `${m.toString().padStart(2, '0')}-${d.toString().padStart(2, '0')}`;
  };

  return { start: formatDate(targetWeekStart), end: formatDate(targetWeekEnd) };
};

// 向外暴露事件
const emit = defineEmits<{
  (e: 'change', value: any): void;
}>();

// 监听默认值props
watch(
  () => props.defaultDateType,
  (val) => {
    if (val) dateType.value = val;
  },
  { immediate: true }
);

watch(
  () => props.defaultSelectedTime,
  (val) => {
    if (val) selectedTime.value = val;
  },
  { immediate: true }
);

// ========== 关键新增：重置方法 ==========
const resetDateSelector = () => {
  // 清空日期类型
  dateType.value = '';
  // 清空选中时间
  selectedTime.value = { label: '', value: null };
  // 关闭弹窗
  timePopoverVisible.value = false;
  // 重置基准值
  baseInfo.value = {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    decadeStart: Math.floor(new Date().getFullYear() / 10) * 10,
  };
  // 派发空值给父组件，同步状态
  emit('change', null);
};

// ========== 暴露重置方法给父组件 ==========
defineExpose({
  resetDateSelector
});
</script>

<style scoped>
/* 保持原有样式不变 */
.date-range-selector {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 0;
}

.type-select {
  width: 120px;
}

.time-select-trigger {
  width: 220px;
  height: 32px;
  line-height: 32px;
  padding: 0 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  position: relative;
}

.time-select-trigger .placeholder {
  color: #c5c8ce;
  font-size: 14px;
}

.time-select-trigger .selected-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.time-select-trigger .el-icon-arrow-down {
  color: #dcdfe6;
  font-size: 12px;
  margin-left: 8px;
}

.time-clear-icon {
  color: #c5c8ce;
  font-size: 14px;
  margin-right: 4px;
  cursor: pointer;
  transition: color 0.2s;
}

.time-clear-icon:hover {
  color: #f56c6c;
}

.time-select-content {
  padding: 8px 0;
}

.time-control-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px 8px;
  border-bottom: 1px solid #ebeef5;
}

.time-control-bar .current-label {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.time-option-list {
  padding: 8px 0;
}

.multi-col-list {
  display: flex;
  flex-wrap: wrap;
  padding: 4px 0;
}

.time-option-item {
  height: 36px;
  line-height: 36px;
  padding: 0 16px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  box-sizing: border-box;
}

.multi-col-item {
  width: 33.33%;
  text-align: center;
  padding: 0;
}

.time-option-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}
</style>