<template>
  <view class="course-manage-page">
    <!-- 顶部统计 -->
    <view class="stats-section">
      <view class="stat-item">
        <text class="stat-value">{{ stats.total }}</text>
        <text class="stat-label">全部课程</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ stats.active }}</text>
        <text class="stat-label">进行中</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ stats.completed }}</text>
        <text class="stat-label">已完成</text>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view 
        v-for="tab in tabs" 
        :key="tab.id"
        class="filter-tab"
        :class="{ active: currentTab === tab.id }"
        @click="switchTab(tab.id)"
      >
        {{ tab.name }}
      </view>
    </view>

    <!-- 课程列表 -->
    <view class="course-list">
      <view 
        v-for="course in courseList" 
        :key="course.id"
        class="course-card"
        @click="goCourseDetail(course.id)"
      >
        <view class="course-header">
          <text class="course-name">{{ course.courseName }}</text>
          <view class="course-status" :class="'status-' + course.status">
            {{ course.statusText }}
          </view>
        </view>
        
        <view class="course-info">
          <view class="info-row">
            <text class="label">👨‍🎓 学生：</text>
            <text class="value">{{ course.studentName }}</text>
          </view>
          <view class="info-row">
            <text class="label">⏰ 时间：</text>
            <text class="value">{{ course.startTime }}</text>
          </view>
          <view class="info-row">
            <text class="label">📍 地点：</text>
            <text class="value">{{ course.location }}</text>
          </view>
          <view class="info-row">
            <text class="label">💵 费用：</text>
            <text class="value price">¥{{ course.fee }}</text>
          </view>
        </view>

        <view class="course-actions">
          <button 
            v-if="course.status === 'pending'" 
            class="btn-start" 
            size="mini" 
            type="primary"
            @click.stop="startCourse(course.id)"
          >
            开始上课
          </button>
          <button 
            v-if="course.status === 'active'" 
            class="btn-end" 
            size="mini"
            @click.stop="endCourse(course.id)"
          >
            结束课程
          </button>
          <button class="btn-detail" size="mini" @click.stop="goCourseDetail(course.id)">
            查看详情
          </button>
        </view>
      </view>

      <view v-if="courseList.length === 0" class="empty-state">
        <text class="empty-icon">📭</text>
        <text class="empty-text">暂无课程</text>
      </view>
    </view>
  </view>
</template>

<script>
import request from '/utils/request.js'

