<template>
  <view class="schedule-page">
    <view class="week-selector" @click="openWeekPicker">
      <text>{{ weekInfo.displayText }}</text>
      <uni-icons type="right" size="16" color="#fff"></uni-icons>
    </view>

    <view class="date-tabs">
      <view
        v-for="(day, index) in weekDates"
        :key="index"
        :class="['date-tab-item', { active: selectedDayIndex === index }]"
        @click="selectDay(index)"
      >
        <text class="weekday">{{ day.weekday }}</text>
        <text class="date">{{ day.dateMMDD }}</text>
      </view>
    </view>

    <view class="schedule-body">
      <view
        v-for="(timeSlot, index) in scheduleData"
        :key="index"
        class="schedule-row"
      >
        <view class="time-slot">
          <text class="slot-name">{{ timeSlot.name }}</text>
          <text class="slot-time">{{ timeSlot.timeRange }}</text>
        </view>

        <view class="course-container">
          <template v-if="timeSlot.subjects && timeSlot.subjects.length > 0">
            <view
              v-for="(course, courseIndex) in timeSlot.subjects"
              :key="courseIndex"
              :class="['course-card', getCourseColorClass(course.subject)]"
            >
              <text class="course-subject">{{ course.subject }}</text>
              <text class="course-class">{{ course.class }}</text>
            </view>
          </template>
          <view v-else class="empty-course">
            <text class="empty-text">暂无课程</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="isLoading" class="loading-overlay">
      <text>加载中...</text>
    </view>

    <!-- 周选择弹窗 -->
    <uni-popup ref="weekPopup" type="bottom" @change="popupChange">
      <view class="week-picker-popup">
        <view class="popup-header">
          <text class="title">选择周</text>
        </view>
        <view class="week-list">
          <scroll-view
            scroll-y
            style="max-height: 60vh"
            :scroll-top="targetScrollTop"
          >
            <view
              v-for="(week, index) in availableWeeks"
              :key="index"
              :class="[
                'week-item',
                { active: week.displayText === weekInfo.displayText },
              ]"
              @click="selectWeek(week)"
            >
              <text>{{ week.displayText }}</text>
              <text v-if="isCurrentWeek(week)" class="current-tag">当前周</text>
            </view>
          </scroll-view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import weekOfYear from "dayjs/plugin/weekOfYear";
import isoWeek from "dayjs/plugin/isoWeek";

dayjs.locale("zh-cn");
dayjs.extend(weekOfYear);
dayjs.extend(isoWeek);

interface Course {
  subject: string;
  class: string;
}

interface TimeSlot {
  name: string;
  timeRange: string;
  subjects?: Course[];
}

interface WeekInfo {
  weekNumber: number;
  startDate: string;
  endDate: string;
  displayText: string;
}

interface WeekDay {
  dateFull: string;
  dateMMDD: string;
  weekday: string;
}

const isLoading = ref(false);
const currentDate = ref(dayjs());
const selectedDayIndex = ref(0);
const scheduleData = ref<TimeSlot[]>([]);

// 周选择相关
const showWeekPicker = ref(false);
const weekPopup = ref<any>(null);
const weekInfo = reactive<WeekInfo>({
  weekNumber: 0,
  startDate: "",
  endDate: "",
  displayText: "",
});
const weekDates = ref<WeekDay[]>([]);
const selectedWeekNumber = ref(0);
const availableWeeks = ref<WeekInfo[]>([]);

// 计算当前周的周一日期
const currentWeekMonday = computed(() => currentDate.value.isoWeekday(1));

// 初始化当前周信息
const initializeCurrentWeekInfo = () => {
  const now = dayjs();
  currentDate.value = now; // Ensure currentDate is today
  const monday = now.isoWeekday(1);
  const friday = monday.add(4, "day");
  const year = monday.year();
  const weekNum = monday.isoWeek();

  weekInfo.weekNumber = weekNum;
  weekInfo.startDate = monday.format("MM.DD");
  weekInfo.endDate = friday.format("MM.DD");
  weekInfo.displayText = `${year}年 第${weekNum}周 (${monday.format(
    "MM.DD"
  )}-${friday.format("MM.DD")})`;
  selectedWeekNumber.value = weekNum;
};

