<template>
  <view class="adjust-course-container">
    <uni-nav-bar
      title="调整课程安排"
      left-icon="left"
      fixed="true"
      background-color="#292929"
      color="#FFFFFF"
      @clickLeft="goBack"
    ></uni-nav-bar>
    
    <view class="form-container">
      <view v-if="loading" class="loading-container">
        <fui-loading></fui-loading>
        <text class="loading-text">加载中...</text>
      </view>
      
      <fui-form v-else>
        <!-- 课程信息 -->
        <view class="section-title">当前课程信息</view>
        <view class="course-info-card">
          <view class="info-row">
            <text class="info-label">课程名称：</text>
            <text class="info-value">{{ scheduleInfo.course_name }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">上课日期：</text>
            <text class="info-value">{{ scheduleInfo.course_date }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">上课时间：</text>
            <text class="info-value">{{ scheduleInfo.time_slot }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">授课教练：</text>
            <text class="info-value">{{ scheduleInfo.coach_name }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">上课场地：</text>
            <text class="info-value">{{ scheduleInfo.venue_name }}</text>
          </view>
        </view>
        
        <view class="section-title">调整后信息</view>
        
        <!-- 教练选择 -->
        <fui-form-item label="授课教练">
          <view class="selector-input" @click="showCoachPicker = true">
            <text>{{ selectedCoach ? selectedCoach.name : scheduleInfo.coach_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="上课场地">
          <view class="selector-input" @click="showVenuePicker = true">
            <text>{{ selectedVenue ? selectedVenue.venue_name : scheduleInfo.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="上课日期">
          <view class="selector-input" @click="showDatePicker = true">
            <text>{{ formData.course_date || scheduleInfo.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 || scheduleInfo.course_date"
          ></fui-date-picker>
        </fui-form-item>
        
        <!-- 时间选择 -->
        <fui-form-item label="上课时间">
          <view class="selector-input" @click="showTimePicker = true">
            <text>{{ formData.time_slot || scheduleInfo.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="课程容量">
          <fui-input
            type="number"
            :value="formData.available_capacity || scheduleInfo.available_capacity"
            placeholder="请输入课程容量"
            @input="formData.available_capacity = $event"
          ></fui-input>
        </fui-form-item>
        
        <!-- 调整原因 -->
        <fui-form-item label="调整原因" required>
          <fui-textarea
            :value="formData.adjust_reason"
            placeholder="请输入调整原因"
            @input="formData.adjust_reason = $event"
            maxlength="200"
          ></fui-textarea>
        </fui-form-item>
        
        <!-- 提交按钮 -->
        <view class="btn-container">
          <fui-button type="primary" @click="submitForm" :loading="submitting">确认调整</fui-button>
        </view>
      </fui-form>
    </view>
  </view>
</template>

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

export default {
  data() {
    return {
      // 状态标记
      loading: true,
      submitting: false,
      
      // 课程ID
      scheduleId: null,
      
      // 课程信息
      scheduleInfo: {},
      
      // 表单数据
      formData: {
        schedule_id: '',
        coach_id: '',
        venue_id: '',
        course_date: '',
        time_slot: '',
        available_capacity: '',
        adjust_reason: ''
      },
      
      // 选择器数据
      showCoachPicker: false,
      showVenuePicker: false,
      showDatePicker: false,
      showTimePicker: false,
      
      // 选项数据
      coachOptions: [],
      venueOptions: [],
      timeSlotOptions: [],
      
      // 选中的数据对象
      selectedCoach: null,
      selectedVenue: null
    };
  },
  
  onLoad(options) {
    if (options.id) {
      this.scheduleId = options.id;
      this.formData.schedule_id = options.id;
      this.loadScheduleInfo();
      this.loadFilterOptions();
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 加载课程安排信息
    async loadScheduleInfo() {
      try {
        const res = await api.getCourseScheduleInfo({ schedule_id: this.scheduleId });
        
        if (res.code === 1) {
          this.scheduleInfo = res.data;
          
          // 初始化表单数据
          this.formData.coach_id = this.scheduleInfo.coach_id;
          this.formData.venue_id = this.scheduleInfo.venue_id;
          this.formData.course_date = this.scheduleInfo.course_date;
          this.formData.time_slot = this.scheduleInfo.time_slot;
          this.formData.available_capacity = this.scheduleInfo.available_capacity;
        } else {
          uni.showToast({
            title: res.msg || '获取课程安排信息失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取课程安排信息失败:', error);
        uni.showToast({
          title: '获取课程安排信息失败',
          icon: 'none'
        });
      }
    },
    
    // 加载选项数据
    async loadFilterOptions() {
      try {
        const res = await api.getCourseScheduleFilterOptions();
        
        if (res.code === 1) {
          // 设置教练选项
          this.coachOptions = res.data.coaches || [];
          
          // 设置场地选项
          this.venueOptions = res.data.venues || [];
          
          // 生成时间段选项
          this.generateTimeSlotOptions();
          
          // 找到当前选中的教练和场地
          this.findSelectedOptions();
        } else {
          uni.showToast({
            title: res.msg || '加载筛选选项失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载筛选选项失败:', error);
        uni.showToast({
          title: '加载筛选选项失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 查找当前选中的选项
    findSelectedOptions() {
      // 查找当前教练
      if (this.scheduleInfo.coach_id) {
        this.selectedCoach = this.coachOptions.find(coach => coach.id === this.scheduleInfo.coach_id);
      }
      
      // 查找当前场地
      if (this.scheduleInfo.venue_id) {
        this.selectedVenue = this.venueOptions.find(venue => venue.id === this.scheduleInfo.venue_id);
      }
    },
    
    // 生成时间段选项
    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;
    },
    
    // 选择器处理方法
    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.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() {
      // 检查是否有任何修改
      const hasChanges = this.formData.coach_id !== this.scheduleInfo.coach_id ||
                          this.formData.venue_id !== this.scheduleInfo.venue_id ||
                          this.formData.course_date !== this.scheduleInfo.course_date ||
                          this.formData.time_slot !== this.scheduleInfo.time_slot ||
                          this.formData.available_capacity !== this.scheduleInfo.available_capacity;
      
      if (!hasChanges) {
        uni.showToast({
          title: '未进行任何修改',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.formData.adjust_reason) {
        uni.showToast({
          title: '请输入调整原因',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 提交表单
    async submitForm() {
      if (!this.validateForm()) {
        return;
      }
      
      this.submitting = true;
      
      try {
        const res = await api.updateCourseSchedule(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>
.adjust-course-container {
  min-height: 100vh;
  background-color: #18181c;
  padding-top: 88rpx;
}

.form-container {
  padding: 30rpx;
}

.loading-container {
  height: 200rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #29d3b4;
  margin: 30rpx 0 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1px solid #333;
}

.course-info-card {
  background-color: #23232a;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
}

.info-row {
  display: flex;
  margin-bottom: 16rpx;
  font-size: 28rpx;
}

.info-label {
  color: #999;
  width: 160rpx;
  flex-shrink: 0;
}

.info-value {
  color: #fff;
  flex: 1;
}

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