<template>
  <view class="interest-course">
    <!-- 选课信息头部 - 固定部分 -->
    <view class="selection-header">
      <view class="header-content">
        <view class="title-section" @click="clickShowXkSelector">
          <view class="title">
            <text v-if="xkData && xkData.xkmc">{{ xkData.xkmc }}</text>
            <text v-else>选课信息</text>
          </view>
          <view class="switch-btn" v-if="xkList.length > 1">切换</view>
        </view>
        <!-- 学生选择部分 -->
        <view class="student-selector-bar" @click="clickShowXsSelector">
          <view class="user-avatar">
            <image
              :src="curXs.xstxUrl || '/static/base/home/11222.png'"
              class="w-full h-full"
            ></image>
          </view>
          <view class="student-info">
            <text class="student-name">{{ curXs.xm }}</text>
            <text class="student-class"
              >{{ curXs.njmc }} {{ curXs.bjmc }}</text
            >
          </view>
          <view class="switch-btn" v-if="xsList.length > 1">切换</view>
        </view>
      </view>
    </view>

    <!-- 可滚动的内容区域 -->
    <view class="scrollable-content">
      <!-- 课程网格列表 -->
      <view class="course-grid" v-if="courseListData.length > 0">
        <view
          v-for="(course, index) in courseListData"
          :key="course.id || index"
          class="course-item"
          :class="{ selected: course.isSelected }"
        >
          <view class="course-name">{{ course.kcmc }}</view>
          <view class="register-info">
            <text>上课人数：</text>
            <text class="register-count">{{ course.ybmr }}</text>
          </view>
          <view class="detail-btn" @click.stop="viewCourseDetail(course)"
            >详情</view
          >
          <view v-if="course.isSelected" class="selected-mark">
            <uni-icons
              type="checkbox-filled"
              color="#3FBF72"
              size="22"
            ></uni-icons>
          </view>
        </view>
      </view>

      <!-- 暂无数据提示 -->
      <view v-else class="empty-course-list">
        <view class="empty-icon">
          <u-icon name="list" size="50" color="#C8C9CC"></u-icon>
        </view>
        <view class="empty-text">暂无课程数据</view>
      </view>
    </view>

    <view>
      <!-- 学生选择弹窗 -->
      <u-popup
        :show="showXsFlag"
        @close="showXsFlag = false"
        mode="bottom"
        round="10"
      >
        <view class="student-selector">
          <view class="selector-header">
            <text class="selector-title">选择学生</text>
            <u-icon
              name="close"
              size="20"
              @click="showXsFlag = false"
            ></u-icon>
          </view>
          <view class="student-list">
            <view
              v-for="(xs, index) in xsList"
              :key="index"
              class="student-item"
              :class="{
                'student-item-active': curXs.id === xs.id
              }"
              @click="switchXs(xs)"
            >
              <view class="student-avatar">
                <image
                  :src="xs.xstxUrl || '/static/base/home/11222.png'"
                  class="w-full h-full"
                ></image>
              </view>
              <view class="student-info">
                <text class="student-name">{{ xs.xm }}</text>
                <text class="student-class"
                  >{{ xs.njmc }} {{ xs.bjmc }}</text
                >
              </view>
              <u-icon
                v-if="curXs.id === xs.id"
                name="checkmark"
                color="#409EFF"
                size="20"
              ></u-icon>
            </view>
          </view>
        </view>
      </u-popup>
    </view>
		
		<view>
			<!-- 俱乐部选择弹窗 -->
			<u-popup
				:show="showXkFlag"
				@close="showXkFlag = false"
				mode="bottom"
				round="10"
			>
				<view class="student-selector">
					<view class="selector-header">
						<text class="selector-title">选择俱乐部</text>
						<u-icon
							name="close"
							size="20"
							@click="showXkFlag = false"
						></u-icon>
					</view>
					<view class="student-list">
						<view
							v-for="(xk, index) in xkList"
							:key="index"
							class="student-item"
							:class="{
								'student-item-active': xkData.id === xk.id
							}"
							@click="switchXk(xk)"
						>
							<view class="student-info">
								<text class="student-name">{{ xk.xkmc }}</text>
							</view>
							<u-icon
								v-if="xkData.id === xk.id"
								name="checkmark"
								color="#409EFF"
								size="20"
							></u-icon>
						</view>
					</view>	
				</view>
			</u-popup>
		</view>
			
	</view>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  reactive,
  onBeforeUnmount,
  watch,
  onMounted,
} from "vue";
import { useUserStore } from "@/store/modules/user";
import { useDataStore } from "@/store/modules/data";
import { xkListApi, xsXkListApi } from "@/api/base/server";
import dayjs from "dayjs";

