<template>
  <div>
    <el-dialog
      title="排课"
      append-to-body
      width="1050px"
      :visible.sync="transPlanVisible"
    >
      <div v-if="myForm && myForm.classs && myForm.classs['HIGH_ONLINE']">
        <el-form
          :model="myForm"
          :inline="true"
          ref="planform"
          label-suffix=": "
        >
          <div v-if="!isMoreClass">
            <p class="title">
              <span style="font-weight: 600">线上基础技能课</span>
              可排课时长:<span style="color: red">{{
                form.courseConvertSum.courseMinute
              }}</span
              >分钟
              <span style="color: #333"
                >已排课时长:
                <span style="color: red"> {{ alltime }}分钟</span></span
              >
            </p>

            <courseItem
              :form="myForm.classs['HIGH_ONLINE']"
              :teacherList="teacherList"
              :surplustime="form.courseConvertSum.courseMinute"
              :activeType="'HIGH_ONLINE'"
              :coreid="myForm.coreTeacher"
              :type="'HIGH_ONLINE'"
              :prices="prices"
              :holidays="holidays"
              @setUserTime="setUserTime"
            />
          </div>
          <div v-else>
            <p class="title">
              <span style="font-weight: 600">线上基础技能课</span>
              可排课时:<span style="color: red">{{
                form.courseConvertSum.courseNum
              }}</span
              >课时
              <span style="color: #333"
                >已排课时:
                <span style="color: red"> {{ allNum }}课时</span></span
              >
            </p>
            <courseItem
              :form="myForm.classs['HIGH_ONLINE']"
              :teacherList="teacherList"
              :surplustime="form.courseConvertSum.courseMinute"
              :surplusCourseNum="form.courseConvertSum.courseNum"
              :activeType="'HIGH_ONLINE'"
              :coreid="myForm.coreTeacher"
              :type="'HIGH_ONLINE'"
              :prices="prices"
              :holidays="holidays"
              @setUserCourse="setUserCourse"
              :isCourseNumType="true"
            />
            <!-- setUserCourse -->
          </div>
          <!--
          :cooperationList="teacherList" -->
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="transPlanVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getSysTenantConfig } from "@/views/courseRulersManager/api";
import { queryByOrganIdAndCourseType } from "@/views/resetTeaming/api";
import courseItem from "../modals/classroom-setting-item.vue";
import { isEmpty } from "lodash";
const formatClassGroupTeacherMapperList = (core, ass) => {
  const list = [];
  if (core) {
    list.push({ userId: core, teacherRole: "BISHOP" });
  }
  if (ass) {
    for (const item of ass) {
      list.push({ userId: item, teacherRole: "TEACHING" });
    }
  }
  return list;
};
import { courseScheduleConvert } from "../../api";
export default {
  props: ["form", "teacherList", "activeRow"],
  data() {
    return {
      prices: [],
      holidays: [],
      transPlanVisible: false,
      allClasss: {},
      courseTypeListByName: {},
      courseTypeList: [{ value: "HIGH_ONLINE", label: "线上基础技能课" }],
      alltime: 0,
      myForm: null,
      allNum: 0,
    };
  },
  components: {
    courseItem,
  },
  methods: {
    async init() {
      try {
        const res = await queryByOrganIdAndCourseType({
          organId: this.$route.query.organId,
        });
        const res1 = await getSysTenantConfig({
          group: "holiday",
        });

        this.holidays = JSON.parse(
          res1.data[0].paranValue ? res1.data[0].paranValue : "[]"
        );
        this.prices = res.data;
        let arr = [];
        if (JSON.stringify(this.prices) == "{}") {
          // 课程时长
          arr.push("teamCourseTimer");
        }
        if (this.holidays.length <= 0) {
          arr.push("holiday");
        }
        //
        if (arr.length > 0) {
          this.$bus.$emit("showguide", arr);
          return;
        }
      } catch (error) {
        console.log(error);
      }
    },
    async openDialog() {
      // 获取列表
      this.init();
      // console.log(
      //   this.activeRow,
      //   this.form,
      //   "初始化",
      //   this.activeRow.classs["HIGH_ONLINE"]
      // );
      this.myForm = { ...this.activeRow };
      this.transPlanVisible = true;
    },
    setCourseTypeListByName() {
      const courseTypeListByName = {};
      for (const item of this.courseTypeList) {
        courseTypeListByName[item.value] = item.label;
      }
      this.courseTypeListByName = courseTypeListByName;
    },
    setUserTime(time, type) {
      this.alltime = time;
    },
    setUserCourse(courseNum, type) {
      this.allNum = courseNum;
    },
    formatTeacher(row) {
      let arr = [];
      if (row.coreTeacher) {
        let obj = {};
        obj.teacherRole = "BISHOP";
        obj.userId = row.coreTeacher;
        arr.push(obj);
      }
      if (row.assistant?.length > 0) {
        row.assistant.forEach((ass) => {
          arr.push({ teacherRole: "TEACHING", userId: ass });
        });
      }
      return arr;
    },
    async submit() {
      try {
        if (!this.isMoreClass) {
          if (this.alltime > this.form.courseConvertSum.courseMinute) {
            this.$message.error("课程时长不足");
            return;
          }

          if (this.alltime != this.form.courseConvertSum.courseMinute) {
            await this.$alert(
              `<b>该班级剩余  <span style="color:red">${parseInt(this.form.courseConvertSum.courseMinute-this.alltime)}</span> 分钟时长未排课</b><br />所有班级排课完成且确认后，剩余时长将被清除，不可再次排课`,
              {
                confirmButtonText: "确定",
                dangerouslyUseHTMLString: true,
              }
            );
          }
        } else {
          if (this.allNum > this.form.courseConvertSum.courseNum) {
            this.$message.error("课程课时不足");
            return;
          }
          if (this.allNum != this.form.courseConvertSum.courseNum) {
        await  this.$alert(
              `<b>该班级剩余  <span style="color:red">${parseInt(this.form.courseConvertSum.courseNum-this.allNum)}</span> 课时未排课</b><br />所有班级排课完成且确认后，剩余课时将被清除，不可再次排课`,
              {
                confirmButtonText: "确定",
                dangerouslyUseHTMLString: true,

              }
            );
          }
        }
      } catch (e) {
        console.log(e);
        return;
      }

      this.$refs.planform.validate(async (valid) => {
        let key = "HIGH_ONLINE";
        if (valid) {
          const item = this.activeRow.classs[key];
          const data = {
            confirmGenerate: false,
            classGroupTeacherMapperList: formatClassGroupTeacherMapperList(
              this.myForm.coreTeacher
            ),
            courseTimeDtoList: item.cycle.map((_) => ({
              classGroupTeacherMapperList: this.formatTeacher(_),
              courseType: key,
              dayOfWeek: _.dayOfWeek,
              endClassTime: _.endClassTime,
              startClassTime: _.startClassTime,
              startDate: _.startDate,
              endDate: _.endDate,
              holiday: _.holiday,
              expectCourseNum: _.expectCourseNum,
            })),
            ...this.myForm,
            userIds: this.myForm.studentList.join(","),
            type: key,
          };
          try {
            let arr = [data];
            const res = await courseScheduleConvert(arr);
            this.activeRow.submitDate = data;
            this.activeRow.courseScheduleList = res.data;
            this.$emit("submitCourse");
            this.transPlanVisible = false;
          } catch (e) {
            console.log(e);
          }
        } else {
          this.$message.error("请先填写所有表单");
        }
      });
    },
    workOut(date, classCount, weekArr, id, startTime = "", endTime = "") {
      // 这里是一天排一节课  现在要改成一天排多节
      while (classCount && classCount > 0) {
        for (let i in weekArr) {
          let date1 = new Date(date.getTime());
          let num; // 下次上课上几天后
          // 星期4 - 当前是星期几 =>
          weekArr[i].weekNum - date.getDay() >= 0
            ? (num = weekArr[i].weekNum - date.getDay())
            : (num = weekArr[i].weekNum - date.getDay() + 7);

          let dataStr = this.getThinkDate(date, num);
          let monthDay = this.getThinkDate(date1, num, 2);

          if (this.isholiday) {
            if (this.holidayList.indexOf(monthDay) != -1) {
              // 这里说明有节假日
              continue;
            }
          }

          // 排的是合奏班

          let nowStartTime = this.week[i].startTime || startTime;
          let nowEndTime = this.week[i].endTime || endTime;
          //       date: this.getNowFormatDate(date),
          this.tableList.push({
            classDate: dataStr,
            week: this.weekDay[weekArr[i].weekNum],
            type: courseType,
            id: id,
            name: className,
            classTime: nowStartTime + "-" + nowEndTime,
            startClassTimeStr: nowStartTime,
            endClassTimeStr: nowEndTime,
            weekNum: weekArr[i].weekNum,
          });
          // 这里我排声部课
          //               date: this.getNowFormatDate(date),

          for (let j in this.activeSingleList) {
            this.classCardList.push({
              classDate: dataStr,
              classGroupId: this.activeSingleList[j].id,
              startClassTimeStr: nowStartTime,
              endClassTimeStr: nowEndTime,
              type: courseType,
              mixid: this.activeSingleList[j].mixid,
              weekNum: weekArr[i].weekNum,
              name: this.activeSingleList[j].name,
              option: 1,
            });
          }
          classCount--;
          if (classCount == 0) break;
        }
        date.setDate(date.getDate() + 7);
      }
      // 请求排课
    },
  },
  watch: {
    courseTypeList() {
      this.setCourseTypeListByName();
    },
  },
  computed: {
    isEmpty() {
      return isEmpty(this.form.classs);
    },
    isMoreClass() {
      return this.form.classList.length > 1;
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
