<template>
  <view class="add-schedule-container">
    <uni-nav-bar
      title="添加课程安排"
      left-icon="left"
      fixed="true"
      background-color="#292929"
      color="#FFFFFF"
      @clickLeft="goBack"
    ></uni-nav-bar>
    
    <view class="form-container">
      <fui-form>
        <!-- 课程选择 -->
        <fui-form-item label="课程" required>
          <view class="selector-input" @click="showCoursePicker = true">
            <text>{{ selectedCourse ? selectedCourse.course_name : '请选择课程' }}</text>
            <fui-icon name="arrowdown" :size="32" color="#CCCCCC"></fui-icon>
          </view>
          <fui-picker
            :show="showCoursePicker"
            :options="courseOptions"
            valueKey="id"
            textKey="course_name"
            @confirm="onCourseSelect"
            @cancel="showCoursePicker = false"
          ></fui-picker>
        </fui-form-item>
        
        <!-- 班级选择 -->
        <fui-form-item label="班级">
          <view class="selector-input" @click="showClassPicker = true">
            <text>{{ selectedClass ? selectedClass.class_name : '请选择班级（可选）' }}</text>
            <fui-icon name="arrowdown" :size="32" color="#CCCCCC"></fui-icon>
          </view>
          <fui-picker
            :show="showClassPicker"
            :options="classOptions"
            valueKey="id"
            textKey="class_name"
            @confirm="onClassSelect"
            @cancel="showClassPicker = false"
          ></fui-picker>
        </fui-form-item>
        
        <!-- 教练选择 -->
        <fui-form-item label="授课教练" required>
          <view class="selector-input" @click="showCoachPicker = true">
            <text>{{ selectedCoach ? selectedCoach.name : '请选择教练' }}</text>
            <fui-icon name="arrowdown" :size="32" color="#CCCCCC"></fui-icon>
          </view>
          <fui-picker
            :show="showCoachPicker"
            :options="coachOptions"
            valueKey="id"
            textKey="name"
            @confirm="onCoachSelect"
            @cancel="showCoachPicker = false"
          ></fui-picker>
        </fui-form-item>
        
        <!-- 场地选择 -->
        <fui-form-item label="上课场地" required>
          <view class="selector-input" @click="showVenuePicker = true">
            <text>{{ selectedVenue ? selectedVenue.venue_name : '请选择场地' }}</text>
            <fui-icon name="arrowdown" :size="32" color="#CCCCCC"></fui-icon>
          </view>
          <fui-picker
            :show="showVenuePicker"
            :options="venueOptions"
            valueKey="id"
            textKey="venue_name"
            @confirm="onVenueSelect"
            @cancel="showVenuePicker = false"
          ></fui-picker>
        </fui-form-item>
        
        <!-- 日期选择 -->
        <fui-form-item label="上课日期" required>
          <view class="selector-input" @click="showDatePicker = true">
            <text>{{ formData.course_date || '请选择日期' }}</text>
            <fui-icon name="calendar" :size="32" color="#CCCCCC"></fui-icon>
          </view>
          <fui-date-picker
            :show="showDatePicker"
            @confirm="onDateSelect"
            @cancel="showDatePicker = false"
            :value="formData.course_date"
          ></fui-date-picker>
        </fui-form-item>
        
        <!-- 时间选择 -->
        <fui-form-item label="上课时间" required>
          <view class="selector-input" @click="showTimePicker = true">
            <text>{{ formData.time_slot || '请选择时间段' }}</text>
            <fui-icon name="time" :size="32" color="#CCCCCC"></fui-icon>
          </view>
          <fui-picker
            :show="showTimePicker"
            :options="timeSlotOptions"
            valueKey="value"
            textKey="text"
            @confirm="onTimeSelect"
            @cancel="showTimePicker = false"
          ></fui-picker>
        </fui-form-item>
        
        <!-- 容量设置 -->
        <fui-form-item label="课程容量" required>
          <fui-input
            type="number"
            :value="formData.available_capacity"
            placeholder="请输入课程容量"
            @input="formData.available_capacity = $event"
          ></fui-input>
        </fui-form-item>
        
        <!-- 备注信息 -->
        <fui-form-item label="备注">
          <fui-textarea
            :value="formData.remark"
            placeholder="请输入备注信息（可选）"
            @input="formData.remark = $event"
            maxlength="200"
          ></fui-textarea>
        </fui-form-item>
      </fui-form>
      
      <!-- 提交按钮 -->
      <view class="btn-container">
        <fui-button type="primary" @click="submitForm" :loading="submitting">创建课程安排</fui-button>
      </view>
    </view>
  </view>
</template>

<script>
import api from '@/api/apiRoute.js';

