<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>
    </view>

    <!-- 可滚动的内容区域 -->
    <view class="scrollable-content">
      <!-- 课程网格列表 -->
      <view class="course-list" v-if="xkkcList && xkkcList.length > 0">
        <view v-for="(xkkc, index) in xkkcList" :key="xkkc.id || index" class="course-item">
          <view class="course-name">{{ xkkc.kcmc }}</view>
          <view class="course-info-item">
            <view class="info-label">上课周期类型：</view>
            <view class="info-data">{{ xkkc.skzqlx }}</view>
          </view>
          <view class="course-info-item">
            <view class="info-label">上课周期：</view>
            <view class="info-data">{{ xkkc.skzqmc }}</view>
          </view>
          <view class="course-info-item">
            <view class="info-label">上课开始时间：</view>
            <view class="info-data">{{ xkkc.skkstime }}</view>
          </view>
          <view class="course-info-item">
            <view class="info-label">上课结束时间：</view>
            <view class="info-data">{{ xkkc.skjstime }}</view>
          </view>
          <view class="course-info-item">
            <view class="info-label">开课地点：</view>
            <view class="info-data">{{ xkkc.kcdd }}</view>
          </view>
          <view class="course-info-item">
            <view class="info-label">上课人数：</view>
            <view class="info-data">{{ xkkc.hasNum || 0 }} | {{ xkkc.maxNum || 0 }}</view>
          </view>
          <view class="course-btn-group">
            <view class="dm-btn" @click.stop="goDm(xkkc)">点名</view>
          </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="showXkFlag" @close="showXkFlag = false" mode="bottom" round="10">
        <view class="xk-selector">
          <view class="selector-header">
            <text class="selector-title">选择俱乐部</text>
            <u-icon name="close" size="20" @click="showXkFlag = false"></u-icon>
          </view>
          <view class="xk-list">
            <view v-for="(xk, index) in xkList" :key="index" class="xk-item" :class="{
              'xk-item-active': xkData.id === xk.id
            }" @click="switchXk(xk)">
              <view class="xk-info">
                <text class="xk-name">{{ xk.xkmc }}</text>
                <text class="xk-type">{{ 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,
  onBeforeUnmount,
  onMounted,
} from "vue";
import { useUserStore } from "@/store/modules/user";
import { useDataStore } from "@/store/modules/data";
import { jsdXkListApi } from "@/api/base/server";
import { dmBeforeMinuteApi } from "@/api/system/config/index";
import dayjs from "dayjs";

const { getJs } = useUserStore();
const { getData, setData } = useDataStore();

const wdNameList = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

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

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

const xkData = ref();

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

// 课程列表数据
const xkkcList = ref<any[]>([]);

const dmBeforeMinute = ref<number>(0);

onMounted(async () => {
  uni.showLoading({
    title: "加载中...",
  });
  await loadCourseList();
	await loadDmBeforeMinute();
	uni.hideLoading();
});

// 加载课程列表
const loadCourseList = async () => {
  const res = await jsdXkListApi({
    jsId: getJs.id
  });
	if (res.resultCode == 1) {
	  if (res.result && res.result.length) {
	    xkList.value = res.result;
	    switchXk(res.result[0]);
	  } else {
	    xkList.value = [];
	    xkData.value = {};
	    xkkcList.value = [];
	  }
	}
};

// 获取点名时间提前分钟数
const loadDmBeforeMinute = async () => {
	const res = await dmBeforeMinuteApi();
	if (res.resultCode == 1) {
		// 将res.result从字符串转换成int的number赋给dmBeforeMinute
    dmBeforeMinute.value = parseInt(res.result);
	}
}

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

// 切换选课
function switchXk(xk: any) {
  xkData.value = xk;
  xkkcList.value = xk.xkkcs;
  showXkFlag.value = false;
	for (let i = 0; i < xk.xkkcs.length; i++) {
		let xkkc = xk.xkkcs[i];
		// 判断周期
		switch (xkkc.skzqlx) {
			case '每天':
				xkkc.skzqmc = "每天";
				break;
			case '每周':
				const daysOfWeek = xkkc.skzq.split(',').map(Number);
				// 从wdNameList读取daysOfWeek对应的周几
				xkkc.skzqmc = daysOfWeek.map((day: number) => wdNameList[day - 1]).join(',');
				break;
			case '每月':
				const daysOfMonth = xkkc.skzq.split(',').map(Number);
				// 从根据编号加
				xkkc.skzqmc = daysOfMonth.map((day: number) => day + "号").join(',');
				break;
		}
	}
  // 显示切换成功提示
  uni.showToast({
    title: `已切换到${xk.xkmc}`,
    icon: "none",
  });
}

// 跳转到点名
const goDm = (xkkc: any) => {
  const now = dayjs();
  let wDay = now.day();
  if (wDay === 0) {
    wDay = 7;
  }
  let mDay = now.date();
  const strDate = now.format('YYYY-MM-DD') + ' ';
	let dmFlag = false;
	let msg = "";
	// 判断周期
	switch (xkkc.skzqlx) {
		case '每天':
			dmFlag = true;
			break;
		case '每周':
			const daysOfWeek = xkkc.skzq.split(',').map(Number);
			dmFlag = daysOfWeek.includes(wDay);
			// 从wdNameList读取daysOfWeek对应的周几
			xkkc.skzqmc = daysOfWeek.map((day: number) => wdNameList[day - 1]).join(',');
			break;
		case '每月':
			const daysOfMonth = xkkc.skzq.split(',').map(Number);
			dmFlag = daysOfMonth.includes(mDay);
			// 从根据编号加
			xkkc.skzqmc = daysOfMonth.map((day: number) => day + "号").join(',');
			break;
	}
	// 判断日期是否合格
	if (dmFlag) {
		// xkkc.skkstime开始时间向前dmBeforeMinute分钟
    const startTime = dayjs(strDate + xkkc.skkstime).subtract(dmBeforeMinute.value, 'minute').format('YYYY-MM-DD HH:mm:ss');
		const endTime = dayjs(strDate + xkkc.skjstime, 'YYYY-MM-DD HH:mm:ss');
		dmFlag = now.isBefore(endTime) && now.isAfter(startTime)
	} else {
		msg = "没到点名日期";
	}
	if (dmFlag) {
		setData(xkkc);
		uni.navigateTo({
			url: `/pages/base/groupTeaching/dmXkkcDetail`,
		});
	} else {
		if (msg === "") {
			msg = "没到点名时间";
		}
		uni.showToast({
		  title: msg,
			icon: 'none',
			duration: 2000
		});
	}
};

// 页面卸载前清除定时器
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;
      }
    }

  }
}

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

.course-list {
  padding: 15px 15px 0 15px;

  .course-item {
    position: relative;
    width: 100%;
    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;
    }

    .course-btn-group {
      display: flex;

      .dm-btn {
        flex: 1 0 1px;
        display: inline-block;
        color: #2879ff;
        font-size: 14px;
      }
    }

    .course-info-item {
      display: flex;
      margin-bottom: 12px;
      font-size: 12px;

      .info-label {
        color: #949AA4;
        flex: 0 0 100px;
      }

      .info-data {
        flex: 1 0 1px;
      }
    }
  }
}


/* 学生选择器弹窗样式 */
.xk-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;
    }
  }

  .xk-list {
    padding: 0 15px;

    .xk-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);
      }

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

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

        .xk-type {
          font-size: 13px;
          color: #303133;
          margin-bottom: 4px;
        }

        .xk-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>