// 生成可选择的周列表 - 只显示当前年份
const generateAvailableWeeks = () => {
  const weeks: WeekInfo[] = [];
  const currentYear = dayjs().year();

  for (let weekNum = 1; weekNum <= 53; weekNum++) {
    const monday = dayjs().year(currentYear).isoWeek(weekNum).isoWeekday(1);

    if (monday.isoWeekYear() === currentYear) {
      const friday = monday.add(4, "day");
      const actualWeekNum = monday.isoWeek();
      weeks.push({
        weekNumber: actualWeekNum,
        startDate: monday.format("MM.DD"),
        endDate: friday.format("MM.DD"),
        displayText: `${currentYear}年 第${actualWeekNum}周 (${monday.format(
          "MM.DD"
        )}-${friday.format("MM.DD")})`,
      });
    }
  }
  const uniqueWeeks = weeks.filter(
    (week, index, self) =>
      index === self.findIndex((w) => w.weekNumber === week.weekNumber)
  );

  availableWeeks.value = uniqueWeeks;
  console.log("Generated weeks:", availableWeeks.value);
};

// 检查是否是当前周
const isCurrentWeek = (week: WeekInfo) => {
  return dayjs().isoWeek() === week.weekNumber;
};

// 更新顶部日期tabs
const updateWeekDates = () => {
  const monday = currentDate.value.isoWeekday(1);
  const dates: WeekDay[] = [];
  const weekdaysZh = ["周一", "周二", "周三", "周四", "周五"];
  for (let i = 0; i < 5; i++) {
    const day = monday.add(i, "day");
    dates.push({
      dateFull: day.format("YYYY-MM-DD"),
      dateMMDD: day.format("M/DD"),
      weekday: weekdaysZh[i],
    });
  }
  weekDates.value = dates;

  // 确定新一周的默认选中日期
  const todayWeekday = dayjs().isoWeekday();
  if (currentDate.value.isSame(dayjs(), "isoWeek")) {
    if (todayWeekday >= 1 && todayWeekday <= 5) {
      selectedDayIndex.value = todayWeekday - 1;
    } else {
      selectedDayIndex.value = 0; // 如果是周末，默认选中周一
    }
  } else {
    selectedDayIndex.value = 0; // 非本周，默认选中周一
  }
};

// 获取课表数据
const fetchScheduleData = async () => {
  console.log(`正在获取第${weekInfo.weekNumber}周课表数据...`);
  isLoading.value = true;

  await new Promise((resolve) => setTimeout(resolve, 500));

  const timeSlotTemplates = [
    { name: "上1", timeRange: "08:00-08:45" },
    { name: "上2", timeRange: "08:55-09:40" },
    { name: "上3", timeRange: "10:00-10:45" },
    { name: "上4", timeRange: "10:55-11:40" },
    { name: "下1", timeRange: "14:00-14:45" },
    { name: "下2", timeRange: "14:55-15:40" },
    { name: "下3", timeRange: "16:00-16:45" },
    { name: "下4", timeRange: "16:55-17:40" },
  ];

  const mockData: TimeSlot[] = [];

  // 这里可以根据weekInfo.weekNumber添加不同的模拟数据
  // 例如奇数周和偶数周的课程安排不同
  const isOddWeek = weekInfo.weekNumber % 2 === 1;

  for (const slot of timeSlotTemplates) {
    const subjectsForDay = generateSubjectsForDay(
      slot.name,
      selectedDayIndex.value,
      isOddWeek
    );
    mockData.push({
      name: slot.name,
      timeRange: slot.timeRange,
      subjects: subjectsForDay,
    });
  }

  scheduleData.value = mockData;
  isLoading.value = false;
  console.log("课表数据加载完成:", scheduleData.value);
};