const { getUser, getCurXs } = useUserStore();
const { getData, setKcData, setData } = useDataStore();
const { sign_file } = getData;

// 学生列表数据
const xsList = computed(() => {
  return getUser.xsList;
});

const curXs = ref<any>({});

// 控制选择器显示状态
const showXsFlag = ref(false);
const showXkFlag = ref(false);

if (xsList.value.length > 1) {
  showXsFlag.value = true;
}

const xkList = ref<any>([]);

const xkData = ref();
const kcStatus = ref(false);

const courseInfo = ref<any>({});

onMounted(() => {
	curXs.value = getCurXs;
	// 先加载课程列表，不立即检查报名状态
	uni.showLoading({
		title: "加载中...",
	});
	loadCourseList(curXs.value);
});

// 加载课程列表
const loadCourseList = (xs: any) => {
  if (!xs) {
    uni.hideLoading();
    return;
  }

  xsXkListApi({
		xsId: xs.id,
		njId: xs.njId,
    xklxId: "816059832",
  })
    .then((res) => {
      if (res.resultCode == 1) {
        if (res.result && res.result.length) {
					xkList.value = res.result;
          xkData.value = res.result[0];
        } else {
					xkList.value = [];
					xkData.value = {};
        }
        uni.hideLoading();
      }
    })
    .catch(() => {
      uni.hideLoading();
    });
};

// 显示学生选择器
function clickShowXsSelector() {
  if (xsList.value.length > 1) {
    showXsFlag.value = true;
  }
}

// 显示学生选择器
function clickShowXkSelector() {
  if (xkList.value.length > 1) {
    showXkFlag.value = true;
  }
}

// 切换学生
function switchXs(xs: any) {
  curXs.value = xs;
  showXsFlag.value = false;

  // 显示加载中
  uni.showLoading({
    title: "加载中...",
  });

  // 显示切换成功提示
  uni.showToast({
    title: `已切换到${xs.xm}`,
    icon: "none",
  });

  // 先加载当前学生的课程列表，课程数据加载完成后会自动检查报名状态
  loadCourseList(xs);
}

// 切换学生
function switchXk(xk: any) {
  xkData.value = xk;
  showXkFlag.value = false;

  // 显示切换成功提示
  uni.showToast({
    title: `已切换到${xk.xkmc}`,
    icon: "none",
  });
}

// 从课程数据中提取课程列表
const displayCourseList = computed(() => {
  if (
    !xkData.value ||
    !xkData.value.xkkcs ||
    !Array.isArray(xkData.value.xkkcs)
  ) {
    return [];
  }

  // 获取本地存储的已选课程ID数组
  const selectedCourseIds = uni.getStorageSync("selectedCourseIds") || [];

  // 为课程添加选中状态属性
  return xkData.value.xkkcs.map((course: any) => ({
    ...course,
    isSelected: selectedCourseIds.includes(course.id),
  }));
});

// 可修改的课程列表数据
const courseListData = ref<any[]>([]);

// 计算已选择的课程数量
const selectedCoursesCount = computed(() => {
  return courseListData.value.filter((course: any) => course.isSelected).length;
});

// 监听计算属性变化，更新可修改的数据
watch(
  displayCourseList,
  (newVal) => {
    courseListData.value = JSON.parse(JSON.stringify(newVal));

    // 初始化时，将已选课程的全部信息存入courseInfo
    const selectedCourseIds = uni.getStorageSync("selectedCourseIds") || [];
    if (selectedCourseIds.length > 0) {
      const selectedCourses = newVal.filter((course: any) =>
        selectedCourseIds.includes(course.id)
      );
      courseInfo.value = selectedCourses;
    }
  },
  { immediate: true }
);

// 查看课程详情
const viewCourseDetail = (course: any) => {
  setKcData(course);
  uni.navigateTo({
    url: `/pages/base/course-selection/detail`,
  });
};

// 页面卸载前清除定时器
onBeforeUnmount(() => {
});
</script>

<style lang="scss" scoped>
.interest-course {
  min-height: 100%;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  height: 44px;
  background-color: #fff;

  .nav-left {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
  }

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

  .nav-right {
    width: 40px;
    display: flex;
    justify-content: flex-end;
  }
}

