<template>
  <view class="schedule-detail-container">
    <!-- 页面加载状态 -->
    <view class="loading-container" v-if="loading">
      <fui-loading></fui-loading>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态显示 -->
    <view class="error-container" v-else-if="error">
      <text class="error-text">{{ errorMessage }}</text>
      <view class="retry-btn" @click="fetchScheduleDetail">
        <text>重试</text>
      </view>
    </view>

    <view class="schedule-content" v-else>
      <!-- 课程基本信息 -->
      <view class="schedule-header">
        <view class="course-title">
          <text>{{ scheduleDetail.title || '暂无课程名称' }}</text>
          <text class="status-tag" :class="statusClass">{{ statusText }}</text>
        </view>
        <view class="course-time">{{ scheduleDetail.course_date || '' }} {{ scheduleDetail.time_slot || '' }}</view>
      </view>

      <!-- 课程详细信息 -->
      <view class="info-card">
        <view class="info-item">
          <text class="info-label">授课教师:</text>
          <text class="info-value">{{ scheduleDetail.coach?.name || '未设置' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">教室:</text>
          <text class="info-value">{{ scheduleDetail.venue?.venue_name || '未设置' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">当前人数:</text>
          <text class="info-value">{{ studentCount }}/{{ scheduleDetail.venue?.capacity || 0 }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">课程内容:</text>
          <text class="info-value">{{ scheduleDetail.content || '未设置上课内容' }}</text>
        </view>
        <view class="info-item" v-if="scheduleDetail.remark">
          <text class="info-label">备注:</text>
          <text class="info-value">{{ scheduleDetail.remark }}</text>
        </view>
      </view>

      <!-- 学员列表 -->
      <view class="student-list-section">
        <view class="section-title">
          <text>学员列表</text>
        </view>
        <view class="student-list" v-if="scheduleDetail.student_courses && scheduleDetail.student_courses.length > 0">
          <view class="student-item" v-for="(student, index) in scheduleDetail.student_courses" :key="index">
            <view class="student-avatar">
              <image :src="$util.img(student.avatar)" mode="aspectFill"></image>
            </view>
            <view class="student-info">
              <text class="student-name">{{ student.name }}</text>
              <text class="student-status" :class="{'signed': student.status === 'signed'}">
                {{ student.status === 'signed' ? '已签到' : '未签到' }}
              </text>
            </view>
          </view>
        </view>
        <view class="empty-list" v-else>
          <text>暂无学员参与此课程</text>
        </view>
      </view>

      <!-- 底部按钮区域 -->
      <view class="footer-actions">
        <view class="action-btn adjust-btn" @click="handleAdjustClass">
          <text>调课</text>
        </view>
        <view class="action-btn sign-btn" @click="handleSignIn">
          <text>点名</text>
        </view>
      </view>
    </view>

    <!-- 引入课程详情组件 -->
    <schedule-detail 
      :visible="showDetailPopup"
      :scheduleId="scheduleId"
      @update:visible="showDetailPopup = $event"
      @sign-in="onSignIn"
      @adjust-class="onAdjustClass"
    ></schedule-detail>
  </view>
</template>

<script>
import apiRoute from '@/api/apiRoute.js'
import ScheduleDetail from '@/components/schedule/ScheduleDetail.vue'

export default {
  components: {
    ScheduleDetail
  },
  data() {
    return {
      scheduleId: '', // 课程安排ID
      loading: false,
      error: false,
      errorMessage: '加载失败，请重试',
      scheduleDetail: {},
      studentCount: 0,
      showDetailPopup: false
    }
  },
  computed: {
    // 课程状态文本和样式
    statusText() {
      if (!this.scheduleDetail.student_courses || !this.scheduleDetail.student_courses[0]) {
        return '未开始';
      }
      
      const now = new Date();
      const startDate = this.scheduleDetail.student_courses[0].start_date ? 
        new Date(this.scheduleDetail.student_courses[0].start_date) : null;
      const endDate = this.scheduleDetail.student_courses[0].end_date ? 
        new Date(this.scheduleDetail.student_courses[0].end_date) : null;
      
      if (startDate && endDate) {
        if (now >= startDate && now <= endDate) {
          return '上课中';
        } else if (now > endDate) {
          return '已结束';
        } else if (now < startDate) {
          return '未开始';
        }
      }
      
      return '未开始';
    },
    statusClass() {
      switch (this.statusText) {
        case '上课中':
          return 'status-in-progress';
        case '已结束':
          return 'status-ended';
        case '未开始':
        default:
          return 'status-not-started';
      }
    }
  },
  onLoad(options) {
    if (options.id) {
      this.scheduleId = options.id;
      this.fetchScheduleDetail();
    } else {
      this.error = true;
      this.errorMessage = '未找到课程安排ID';
    }
  },
  methods: {
    // 获取课程详情
    async fetchScheduleDetail() {
      if (!this.scheduleId) {
        this.error = true;
        this.errorMessage = '课程ID不能为空';
        return;
      }
      
      this.loading = true;
      this.error = false;
      
      try {
        // 使用新接口获取课程安排详情
        const res = await apiRoute.getCourseScheduleInfo({
          id: this.scheduleId
        });
        
        if (res.code === 1 && res.data) {
          this.scheduleDetail = res.data;
          // 计算学生数量
          this.studentCount = this.scheduleDetail.student_courses ? 
            this.scheduleDetail.student_courses.length : 0;
        } else {
          // 如果新接口不可用，尝试使用旧接口
          const fallbackRes = await apiRoute.courseInfo({
            id: this.scheduleId
          });
          
          if (fallbackRes.code === 1 && fallbackRes.data) {
            this.scheduleDetail = fallbackRes.data;
            this.studentCount = this.scheduleDetail.student_courses ? 
              this.scheduleDetail.student_courses.length : 0;
          } else {
            throw new Error(res.msg || fallbackRes.msg || '获取课程详情失败');
          }
        }
      } catch (error) {
        console.error('获取课程详情失败:', error);
        this.error = true;
        this.errorMessage = error.message || '获取课程详情失败，请重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 点名功能
    handleSignIn() {
      // 如果课程已结束，显示提示
      if (this.statusText === '已结束') {
        uni.showToast({
          title: '课程已结束，无法点名',
          icon: 'none'
        });
        return;
      }
      
      // 如果没有学生，显示提示
      if (!this.scheduleDetail.student_courses || this.scheduleDetail.student_courses.length === 0) {
        uni.showToast({
          title: '暂无学员，无法点名',
          icon: 'none'
        });
        return;
      }
      
      // 显示点名界面或跳转至点名页面
      uni.navigateTo({
        url: `/pages/coach/schedule/sign_in?id=${this.scheduleId}`
      });
    },
    
    // 调课功能
    handleAdjustClass() {
      // 如果课程已结束，显示提示
      if (this.statusText === '已结束') {
        uni.showToast({
          title: '课程已结束，无法调课',
          icon: 'none'
        });
        return;
      }
      
      // 跳转至调课页面
      uni.navigateTo({
        url: `/pages/coach/schedule/adjust_course?id=${this.scheduleId}`
      });
    },

    // 从弹窗组件中点名处理
    onSignIn(data) {
      console.log('处理点名:', data);
      uni.navigateTo({
        url: `/pages/coach/schedule/sign_in?id=${data.scheduleId}`
      });
    },

    // 从弹窗组件中调课处理
    onAdjustClass(data) {
      console.log('处理调课:', data);
      uni.navigateTo({
        url: `/pages/coach/schedule/adjust_course?id=${data.scheduleId}`
      });
    },

    // 显示弹窗
    showPopup() {
      this.showDetailPopup = true;
    }
  }
}
</script>

<style lang="less" scoped>
.schedule-detail-container {
  background-color: #292929;
  min-height: 100vh;
  padding-bottom: 140rpx; // 为底部按钮留出空间
}

.loading-container, .error-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-text, .error-text {
  margin-top: 30rpx;
  font-size: 28rpx;
  color: #ccc;
}

.retry-btn {
  margin-top: 30rpx;
  padding: 12rpx 30rpx;
  background-color: #29d3b4;
  border-radius: 8rpx;
  color: #fff;
  font-size: 24rpx;
}

.schedule-content {
  padding: 30rpx;
}

.schedule-header {
  margin-bottom: 30rpx;
}

.course-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  margin-bottom: 16rpx;
}

.status-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 30rpx;
}

.status-in-progress {
  background-color: #FAD24E;
  color: #333;
}

.status-ended {
  background-color: #e2e2e2;
  color: #333;
}

.status-not-started {
  background-color: #1cd188;
  color: #fff;
}

.course-time {
  font-size: 28rpx;
  color: #FAD24E;
  margin-bottom: 30rpx;
}

.info-card {
  background-color: #434544;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 30rpx;
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
}

.info-label {
  width: 160rpx;
  font-size: 26rpx;
  color: #ccc;
}

.info-value {
  flex: 1;
  font-size: 26rpx;
  color: #fff;
}

.student-list-section {
  background-color: #434544;
  border-radius: 16rpx;
  padding: 24rpx;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16rpx;
  border-bottom: 1px solid #555;
  margin-bottom: 20rpx;
}

.section-title text {
  font-size: 28rpx;
  color: #fff;
}

.student-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.student-item {
  display: flex;
  align-items: center;
}

.student-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  background-color: #555;
  margin-right: 20rpx;
}

.student-avatar image {
  width: 100%;
  height: 100%;
}

.student-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.student-name {
  font-size: 28rpx;
  color: #fff;
}

.student-status {
  font-size: 24rpx;
  color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
}

.student-status.signed {
  color: #1cd188;
  background: rgba(28, 209, 136, 0.1);
}

.empty-list {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
  background-color: #292929;
  border-top: 1px solid #434544;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.adjust-btn {
  background-color: #555;
  color: #fff;
}

.sign-btn {
  background-color: #29d3b4;
  color: #fff;
}
</style>