// 根据周次生成不同的课程数据
const generateSubjectsForDay = (
  slotName: string,
  dayIndex: number,
  isOddWeek: boolean
): Course[] => {
  const subjects: Course[] = [];

  // 模拟不同日期和时间段的课程数据
  // 可以根据isOddWeek参数生成不同的课程安排
  if (dayIndex === 0) {
    // 周一
    if (slotName === "上1" || slotName === "上2") {
      subjects.push({
        subject: isOddWeek ? "语文" : "数学",
        class: "小2018级01班",
      });
    } else if (slotName === "上3") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    } else if (slotName === "下1" || slotName === "下2") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    }
  } else if (dayIndex === 1) {
    // 周二
    if (slotName === "上1" || slotName === "上2") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    } else if (slotName === "下1") {
      subjects.push({
        subject: isOddWeek ? "语文" : "数学",
        class: "小2018级01班",
      });
    }
  } else if (dayIndex === 2) {
    // 周三
    if (slotName === "上2") {
      subjects.push({
        subject: isOddWeek ? "语文" : "数学",
        class: "小2018级01班",
      });
    } else if (slotName === "下1") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    } else if (slotName === "下3") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    }
  } else if (dayIndex === 3) {
    // 周四
    if (slotName === "上4") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    } else if (slotName === "下1") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    }
  } else if (dayIndex === 4) {
    // 周五
    if (slotName === "上1") {
      subjects.push({
        subject: isOddWeek ? "语文" : "数学",
        class: "小2018级01班",
      });
    } else if (slotName === "上2") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    } else if (slotName === "下2") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    } else if (slotName === "下4") {
      subjects.push({ subject: "体育", class: "小2018级01班" });
    }
  }

  return subjects;
};

// 选择日期
const selectDay = (index: number) => {
  selectedDayIndex.value = index;
  fetchScheduleData();
};

// 调整估算的周列表项高度
const ESTIMATED_WEEK_ITEM_HEIGHT = 53.5; // px (精确值)

const targetScrollTop = ref(0); // 新增：用于绑定 scroll-top

// 打开周选择弹窗
const openWeekPicker = async () => {
  showWeekPicker.value = true;

  // 确保列表数据已准备好
  if (availableWeeks.value.length === 0) {
    console.warn("Available weeks list is empty.");
    // generateAvailableWeeks(); // 可选：如果列表可能为空则重新生成
  }

  // 找到当前周的索引
  const currentIndex = availableWeeks.value.findIndex(
    (week) => week.weekNumber === weekInfo.weekNumber
  );

  if (currentIndex !== -1) {
    // 使用调整后的高度重新计算
    const calculatedScrollTop = currentIndex * ESTIMATED_WEEK_ITEM_HEIGHT;

    // 简化设置逻辑，直接在 nextTick 后设置
    await nextTick();
    targetScrollTop.value = calculatedScrollTop;
  } else {
    // 如果找不到当前周，滚动到顶部
    await nextTick();
    targetScrollTop.value = 0; // 直接设置为 0
  }

  // 打开弹窗
  await nextTick();
  if (weekPopup.value) {
    weekPopup.value.open("bottom");
  } else {
    console.error("Week popup ref is not available.");
  }
};

// 关闭周选择弹窗
const closeWeekPicker = () => {
  if (weekPopup.value) {
    weekPopup.value.close();
  }
};

// 弹窗状态变化
const popupChange = (e: { show: boolean }) => {
  if (!e.show) {
    showWeekPicker.value = false;
  }
};

// 选择周
const selectWeek = (week: WeekInfo) => {
  if (week.displayText === weekInfo.displayText) {
    // 如果点击的是当前已选中的周，则只关闭弹窗
    closeWeekPicker();
    return;
  }

  // 更新当前显示的周信息
  Object.assign(weekInfo, week);

  // 更新 currentDate 以匹配新选择的周
  const selectedYear = parseInt(week.displayText.substring(0, 4));
  const selectedIsoWeek = week.weekNumber;
  currentDate.value = dayjs()
    .year(selectedYear)
    .isoWeek(selectedIsoWeek)
    .isoWeekday(1);

  // 更新顶部日期tabs
  updateWeekDates();

  // 关闭弹窗
  closeWeekPicker();

  // 获取新的课表数据
  fetchScheduleData();
};