export default {
  data() {
    return {
      // 表单数据
      formData: {
        course_id: '',
        class_id: '',
        coach_id: '',
        venue_id: '',
        course_date: '',
        time_slot: '',
        available_capacity: '',
        remark: ''
      },
      
      // 选择器数据
      showCoursePicker: false,
      showClassPicker: false,
      showCoachPicker: false,
      showVenuePicker: false,
      showDatePicker: false,
      showTimePicker: false,
      
      // 选项数据
      courseOptions: [],
      classOptions: [],
      coachOptions: [],
      venueOptions: [],
      timeSlotOptions: [],
      
      // 选中的数据对象
      selectedCourse: null,
      selectedClass: null,
      selectedCoach: null,
      selectedVenue: null,
      
      // 状态标记
      submitting: false,
      
      // 预填充数据
      prefillDate: '',
      prefillTime: '',
      prefillTimeSlot: ''
    };
  },
  
  onLoad(options) {
    // 从路由参数获取预填充数据
    if (options.date) {
      this.prefillDate = options.date;
      this.formData.course_date = options.date;
    }
    
    if (options.time) {
      this.prefillTime = options.time;
    }
    
    if (options.time_slot) {
      this.prefillTimeSlot = options.time_slot;
      this.formData.time_slot = options.time_slot;
    }
    
    // 加载初始数据
    this.loadFilterOptions();
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 加载选项数据
    async loadFilterOptions() {
      uni.showLoading({
        title: '加载数据中...'
      });
      
      try {
        const res = await api.getCourseScheduleFilterOptions();
        
        if (res.code === 1) {
          // 设置课程选项
          this.courseOptions = res.data.courses || [];
          
          // 设置班级选项
          this.classOptions = res.data.classes || [];
          
          // 设置教练选项
          this.coachOptions = res.data.coaches || [];
          
          // 设置场地选项
          this.venueOptions = res.data.venues || [];
          
          // 生成时间段选项
          this.generateTimeSlotOptions();
          
          // 如果有预填充时间段，设置选中的时间段
          if (this.prefillTimeSlot) {
            this.formData.time_slot = this.prefillTimeSlot;
          }
        } else {
          uni.showToast({
            title: res.msg || '加载筛选选项失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载筛选选项失败:', error);
        uni.showToast({
          title: '加载筛选选项失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 生成时间段选项
    generateTimeSlotOptions() {
      const timeSlots = [];
      
      // 早上时间段
      for (let hour = 8; hour < 12; hour++) {
        const startHour = hour.toString().padStart(2, '0');
        const endHour = (hour + 1).toString().padStart(2, '0');
        timeSlots.push({
          value: `${startHour}:00-${endHour}:00`,
          text: `${startHour}:00-${endHour}:00`
        });
      }
      
      // 下午时间段
      for (let hour = 12; hour < 18; hour++) {
        const startHour = hour.toString().padStart(2, '0');
        const endHour = (hour + 1).toString().padStart(2, '0');
        timeSlots.push({
          value: `${startHour}:00-${endHour}:00`,
          text: `${startHour}:00-${endHour}:00`
        });
      }
      
      // 晚上时间段
      for (let hour = 18; hour < 22; hour++) {
        const startHour = hour.toString().padStart(2, '0');
        const endHour = (hour + 1).toString().padStart(2, '0');
        timeSlots.push({
          value: `${startHour}:00-${endHour}:00`,
          text: `${startHour}:00-${endHour}:00`
        });
      }
      
      this.timeSlotOptions = timeSlots;
    },
    
    // 选择器处理方法
    onCourseSelect(e) {
      const index = e.index;
      if (index >= 0 && index < this.courseOptions.length) {
        this.selectedCourse = this.courseOptions[index];
        this.formData.course_id = this.selectedCourse.id;
      }
      this.showCoursePicker = false;
    },
    
    onClassSelect(e) {
      const index = e.index;
      if (index >= 0 && index < this.classOptions.length) {
        this.selectedClass = this.classOptions[index];
        this.formData.class_id = this.selectedClass.id;
      } else {
        this.selectedClass = null;
        this.formData.class_id = '';
      }
      this.showClassPicker = false;
    },
    
    onCoachSelect(e) {
      const index = e.index;
      if (index >= 0 && index < this.coachOptions.length) {
        this.selectedCoach = this.coachOptions[index];
        this.formData.coach_id = this.selectedCoach.id;
      }
      this.showCoachPicker = false;
    },
    
    onVenueSelect(e) {
      const index = e.index;
      if (index >= 0 && index < this.venueOptions.length) {
        this.selectedVenue = this.venueOptions[index];
        this.formData.venue_id = this.selectedVenue.id;
        
        // 如果场地有默认容量，设置容量
        if (this.selectedVenue.capacity) {
          this.formData.available_capacity = this.selectedVenue.capacity;
        }
      }
      this.showVenuePicker = false;
    },
    
    onDateSelect(e) {
      this.formData.course_date = e.result;
      this.showDatePicker = false;
    },
    
    onTimeSelect(e) {
      const index = e.index;
      if (index >= 0 && index < this.timeSlotOptions.length) {
        this.formData.time_slot = this.timeSlotOptions[index].value;
      }
      this.showTimePicker = false;
    },
    
    // 表单验证
    validateForm() {
      if (!this.formData.course_id) {
        uni.showToast({
          title: '请选择课程',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.coach_id) {
        uni.showToast({
          title: '请选择授课教练',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.venue_id) {
        uni.showToast({
          title: '请选择上课场地',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.course_date) {
        uni.showToast({
          title: '请选择上课日期',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.time_slot) {
        uni.showToast({
          title: '请选择上课时间',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.available_capacity) {
        uni.showToast({
          title: '请输入课程容量',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 提交表单
    async submitForm() {
      if (!this.validateForm()) {
        return;
      }
      
      this.submitting = true;
      
      try {
        const res = await api.createCourseSchedule(this.formData);
        
        if (res.code === 1) {
          uni.showToast({
            title: '创建成功',
            icon: 'success'
          });
          
          // 延迟返回，让用户看到成功提示
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || '创建失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('创建课程安排失败:', error);
        uni.showToast({
          title: '创建失败，请重试',
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.add-schedule-container {
  min-height: 100vh;
  background-color: #18181c;
  padding-top: 88rpx;
}

.form-container {
  padding: 30rpx;
}

.selector-input {
  height: 80rpx;
  background-color: #23232a;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #fff;
}

.btn-container {
  margin-top: 60rpx;
  padding: 0 30rpx;
}
</style>