.selection-header {
  background: linear-gradient(135deg, #4a90e2, #2879ff);
  padding: 20px 15px;
  color: #fff;
  border-radius: 0 0 15px 15px;
  box-shadow: 0 4px 12px rgba(40, 121, 255, 0.2);
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;

  .header-content {
    display: flex;
    flex-direction: column;
    gap: 15px;

    .title-section {
      display: flex;
      align-items: center;
      .title {
				flex: 1 0 1px;
        font-size: 24px;
        font-weight: bold;
      }

      .subtitle {
        font-size: 14px;
        opacity: 0.8;
      }
			
			.switch-btn {
			  padding: 5px 15px;
			  background-color: rgba(255, 255, 255, 0.2);
			  color: #fff;
			  border-radius: 15px;
			  font-size: 15px;
			}
    }

    // 学生选择栏样式
    .student-selector-bar {
      display: flex;
      align-items: center;
      background-color: rgba(255, 255, 255, 0.1);
      border-radius: 10px;
      padding: 10px;

      .user-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #fff;
        overflow: hidden;
        margin-right: 10px;
      }

      .student-info {
        flex: 1;
        display: flex;
        flex-direction: column;

        .student-name {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 2px;
        }

        .student-class {
          font-size: 12px;
          opacity: 0.8;
        }
      }

      .switch-btn {
        padding: 4px 12px;
        background-color: rgba(255, 255, 255, 0.2);
        color: #fff;
        border-radius: 20px;
        font-size: 13px;
      }
    }

    .countdown-section {
      .countdown-title {
        font-size: 14px;
        margin-bottom: 8px;
      }

      .countdown-timer {
        display: flex;
        align-items: center;

        .time-block {
          background-color: rgba(255, 255, 255, 0.2);
          border-radius: 6px;
          min-width: 40px;
          padding: 5px 8px;
          text-align: center;

          .time-value {
            font-size: 20px;
            font-weight: bold;
            display: block;
          }

          .time-unit {
            font-size: 12px;
            opacity: 0.9;
          }
        }

        .time-separator {
          font-size: 20px;
          font-weight: bold;
          margin: 0 5px;
        }
      }
    }
  }
}

// 可滚动内容区域样式
.scrollable-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch; // 增强iOS滚动体验
}

.course-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 15px 15px 0 15px;

  .course-item {
    position: relative;
    width: calc(50% - 10px);
    margin-bottom: 15px;
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    box-sizing: border-box;
    border: 1px solid transparent;
    transition: all 0.3s ease;

    &:nth-child(odd) {
      margin-right: 10px;
    }

    &:nth-child(even) {
      margin-left: 10px;
    }

    &.selected {
      border: 1px solid #3fbf72;
      background-color: rgba(63, 191, 114, 0.05);
      box-shadow: 0 2px 8px rgba(63, 191, 114, 0.15);
    }

    .course-name {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 10px;
    }

    .register-info {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;

      .register-count {
        color: #2879ff;
      }
    }

    .detail-btn {
      display: inline-block;
      color: #2879ff;
      font-size: 14px;
    }

    .selected-mark {
      position: absolute;
      top: -6px;
      right: -6px;
    }
  }
}

.register-btn-container {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background-color: #fff;
  z-index: 10;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

  .register-btn {
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-color: #2879ff;
    color: #fff;
    border-radius: 25px;
    font-size: 16px;
    font-weight: 500;
  }
}

/* 学生选择器弹窗样式 */
.student-selector {
  background-color: #ffffff;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  padding-bottom: 20px;

  .selector-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #f2f2f2;

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

  .student-list {
    padding: 0 15px;

    .student-item {
      display: flex;
      align-items: center;
      padding: 15px 0;
      border-bottom: 1px solid #f2f2f2;

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

      &-active {
        background-color: rgba(64, 158, 255, 0.05);
      }

      .student-avatar {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        background-color: #f0f0f0;
        overflow: hidden;
        flex-shrink: 0;
      }

      .student-info {
        flex: 1;
        margin-left: 12px;

        .student-name {
          font-size: 15px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
        }

        .student-class {
          font-size: 13px;
          color: #606266;
        }
      }
    }
  }
}

/* 全局图片样式 */
.w-full {
  width: 100%;
}

.h-full {
  height: 100%;
}

// 暂无数据样式
.empty-course-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;

  .empty-icon {
    margin-bottom: 20px;
    background-color: #f5f6f7;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .empty-text {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 8px;
  }

  .empty-desc {
    font-size: 14px;
    color: #909399;
    max-width: 80%;
    line-height: 1.5;
  }
}

/* 选课已结束样式 */
.enrollment-ended {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  padding: 12px 15px;
  font-size: 16px;
  font-weight: 500;
  color: #fff;
  gap: 8px;
}
</style>
