<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级编号" prop="classCode">
        <el-input
          v-model="queryParams.classCode"
          placeholder="请输入班级编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教师姓名" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入教师姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.edu_course_class_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['education:courseClass:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['education:courseClass:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['education:courseClass:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="multiple"
          @click="handleBatchPublish"
          v-hasPermi="['education:courseClass:publish']"
        >批量发布</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['education:courseClass:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseClassList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班级编号" align="center" prop="classCode" />
      <el-table-column label="课程编码" align="center" prop="courseCode" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="教师姓名" align="center" prop="teacherName" />
      <el-table-column label="学期名称" align="center" prop="semesterName" />
      <el-table-column label="容量" align="center" prop="capacity" />
      <el-table-column label="已选人数" align="center" prop="enrolledCount">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enrolledCount >= scope.row.capacity ? 'danger' : 'success'">
            {{ scope.row.enrolledCount || 0 }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="选课率" align="center">
        <template slot-scope="scope">
          <el-progress 
            :percentage="Math.round((scope.row.enrolledCount || 0) / scope.row.capacity * 100)"
            :color="getProgressColor(scope.row.enrolledCount, scope.row.capacity)"
            :stroke-width="6"
          />
        </template>
      </el-table-column>
      <el-table-column label="上课时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.weekday }} {{ scope.row.timeSlot }}</span>
        </template>
      </el-table-column>
      <el-table-column label="教室" align="center" prop="classroomName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.edu_course_class_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-dropdown size="mini">
            <el-button size="mini" type="primary">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                icon="el-icon-edit"
                @click.native="handleUpdate(scope.row)"
                v-hasPermi="['education:courseClass:edit']"
              >修改</el-dropdown-item>
              <el-dropdown-item 
                icon="el-icon-time"
                @click.native="handleSchedule(scope.row)"
                v-hasPermi="['education:schedule:list']"
              >节次安排</el-dropdown-item>
              <el-dropdown-item 
                v-if="scope.row.status == '0'"
                icon="el-icon-video-play"
                @click.native="handlePublish(scope.row)"
                v-hasPermi="['education:courseClass:publish']"
              >发布</el-dropdown-item>
              <el-dropdown-item 
                v-if="scope.row.status == '1'"
                icon="el-icon-setting"
                @click.native="handleAdjustCapacity(scope.row)"
                v-hasPermi="['education:courseClass:capacity']"
              >调整容量</el-dropdown-item>
              <el-dropdown-item 
                v-if="scope.row.status == '1'"
                icon="el-icon-circle-close"
                @click.native="handleStopEnrollment(scope.row)"
                v-hasPermi="['education:courseClass:edit']"
              >停止选课</el-dropdown-item>
              <el-dropdown-item 
                v-if="scope.row.status == '1' || scope.row.status == '2'"
                icon="el-icon-finished"
                @click.native="handleFinish(scope.row)"
                v-hasPermi="['education:courseClass:edit']"
              >结课</el-dropdown-item>
              <el-dropdown-item 
                icon="el-icon-delete"
                @click.native="handleDelete(scope.row)"
                v-hasPermi="['education:courseClass:remove']"
              >删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改开课计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基础信息选择 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请选择课程" filterable style="width: 100%">
                <el-option
                  v-for="course in courseOptions"
                  :key="course.courseId"
                  :label="`${course.courseName}(${course.courseCode})`"
                  :value="course.courseId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学期" prop="semesterId">
              <el-select v-model="form.semesterId" placeholder="请选择学期" style="width: 100%">
                <el-option
                  v-for="semester in semesterOptions"
                  :key="semester.semesterId"
                  :label="semester.semesterName"
                  :value="semester.semesterId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="授课教师" prop="teacherId">
              <el-select v-model="form.teacherId" placeholder="请选择教师" filterable style="width: 100%">
                <el-option
                  v-for="teacher in teacherOptions"
                  :key="teacher.teacherId"
                  :label="`${teacher.realName}(${teacher.teacherNo})`"
                  :value="teacher.teacherId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="授课教室" prop="classroomId">
              <el-select v-model="form.classroomId" placeholder="请选择教室" clearable style="width: 100%">
                <el-option
                  v-for="classroom in classroomOptions"
                  :key="classroom.classroomId"
                  :label="classroom.classroomName"
                  :value="classroom.classroomId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 班级配置信息 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="班级编号" prop="classCode">
              <el-input v-model="form.classCode" placeholder="请输入班级编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="容量上限" prop="capacity">
              <el-input-number v-model="form.capacity" :min="1" :max="300" placeholder="请输入容量上限" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选课人数上限" prop="enrollLimit">
              <el-input-number v-model="form.enrollLimit" :min="0" placeholder="0表示同容量上限" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已选人数" prop="enrolledCount">
              <el-input-number v-model="form.enrolledCount" :min="0" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选课开始时间" prop="enrollStartTime">
              <el-date-picker
                v-model="form.enrollStartTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择选课开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选课结束时间" prop="enrollEndTime">
              <el-date-picker
                v-model="form.enrollEndTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择选课结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开课日期" prop="teachStartDate">
              <el-date-picker
                v-model="form.teachStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择开课日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结课日期" prop="teachEndDate">
              <el-date-picker
                v-model="form.teachEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择结课日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上课星期" prop="weekday">
              <el-select v-model="form.weekday" placeholder="请选择上课星期">
                <el-option label="周一" value="周一" />
                <el-option label="周二" value="周二" />
                <el-option label="周三" value="周三" />
                <el-option label="周四" value="周四" />
                <el-option label="周五" value="周五" />
                <el-option label="周六" value="周六" />
                <el-option label="周日" value="周日" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上课节次" prop="timeSlot">
              <el-select v-model="form.timeSlot" placeholder="请选择上课节次">
                <el-option label="第1-2节" value="第1-2节" />
                <el-option label="第3-4节" value="第3-4节" />
                <el-option label="第5-6节" value="第5-6节" />
                <el-option label="第7-8节" value="第7-8节" />
                <el-option label="第9-10节" value="第9-10节" />
                <el-option label="第11-12节" value="第11-12节" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 调整容量对话框 -->
    <el-dialog title="调整容量" :visible.sync="capacityOpen" width="400px" append-to-body>
      <el-form ref="capacityForm" :model="capacityForm" :rules="capacityRules" label-width="100px">
        <el-form-item label="当前容量" prop="currentCapacity">
          <el-input v-model="capacityForm.currentCapacity" :disabled="true" />
        </el-form-item>
        <el-form-item label="已选人数" prop="enrolledCount">
          <el-input v-model="capacityForm.enrolledCount" :disabled="true" />
        </el-form-item>
        <el-form-item label="新容量" prop="newCapacity">
          <el-input-number 
            v-model="capacityForm.newCapacity" 
            :min="capacityForm.enrolledCount" 
            :max="500"
            placeholder="请输入新容量" 
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCapacityForm">确 定</el-button>
        <el-button @click="cancelCapacity">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 节次安排对话框 -->
    <el-dialog title="节次安排" :visible.sync="scheduleOpen" width="900px" append-to-body>
      <div v-if="scheduleData.length > 0">
        <el-table :data="scheduleData" border>
          <el-table-column label="星期" align="center" prop="weekdayName" />
          <el-table-column label="节次" align="center" prop="periodName" />
          <el-table-column label="上课周次" align="center" prop="weeks" />
          <el-table-column label="教室" align="center" prop="classroomName" />
          <el-table-column label="备注" align="center" prop="remark" />
        </el-table>
      </div>
      <div v-else class="no-data">
        <el-empty description="暂无节次安排数据"></el-empty>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listCourseClass, 
  getCourseClass, 
  delCourseClass, 
  addCourseClass, 
  updateCourseClass, 
  publishCourseClass,
  batchPublishCourseClass,
  stopEnrollment,
  finishCourse,
  adjustCapacity
} from "@/api/education/courseClass"
import { getScheduleByClassId } from "@/api/education/schedule"
import { listSemester } from "@/api/education/semester"
import { getCourseOptions, getTeacherOptions, getClassroomOptions } from "@/api/education/options"

export default {
  name: "CourseClass",
  dicts: ['edu_course_class_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 开课计划表格数据
      courseClassList: [],
      // 选项数据
      courseOptions: [],
      semesterOptions: [],
      teacherOptions: [],
      classroomOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 容量调整对话框
      capacityOpen: false,
      // 节次安排对话框
      scheduleOpen: false,
      // 节次安排数据
      scheduleData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseId: null,
        semesterId: null,
        teacherId: null,
        classCode: null,
        capacity: null,
        enrollLimit: null,
        enrolledCount: null,
        classroomId: null,
        enrollStartTime: null,
        enrollEndTime: null,
        teachStartDate: null,
        teachEndDate: null,
        weekday: null,
        timeSlot: null,
        status: null,
        courseName: null,
        courseCode: null,
        teacherName: null,
        semesterName: null
      },
      // 表单参数
      form: {},
      // 容量调整表单
      capacityForm: {},
      // 表单校验
      rules: {
        courseId: [
          { required: true, message: "课程不能为空", trigger: "change" }
        ],
        semesterId: [
          { required: true, message: "学期不能为空", trigger: "change" }
        ],
        teacherId: [
          { required: true, message: "授课教师不能为空", trigger: "change" }
        ],
        classCode: [
          { required: true, message: "班级编号不能为空", trigger: "blur" }
        ],
        capacity: [
          { required: true, message: "容量上限不能为空", trigger: "blur" }
        ]
      },
      // 容量调整校验
      capacityRules: {
        newCapacity: [
          { required: true, message: "新容量不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.loadOptions();
  },
  methods: {
    /** 查询开课计划列表 */
    getList() {
      this.loading = true;
      listCourseClass(this.queryParams).then(response => {
        this.courseClassList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取课程选项 */
    getCourseOptions() {
      getCourseOptions().then(response => {
        this.courseOptions = response.data;
      });
    },
    /** 获取学期选项 */
    getSemesterOptions() {
      listSemester().then(response => {
        this.semesterOptions = response.rows;
      });
    },
    /** 获取教师选项 */
    getTeacherOptions() {
      getTeacherOptions().then(response => {
        this.teacherOptions = response.data;
      });
    },
    /** 获取教室选项 */
    getClassroomOptions() {
      getClassroomOptions().then(response => {
        this.classroomOptions = response.data;
      });
    },
    /** 加载所有选项数据 */
    loadOptions() {
      this.getCourseOptions();
      this.getSemesterOptions();
      this.getTeacherOptions();
      this.getClassroomOptions();
    },
    // 进度条颜色
    getProgressColor(enrolled, capacity) {
      const rate = (enrolled || 0) / capacity;
      if (rate < 0.5) {
        return '#67C23A';
      } else if (rate < 0.8) {
        return '#E6A23C';
      } else {
        return '#F56C6C';
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 容量调整取消
    cancelCapacity() {
      this.capacityOpen = false;
      this.capacityForm = {};
    },
    // 表单重置
    reset() {
      this.form = {
        classId: null,
        courseId: null,
        semesterId: null,
        teacherId: null,
        classCode: null,
        capacity: 50,
        enrollLimit: null,
        enrolledCount: 0,
        classroomId: null,
        enrollStartTime: null,
        enrollEndTime: null,
        teachStartDate: null,
        teachEndDate: null,
        weekday: null,
        timeSlot: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.classId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.loadOptions();
      this.open = true;
      this.title = "添加开课计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.loadOptions();
      const classId = row.classId || this.ids
      getCourseClass(classId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改开课计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.classId != null) {
            updateCourseClass(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCourseClass(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const classIds = row.classId || this.ids;
      this.$modal.confirm('是否确认删除开课计划编号为"' + classIds + '"的数据项？').then(function() {
        return delCourseClass(classIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 发布按钮操作 */
    handlePublish(row) {
      this.$modal.confirm('是否确认发布开课计划"' + row.classCode + '"？发布后学生可以选课。').then(function() {
        return publishCourseClass(row.classId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发布成功");
      }).catch(() => {});
    },
    /** 批量发布按钮操作 */
    handleBatchPublish() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要发布的开课计划");
        return;
      }
      this.$modal.confirm('是否确认批量发布选中的开课计划？').then(() => {
        return batchPublishCourseClass(this.ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("批量发布成功");
      }).catch(() => {});
    },
    /** 停止选课按钮操作 */
    handleStopEnrollment(row) {
      this.$modal.confirm('是否确认停止开课计划"' + row.classCode + '"的选课？').then(function() {
        return stopEnrollment(row.classId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("已停止选课");
      }).catch(() => {});
    },
    /** 结课按钮操作 */
    handleFinish(row) {
      this.$modal.confirm('是否确认结课"' + row.classCode + '"？结课后无法再选课。').then(function() {
        return finishCourse(row.classId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("结课成功");
      }).catch(() => {});
    },
    /** 调整容量按钮操作 */
    handleAdjustCapacity(row) {
      this.capacityForm = {
        classId: row.classId,
        currentCapacity: row.capacity,
        enrolledCount: row.enrolledCount || 0,
        newCapacity: row.capacity
      };
      this.capacityOpen = true;
    },
    /** 提交容量调整 */
    submitCapacityForm() {
      this.$refs["capacityForm"].validate(valid => {
        if (valid) {
          adjustCapacity(this.capacityForm.classId, this.capacityForm.newCapacity).then(response => {
            this.$modal.msgSuccess("容量调整成功");
            this.capacityOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 节次安排按钮操作 */
    handleSchedule(row) {
      this.scheduleData = [];
      this.scheduleOpen = true;
      getScheduleByClassId(row.classId).then(response => {
        this.scheduleData = response.data || [];
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('education/courseClass/export', {
        ...this.queryParams
      }, `courseClass_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.no-data {
  text-align: center;
  padding: 40px;
}
</style>