export default {
  data() {
    return {
      stats: {
        total: 0,
        active: 0,
        completed: 0
      },
      tabs: [
        { id: 'all', name: '全部' },
        { id: 'pending', name: '待开始' },
        { id: 'active', name: '进行中' },
        { id: 'completed', name: '已完成' }
      ],
      currentTab: 'all',
      courseList: []
    }
  },
  
  onLoad() {
    console.log('课程管理页面 onLoad')
    this.loadData()
  },
  
  onShow() {
    console.log('课程管理页面 onShow')
    this.loadData()
  },
  
  methods: {
    async loadData() {
      console.log('loadData 开始执行')
      uni.showLoading({ title: '加载中' })
      try {
        await Promise.all([
          this.loadStats(),
          this.loadCourseList()
        ])
      } finally {
        uni.hideLoading()
      }
    },
    
    async loadStats() {
      try {
        console.log('开始加载统计数据...')
        const res = await request({
          url: '/api/provider/course/list',
          method: 'GET',
          params: { statsOnly: true }
        })
        console.log('统计数据响应:', res)
        if (res.code === 200 && res.data) {
          this.stats = {
            total: res.data.total || 0,
            active: res.data.active || 0,
            completed: res.data.completed || 0
          }
          console.log('统计数据已更新:', this.stats)
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
        this.stats = { total: 0, active: 0, completed: 0 }
      }
    },
    
    async loadCourseList() {
      try {
        console.log('开始加载课程列表...', { currentTab: this.currentTab })
        const res = await request({
          url: '/api/provider/course/list',
          method: 'GET',
          params: {
            status: this.currentTab === 'all' ? null : this.currentTab,
            page: 1,
            size: 20
          }
        })
        console.log('课程列表响应:', res)
        if (res.code === 200 && res.data) {
          this.courseList = res.data.records || []
          console.log('课程列表已更新:', this.courseList.length, '条')
        }
      } catch (error) {
        console.error('加载课程列表失败:', error)
        this.courseList = []
      }
    },
    
    switchTab(tabId) {
      console.log('切换标签:', tabId)
      this.currentTab = tabId
      this.loadCourseList()
    },
    
    goCourseDetail(id) {
      uni.navigateTo({ url: `/pages/provider/course-detail?id=${id}` })
    },
    
    startCourse(id) {
      uni.navigateTo({ url: `/pages/provider/course-start?id=${id}` })
    },
    
    endCourse(id) {
      uni.showModal({
        title: '结束课程',
        content: '确认结束本次课程吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: '处理中...' })
              const result = await request({
                url: '/api/provider/course/end',
                method: 'POST',
                data: { courseId: id }
              })
              uni.hideLoading()
              
              if (result.code === 200) {
                uni.showToast({ title: '课程已结束', icon: 'success' })
                this.loadData()
              } else {
                uni.showToast({ title: result.message || '操作失败', icon: 'none' })
              }
            } catch (error) {
              uni.hideLoading()
              console.error('结束课程失败:', error)
              uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/static/css/common.scss';

.course-manage-page {
  min-height: 100vh;
  background: $bg-color;
}

.stats-section {
  display: flex;
  background: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .stat-item {
    flex: 1;
    text-align: center;
    
    .stat-value {
      display: block;
      font-size: 40rpx;
      font-weight: bold;
      color: $primary-color;
      margin-bottom: 8rpx;
    }
    
    .stat-label {
      display: block;
      font-size: 24rpx;
      color: $text-secondary;
    }
  }
}

.filter-bar {
  display: flex;
  background: #fff;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
  gap: 20rpx;
  
  .filter-tab {
    flex: 1;
    text-align: center;
    padding: 16rpx;
    background: $bg-color;
    border-radius: 8rpx;
    font-size: 26rpx;
    color: $text-color;
    
    &.active {
      background: $primary-color;
      color: #fff;
    }
  }
}

.course-list {
  padding: 0 30rpx 30rpx;
}

.course-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  
  .course-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .course-name {
      font-size: 28rpx;
      font-weight: bold;
      color: $text-color;
    }
    
    .course-status {
      padding: 4rpx 16rpx;
      border-radius: 20rpx;
      font-size: 22rpx;
      
      &.status-pending {
        background: rgba($warning-color, 0.1);
        color: $warning-color;
      }
      
      &.status-active {
        background: rgba($success-color, 0.1);
        color: $success-color;
      }
      
      &.status-completed {
        background: rgba(0, 0, 0, 0.05);
        color: $text-secondary;
      }
    }
  }
  
  .course-info {
    margin-bottom: 16rpx;
    
    .info-row {
      display: flex;
      margin-bottom: 12rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .label {
        font-size: 24rpx;
        color: $text-secondary;
        min-width: 120rpx;
      }
      
      .value {
        flex: 1;
        font-size: 26rpx;
        color: $text-color;
        
        &.price {
          color: $secondary-color;
          font-weight: bold;
        }
      }
    }
  }
  
  .course-actions {
    display: flex;
    gap: 20rpx;
    
    button {
      flex: 1;
      font-size: 26rpx;
    }
    
    .btn-detail {
      background: #fff;
      color: $primary-color;
      border: 1rpx solid $primary-color;
    }
  }
}

.empty-state {
  padding: 120rpx 0;
  text-align: center;
  
  .empty-icon {
    display: block;
    font-size: 100rpx;
    margin-bottom: 20rpx;
    opacity: 0.3;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: $text-secondary;
  }
}
</style>
