<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="goBack" :content="name"></el-page-header>
    </h2>
    <!--   v-permission="'vipGroupManage/updateVipBaseInfo'" -->
    <div class="wrap">
      <div
        class="newBand"
        @click="resetTeachers"
        v-permission="'courseSchedule/practiceGroupTeacherAdjust'"
      >修改老师</div>
      <!-- // accompanys/addCourse -->
      <!-- <div v-permission="'accompanys/addCourse'" class="newBand" @click="addCourse">网管课加课</div> -->
      <!-- <div class="newBand" v-permission="'accompanys/vipCourseAdjust'" @click="adjustment">批量调整</div> -->
    </div>

    <div class="tableWrap">
      <el-table
        :data="tableList"
        :header-cell-style="{background:'#EDEEF0',color:'#444'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="isDisabled" width="55"></el-table-column>
        <el-table-column label="课程编号" align="center" prop="id"></el-table-column>
        <el-table-column label="课程名称" align="center" prop="name"></el-table-column>
        <el-table-column label="主教老师" align="center" prop="teacherName"></el-table-column>
        <!-- <el-table-column label="主教老师" align="center" >
          <template slot-scope="scope">
            <div v-if="scope.row.teacher">
              {{scope.row.teacher.realName}}
            </div>
          </template>
        </el-table-column>-->
        <!-- <el-table-column label="班级id"
                         align="center"
                         prop="classGroupId">
        </el-table-column>-->
        <el-table-column label="上课日期" align="center" prop="classDate">
          <template slot-scope="scope">
            <div>{{ scope.row.classDate | formatTimer}}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="是否点名" align="center" prop="status">
          <template slot-scope="scope">{{ scope.row.isCallNames ? '是' : '否' }}</template>
        </el-table-column> -->
        <el-table-column label="课程状态" align="center" prop="status">
          <template slot-scope="scope">
            <div>{{ scope.row.status | coursesStatus }}</div>
          </template>
        </el-table-column>
        <el-table-column label="结算状态" align="center">
          <template slot-scope="scope">
            <div>{{scope.row.isSettlement?'已结算':'未结算'}}</div>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startClassTimeStr"></el-table-column>
        <el-table-column label="结束时间" align="center" prop="endClassTimeStr"></el-table-column>
        <!-- <el-table-column label="教学点" align="center" prop="schoolName">
          <template slot-scope="scope">
            <div>{{scope.row.schoolName?scope.row.schoolName:'网络教室'}}</div>
          </template>
        </el-table-column>-->
        <el-table-column label="操作" width="250px" align="center" fixed="right">
          <template slot-scope="scope">
            <div>
              <el-button
                type="text"
                v-permission="'courseSchedule/classStartDateAdjust'"
                v-if="scope.row.status == 'NOT_START'"
                @click="resetClass(scope.row)"
              >调整</el-button>
              <!-- <el-button
                type="text"
                v-permission="'accompanys/remove'"
                v-if="!scope.row.isSettlement"
                @click="removeClass(scope.row)"
              >删除</el-button> -->
              <el-button
                v-permission="'courseSchedule/practiceCourseTeacherAdjust'"
                type="text"
                v-if="scope.row.status == 'NOT_START'"
                @click="resetTeacher(scope.row)"
              >更换老师</el-button>
              <!-- <el-button
                type="text"
                v-permission="'accompanys/cleanAttendance'"
                v-if="!scope.row.isSettlement"
                @click="clearAttend(scope.row)"
              >清除考勤</el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="rules.total"
        :page.sync="rules.page"
        :limit.sync="rules.limit"
        :page-sizes="rules.page_size"
        @pagination="getList"
      />
    </div>
    <el-dialog title="课程调整" width="400px" :before-close="handleClose" :visible.sync="courseVisible">
      <el-form
        :model="maskForm"
        ref="maskForm"
        :rules="maskRules"
        label-position="right"
        label-width="80px;"
        :inline="true"
      >
        <el-form-item label="上课日期" prop="date">
          <el-date-picker
            v-model.trim="maskForm.date"
            style="width:200px!important;"
            type="date"
            :picker-options="courseOption"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-select
            placeholder="起始时间"
            style="width:200px!important;"
            v-model.trim="startTime"
            :picker-options="{
                            start: '08:30',
                            step: '00:30',
                            end: '23:00'
                            }"
          ></el-time-select>
        </el-form-item>
        <!-- <el-form-item label="结束时间"
                      prop="endTime">
          <el-time-select placeholder="结束时间"
                          v-model.trim="maskForm.endTime"
                          :picker-options="{
                            start: '04:30',
                            step: '00:05',
                            end: '23:30',
                            minTime: maskForm.startTime
                          }">
          </el-time-select>
        </el-form-item>  v-if="maskForm.teachMode=='OFFLINE'"-->
        <!-- <el-form-item label="课程类型" prop="courseType">
          <el-select clearable v-model.trim="maskForm.teachMode">
            <el-option label="线上课" value="ONLINE"></el-option>
            <el-option label="线下课" value="OFFLINE"></el-option>
          </el-select>
        </el-form-item>-->
        <!-- <el-form-item label="教学地点" v-if="maskForm.teachMode == 'OFFLINE'">
          <el-select v-model.trim="maskForm.address" filterable clearable>
            <el-option
              v-for="(item,index) in schoolList"
              :key="index"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="courseVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitResetClass">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="老师调整"
      width="400px"
      :before-close="teacherClose"
      :visible.sync="teacherVisible"
    >
      <el-form
        :model="teacherForm"
        ref="teacherForm"
        :rules="teacherRules"
        label-position="right"
        label-width="80px;"
        :inline="true"
      >
        <el-form-item label="老师姓名">
          <el-select v-model.trim="teacherForm.teacher" filterable clearable>
            <el-option
              v-for="(item,index) in teacherList"
              :key="index"
              :value="item.id"
              :label="item.realName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="teacherVisible = false">取 消</el-button>
        <el-button type="primary" @click="subresetTeacher">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="adjustmentName" width="800px" :visible.sync="adjustmentVisible">
      <el-form
        :model="adjustmentForm"
        label-position="right"
        label-width="120px"
        ref="adjustmentForm"
        :rules="adjustmentRules"
        :inline="true"
      >
        <el-form-item label="已选择课时数" v-if="!isaddCourse">
          <el-input disabled v-model.trim="adjustmentForm.count"></el-input>
        </el-form-item>
        <el-form-item label="添加课时数" prop="addCount" v-if="isaddCourse">
          <el-input type="number" @mousewheel.native.prevent v-model.trim="adjustmentForm.addCount"></el-input>
        </el-form-item>
        <br />
        <el-form-item label="单课费用" prop="fee" v-if="isaddCourse">
          <el-input v-model.trim="adjustmentForm.fee"></el-input>
        </el-form-item>
        <el-form-item label="排课起始时间" prop="courseTime">
          <el-date-picker
            v-model.trim="adjustmentForm.courseTime"
            :picker-options="pickerOptions"
            style="width:200px!important;"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          ></el-date-picker>
          <el-checkbox style="margin-left:10px;" v-model.trim="adjustmentForm.checked">是否跳过节假日</el-checkbox>
        </el-form-item>
      </el-form>
      <div class="WeekWrap">
        <h3 style="margin-bottom:20px;">
          循环次数
          <el-button type="text" style="margin-left:10px;" @click="addWeek">添加</el-button>
        </h3>
        <div class="countWrap" style="margin-bottom:10px;">
          <div
            class="countItem"
            style="margin-bottom:20px;"
            v-for="(item,index) in weekList"
            :key="index"
          >
            <span>循环周期:</span>
            <el-select v-model.trim="item.dayOfWeek" filterable clearable>
              <el-option
                v-for="(item,index) in weekDateList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <span style="margin-left:10px;">开始时间</span>
            <el-time-select
              style="margin-left:10px;"
              placeholder
              v-model.trim="item.startClassTime"
              :picker-options="{
                               start: '04:30',
                               step: '00:05',
                               end: '23:55'
            }"
            ></el-time-select>
            <el-button
              style="margin-left:10px;"
              type="danger"
              @click="removeWeek(item)"
              icon="el-icon-delete"
              circle
            ></el-button>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adjustmentVisible = false">取 消</el-button>
        <el-button type="primary" v-if="!isaddCourse" @click="submitAdjustment">确 定</el-button>
        <el-button type="primary" v-if="isaddCourse" @click="addCourseSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import {
  findPracticeGroupCourseSchedules,
  practiceCourseAdjus,
  getTeacher,
  practiceGroupManage,
  practiceGroupTeacherAdjust,
  practiceCourseTeacherAdjust,
  cleanAttendance
} from "@/api/buildTeam";
import {
  vipCourseAdjust,
  batchAppendVipGroupCourses,
  bathDelete
} from "@/api/vipSeting";
export default {
  components: {
    pagination
  },
  data() {
    return {
      adjustmentName: "",
      isaddCourse: false,
      adjustmentVisible: false,
      isMultiple: true,
      name: "网管课程组",
      courseVisible: false,
      teacherVisible: false,
      Frules: null,
      FsearchForm: null,
      userId: null,
      activeRow: null,
      rules: {
        // 分页规则
        limit: 20, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 50, 100] // 选择限制显示条数
      },
      tableList: [],
      teacherList: [],
      courseData: [],
      practiceId: null,
      maskForm: {
        date: "",
        startTime: "",
        id: ""
      },
      adjustmentForm: {
        count: "",
        courseTime: "",
        checked: false,
        addCount: "",
        courseType: "",
        fee: ""
      },
      startTime: null,
      maskRules: {
        date: [{ required: true, message: "请选择上课时间", trigger: "blur" }],
        // startTime: [{ required: true, message: '请选择上课开始时间', trigger: 'blur' },],
        endTime: [
          { required: true, message: "请选择上课结束时间", trigger: "blur" }
        ]
      },
      teacherRules: {
        teacher: [{ required: true, message: "请选择老师", trigger: "blur" }]
      },
      teacherForm: {
        teacher: null
      },
      courseOption: null,
      coursesExpireDate: null,
      adjustmentRules: {
        courseTime: [{ required: true, message: "请选择开始时间" }],
        addCount: [{ required: true, message: "请输入加课次数" }],
        courseType: [{ required: true, message: "请选择课程类型" }],
        fee: [{ required: true, message: "请输入费用" }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() + 86400000 <= new Date().getTime();
        }
      },
      weekList: [
        {
          dayOfWeek: "",
          startTime: "",
          endTime: "",
          moid: new Date().getTime()
        }
      ],
      weekDateList: [
        { value: "1", label: "星期一" },
        { value: "2", label: "星期二" },
        { value: "3", label: "星期三" },
        { value: "4", label: "星期四" },
        { value: "5", label: "星期五" },
        { value: "6", label: "星期六" },
        { value: "7", label: "星期日" }
      ],
      activeList: []
    };
  },
  created() {
    this.init();
  },
  activated() {
    this.init();
  },
  methods: {
    init() {
      this.practiceId = this.$route.query.id;
      this.userId = this.$route.query.userId;
      if (this.$route.query.rules) {
        this.Frules = this.$route.query.rules;
      }
      if (this.$route.query.searchForm) {
        this.FsearchForm = this.$route.query.searchForm;
      }
      //   console.log(this.practiceId)
      //   <!-- 状态 指导老师 活动方案-->
      getTeacher({ organId: this.organId }).then(res => {
        if (res.code == 200) {
          this.teacherList = res.data;
        }
      });
      // 获取课程组信息
      this.courseOption = this.coursesDate();
      this.getCourseGroup();
      this.getList();
    },
    getCourseGroup() {
      practiceGroupManage({ search: this.practiceId }).then(res => {
        if (res.code == 200) {
          this.courseData = res.data.rows;
          if (this.courseData.length > 0) {
            this.name = this.courseData[0].name;
          }
        }
      });
    },
    getList() {
      findPracticeGroupCourseSchedules({ practiceId: this.practiceId }).then(
        res => {
          if (res.code == 200) {
            this.tableList = res.data.pageInfo.rows;
            this.rules.total = res.data.pageInfo.total;
          }
        }
      );
    },
    goBack() {
      this.$router.push({
        path: "/business/accompanyList",
        query: { rules: this.Frules, searchForm: this.FsearchForm }
      });
    },
    teacherClose() {
      this.isMultiple = true;
      this.teacherForm.teacher = null;
      this.teacherVisible = false;
    },
    handleClose() {
      this.courseVisible = false;
      this.startTime = "";
      this.maskForm = {
        date: "",
        startTime: "",
        id: ""
      };
      this.$refs["maskForm"].resetFields();
    },
    submitResetClass() {
      //   endClassTimeStr: this.maskForm.endTime,
      if (!this.startTime) {
        this.$message.error("请填写修改时间");
        return;
      }
      let obj = {
        startClassTimeStr: this.startTime,
        id: this.maskForm.id,
        classDate: this.maskForm.date
      };
      practiceCourseAdjus(obj).then(res => {
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.courseVisible = false;
          this.getList();
        } //else {
        //     this.$message.error(res.msg)
        //   }
      });
    },
    resetClass(row) {
      /**
       * maskForm.startTime
       *
       */

      this.maskForm.date = row.classDate;
      this.startTime = row.startClassTimeStr;
      // this.maskForm.endTime = row.endClassTimeStr;
      this.maskForm.id = row.id;
      this.coursesExpireDate = row.coursesExpireDate;
      // 修改课时
      this.courseVisible = true;
    },
    resetTeacher(row) {
      // 单节课
      this.isMultiple = false;
      this.activeRow = row;
      this.teacherForm.teacher = row.actualTeacherId;
      this.teacherVisible = true;
    },
    resetTeachers() {
      // 课程组
      this.isMultiple = true;
      this.teacherForm.teacher = this.courseData[0].userId;
      this.teacherVisible = true;
    },
    subresetTeacher() {
      this.$refs.teacherForm.validate(some => {
        if (some) {
          if (this.isMultiple) {
            // 修改课程组老师
            this.$confirm("此操作将修改所有未上课程的老师, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                practiceGroupTeacherAdjust({
                  practiceGroupId: this.practiceId,
                  teacherId: this.teacherForm.teacher
                }).then(res => {
                  if (res.code == 200) {
                    this.$message.success("修改成功");
                    this.getCourseGroup();
                    this.getList();
                    this.teacherVisible = false;
                  }
                });
              })
              .catch(() => {
                return;
              });
          } else {
            // 修改单节课老师
            practiceCourseTeacherAdjust({
              courseScheduleId: this.activeRow.id,
              teacherId: this.teacherForm.teacher
            }).then(res => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.getList();
                this.teacherVisible = false;
              }
            });
          }
        } else {
          return;
        }
      });
    },
    coursesDate() {
      let self = this;
      return {
        disabledDate: time => {
          // if (self.leftForm.courseStart) {
          // let date = new Date(self.leftForm.courseStart.replace(/-/, "/"));
          // coursesExpireDate
          let date = new Date(this.coursesExpireDate.replace(/-/, "/"));

          return time.getTime() > date.getTime();
          // }
          // return;
        }
      };
    },
    // 是否允许批量调整
    isDisabled(row, index) {
      // || !row.isCallNames
      if (row.isSettlement) {
        return false;
      } else {
        return true;
      }
    },
    adjustment() {
      this.adjustmentName = "批量调整";
      this.isaddCourse = false;
      if (this.adjustmentForm.count <= 0) {
        this.$message.error("请至少勾选一节课");
      } else {
        this.adjustmentVisible = true;
      }
    },
    addWeek() {
      // 添加循环周期
      this.weekList.push({
        dayOfWeek: "",
        startClassTime: "",
        endClassTime: "",
        id: new Date()
      });
    },
    // 删除循环周
    removeWeek(item) {
      for (let i in this.weekList) {
        if (this.weekList[i].id == item.id) {
          this.weekList.splice(i, 1);
        }
      }
    },
    submitAdjustment() {
      this.$refs["adjustmentForm"].validate(item => {
        if (item) {
          let week = this.weekList;
          if (!week[0] || !week[0].startClassTime || !week[0].dayOfWeek) {
            this.$message.error("至少排一节课");
            return;
          }
          // 开始
          let obj = {};
          obj.courseCreateStartTime = this.adjustmentForm.courseTime;
          let idArr = this.activeList.map(item => {
            return item.id;
          });
          let courseScheduleIds = idArr.join(",");
          obj.courseScheduleIds = courseScheduleIds;
          obj.courseTimes = this.weekList;
          obj.holiday = this.adjustmentForm.checked;
          obj.teachMode = this.adjustmentForm.courseType || null;
          obj.groupType = "PRACTICE";

          obj.vipGroupId = this.practiceId;
          vipCourseAdjust(obj).then(res => {
            if (res.code == 200) {
              this.$message.success("恭喜您修改成功");
              this.adjustmentVisible = false;
              this.getList();
            }
          });
        }
      });
    },
    handleSelectionChange(val) {
      this.adjustmentForm.count = val.length;
      this.activeList = val;
    },
    clearAttend(row) {
      this.$confirm("是否清除考勤记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          cleanAttendance({ courseScheduleIds: row.id }).then(res => {
            if (res.code == 200) {
              this.$message.success("清除成功");
              this.getList();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    // 网管课加课弹窗
    addCourse() {
      this.adjustmentName = "网管课加课";
      this.isaddCourse = true;
      this.adjustmentVisible = true;
    },
    // 网管课加课提交
    addCourseSubmit() {
      this.$refs["adjustmentForm"].validate(item => {
        if (item) {
          let week = this.weekList;
          if (!week[0] || !week[0].startClassTime || !week[0].dayOfWeek) {
            this.$message.error("至少排一节课");
            return;
          }
          // 开始
          let obj = {};
          obj.courseCreateStartTime = this.adjustmentForm.courseTime;
          let idArr = this.activeList.map(item => {
            return item.id;
          });
          let courseScheduleIds = idArr.join(",");
          obj.courseScheduleIds = courseScheduleIds;
          obj.courseTimes = this.weekList;
          obj.holiday = this.adjustmentForm.checked;
          obj.vipGroupId = this.practiceId;
          obj.courseCount = this.adjustmentForm.addCount;
          obj.teachMode = this.adjustmentForm.courseType;
          obj.singleClassPrice = this.adjustmentForm.fee;
          obj.groupType = "PRACTICE";
          batchAppendVipGroupCourses(obj).then(res => {
            if (res.code == 200) {
              this.$message.success("恭喜您添加成功");
              this.adjustmentVisible = false;
              this.getList();
            }
          });
        }
      });
    },
    // 删除
    removeClass(row) {
      this.$confirm("是否删除该课程?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        bathDelete({ courseScheduleIds: row.id }).then(res => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.getList();
          }
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.wrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  div {
    margin-right: 20px;
  }
}
</style>