// 判断课程颜色
const getCourseColorClass = (subject: string | undefined): string => {
  if (!subject) return "";
  if (subject.includes("语文")) return "color-lang";
  if (subject.includes("体育")) return "color-phys";
  if (subject.includes("数学")) return "color-math";
  return "color-other";
};

onMounted(() => {
  initializeCurrentWeekInfo();
  generateAvailableWeeks();
  updateWeekDates();
  fetchScheduleData();
});
</script>

<style scoped lang="scss">
.schedule-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.week-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #4477ee;
  color: #ffffff;
  font-size: 15px;
}

.date-tabs {
  display: flex;
  background-color: #4477ee;
  padding: 10px 15px 15px 15px;
  gap: 10px;

  .date-tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 8px 5px;
    border-radius: 6px;
    background-color: rgba(255, 255, 255, 0.1);
    color: #ffffff;
    flex: 1;
    min-width: 50px;
    cursor: pointer;
    transition: background-color 0.2s ease;

    .weekday {
      font-size: 13px;
      opacity: 0.9;
    }

    .date {
      font-size: 14px;
      font-weight: 500;
      margin-top: 2px;
    }

    &.active {
      background-color: #ffffff;
      color: #4477ee;

      .weekday {
        opacity: 1;
      }
    }
  }
}

.schedule-body {
  flex: 1;
  overflow-y: auto;
  background-color: #ffffff;
  margin: 15px;
  border-radius: 8px;
  padding: 10px;
}

.schedule-row {
  display: flex;
  margin-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;

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

.time-slot {
  width: 75px;
  min-width: 75px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f9fafb;
  border-radius: 6px;
  padding: 8px 0;

  .slot-name {
    font-size: 14px;
    font-weight: 500;
    color: #333;
  }

  .slot-time {
    font-size: 11px;
    color: #999;
    margin-top: 3px;
  }
}

.course-container {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  margin-left: 10px;
  gap: 8px;
}

.course-card {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  padding: 8px 12px;
  min-width: 120px;
  text-align: center;
  color: #333;

  .course-subject {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 2px;
  }

  .course-class {
    font-size: 11px;
    color: #666;
  }

  &.color-lang {
    background-color: #ffebee;
    border-left: 3px solid #f44336;
  }
  &.color-phys {
    background-color: #e3f2fd;
    border-left: 3px solid #2196f3;
  }
  &.color-math {
    background-color: #e8f5e9;
    border-left: 3px solid #4caf50;
  }
  &.color-other {
    background-color: #f5f5f5;
    border-left: 3px solid #9e9e9e;
  }
}

.empty-course {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
  border-radius: 6px;
  min-height: 60px;

  .empty-text {
    color: #999;
    font-size: 13px;
  }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  color: #333;
  font-size: 16px;
}

/* 周选择弹窗样式 */
.week-picker-popup {
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  padding-bottom: 20px;

  .popup-header {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    position: relative;

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

  .week-list {
    padding: 10px 0;

    .week-item {
      height: 53.5px; // 设置固定高度
      display: flex;
      justify-content: space-between;
      align-items: center; // 确保垂直居中
      padding: 0 15px; // 调整 padding 以适应固定高度，移除上下 padding
      border-bottom: 1px solid #f5f5f5;
      box-sizing: border-box;

      &.active {
        background-color: #f0f7ff;
        color: #4477ee;
      }

      .current-tag {
        font-size: 12px;
        color: #fff;
        background-color: #4477ee;
        padding: 2px 6px;
        border-radius: 10px;
        white-space: nowrap; // 防止标签换行
      }
    }
  }
}
</style>
