<template>
  <div>
    <el-form
      :model="form"
      inline
      ref="form"
      label-suffix=": "
      label-width="130px"
    >
      <el-form-item
        v-if="!!Object.keys(allClasss).length"
        style="display: block"
        label="排课类型"
        label-width="88px"
      >
        <el-tag
          class="tag"
          :effect="form.classs[key] ? 'dark' : 'plain'"
          v-for="(item, key) in allClasss"
          :key="key"
          @click="changeTag(key)"
          >{{ courseTypeListByName[key] }}</el-tag
        >
        <el-button
          type="text"
          @click="studentListModalVisible = true"
          :disabled="detail.id ? false : true"
          class="studentTitle"
          >学员列表>></el-button
        >
      </el-form-item>
      <empty v-if="isEmpty" desc="暂无可排课时长" />
      <p class="title">
        <span
          >该班级截止到{{ endSchoolTerm }}可预排课时长:{{
            activeCourseTime
          }}分钟</span
        >
        <span
          >已排课时长:{{
            musicSurplus
          }}分钟,请根据教学规划安排各类型课程的课时数
          <el-tooltip placement="top" popper-class="mTooltip">
            <div slot="content">开课日期至本学期截止日期周次*4*45</div>
            <i
              class="el-icon-question micon el-tooltip"
              style="font-size: 18px; color: #f56c6c"
              v-permission="'export/teacherSalary'"
            ></i> </el-tooltip
        ></span>
      </p>
      <el-collapse v-model="collapses" @change="collapseChange">
        <el-collapse-item
          v-for="(item, key, index) in form.classs"
          :name="index"
          :key="key"
        >
          <template #title>
            <p class="coursetitle">
              {{ courseTypeListByName[key] }}
              <span>已排课时长:{{ courseTimeList[key] }}分钟</span>
            </p>
          </template>
          <courseItem
            :endSchoolTerm="endSchoolTerm"
            :startCourseDate="startCourseDate"
            :surplustime="activeCourseTime"
            @setUserTime="setUserTime"
            :teacherList="teacherList"
            :activeType="activeType"
            :cooperationList="cooperationList"
            :coreid="coreid"
            :assistant="assistant"
            :type="key"
            :form="item"
            :prices="prices"
            :holidays="holidays"
            :selectPrice="selectPrices ? selectPrices[key] : ''"
          />
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="classType != 5">
      <el-button @click="$listeners.close">取 消</el-button>
      <el-button type="primary" :disabled="isEmpty" @click="submit"
        >确定</el-button
      >
    </div>
    <el-dialog
      title="学员列表"
      width="700px"
      :visible.sync="studentListModalVisible"
      append-to-body
      destroy-on-close
    >
      <viewStudentList
        :list="studentList"
        v-if="studentListModalVisible"
        :showOk="true"
        :isChiose="false"
        @close="studentListModalVisible = false"
      />
    </el-dialog>
  </div>
</template>
<script>
import courseItem from "./classroom-setting-item";
import MusicStore from "@/views/resetTeaming/store"; // 乐团的基本信息
import { isEmpty } from "lodash";
import { preCourseSchedule } from "@/api/buildTeam";
import { getClassAllStudent } from "@/api/studentManager";
import { queryByOrganIdAndCourseType } from "@/views/resetTeaming/api";
import { getSysTenantConfig } from "@/views/courseRulersManager/api";
import viewStudentList from "@/views/teamDetail/componentClass/student-list";
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;
};
export default {
  components: { courseItem, viewStudentList },
  props: [
    "activeType",
    "courseTypeList",
    "musicGroupId",
    "detail",
    "studentSubmitedData",
    "classType",
    "musicGroupPaymentCalenderDtos",
    "classIdList",
    "classGroupStudents",
    "selectPrices",
    "classCouresTimeList",
    "teacherList",
    "cooperationList",
    "endSchoolTerm",
    "startCourseDate",
    "musicGroupSchoolTermCourseDetailId",
  ],

  data() {
    return {
      form: { coreTeacher: "", assistant: "", classs: {} },
      allClasss: {},
      prices: {},
      collapses: [0],
      courseTimes: {},
      courseTypeListByName: {},
      musicCourseSettings: 0, // 可排课时长
      musicSurplus: 0, //已排课时长
      courseTimeList: {}, // 每种课程类型已排课
      previewVisible: false,
      previewList: [],
      holidays: [],
      studentListModalVisible: false,
      studentList: [],
    };
  },
  async mounted() {
    try {
      await MusicStore.dispatch("getBaseInfo", {
        data: { musicGroupId: this.musicGroupId },
      });
    } catch (error) {}
    // console.log('courseTypeList',this.courseTypeList)
    // 获取班级的学生列表
    getClassAllStudent({ classGroupId: this.detail.id }).then((res) => {
      if (res.code == 200) {
        this.studentList = res.data.map((item) => {
          return {
            userId: item.userId,
            nickName: item.name,
            gender: item.gender,
            phone: item.parentsPhone,
            subjectNames: item.subjectName,
          };
        });
      }
    });
    this.setCourseTypeListByName(); // 获取课程名称和枚举的键值对
    this.formatClasss(); // 初始化班级
    this.FetchHoliday(); // 设置节假日
  },
  methods: {
    async FetchHoliday() {
      try {
        const res1 = await getSysTenantConfig({
          group: "holiday",
        });
        const res = await queryByOrganIdAndCourseType({
          organId: this.musicGroup.organId,
        });
        this.holidays = JSON.parse(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);
      }
    },
    setCourseTypeListByName() {
      const courseTypeListByName = {};
      for (const item of this.courseTypeList) {
        if (item.value == "HIGH" || item.value == "HIGH_ONLINE") {
        } else {
          courseTypeListByName[item.value] = item.label;
        }
      }
      this.courseTypeListByName = courseTypeListByName;
    },
    async formatClasss() {
      this.coreid = "";
      this.assistant = [];
      if (this.detail) {
        const { classGroupTeacherMapperList } = this.detail;
        for (const item of classGroupTeacherMapperList || []) {
          if (item.teacherRole === "BISHOP") {
            this.coreid = String(item.userId);
          }
          if (item.teacherRole === "TEACHING") {
            this.assistant.push(item.userId);
          }
        }
        this.$set(this.form, "coreTeacher", String(this.coreid));
        this.$set(this.form, "assistant", this.assistant);
      }
      const classGroupId = this.detail?.id;
      if (!classGroupId) {
        this.$message.error("班级信息错误");
        return;
      }
      this.musicCourseSettings = this.detail.preSubMinutes;

      const classs = {};
      for (const item of this.courseTypeList) {
        const key = item.value;
        if (item.value == "HIGH" || item.value == "HIGH_ONLINE") {
        } else {
          this.courseTimeList[key] = 0;
          classs[key] = {
            courseTotalMinuties: this.musicCourseSettings,
            cycle: [
              {
                time: this.selectPrices ? this.selectPrices[key] : undefined,
                coreTeacher: this.coreid,
                assistant: this.assistant,
              },
            ],
          };
        }
      }
      // console.log(classs,this.courseTypeList[0].value)
      let key = this.courseTypeList[0].value;
      this.allClasss = { ...classs };
      let onlyClass = { [key]: classs[this.courseTypeList[0].value] };
      this.$set(this.form, "classs", onlyClass);
    },
    collapseChange(val) {
      this.collapses = val;
    },
    async submit() {
      if (this.activeCourseTime < 0) {
        this.$message.error("课程使用时长超过最大预排课数");
        return;
      }
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const list = [];
          for (const key in this.form.classs) {
            if (this.form.classs.hasOwnProperty(key)) {
              const item = this.form.classs[key];
              const data = {
                confirmGenerate: true,
                type: this.detail ? undefined : this.activeType,
                courseType: key,
                classGroupName:
                  this.studentSubmitedData?.name ||
                  this.detail?.name ||
                  this.form.className,
                classGroupId: this.detail?.id,
                musicGroupId: this.musicGroupId,
                startDate: item.courseTime,
                classGroupTeacherMapperList: formatClassGroupTeacherMapperList(
                  this.form.coreTeacher,
                  this.form.assistant
                ),
                holiday: item.holiday,
                students: this.studentSubmitedData?.seleched,
                courseTimes: item.cycle.length,
                courseTimeDtoList: item.cycle.map((_) => ({
                  classGroupTeacherMapperList: this.formatTeacher(_),
                  courseType: key,
                  dayOfWeek: _.dayOfWeek,
                  endClassTime: _.endClassTime,
                  startClassTime: _.startClassTime,
                  startDate: _.startDate,
                  endDate: _.endDate,
                  holiday: _.holiday,
                  expectCourseNum: _.expectCourseNum,
                  expectCourseMinutes: _.time,
                })),
                musicGroupSchoolTermCourseDetailId:
                  this.musicGroupSchoolTermCourseDetailId,
              };
              list.push(data);
            }
          }
          try {
            const res = await preCourseSchedule(list);
            if (res.code == 207) {
              await this.$confirm(
                res.msg || `当前课程课酬预计为0,是否继续`,
                "提示",
                {
                  type: "warning",
                }
              );
              // obj.allowZeroSalary = true;
              list.forEach((item) => {
                item.allowZeroSalary = true;
              });
              await preCourseSchedule(list);
              this.$listeners.submited();
              this.$listeners.close();
              return;
            }
            this.$message.success("排课成功");
            this.$listeners.submited();
            this.$listeners.close();
          } catch (e) {
            console.log(e);
          }
        }
      });
    },
    setUserTime(time, type) {
      this.$set(this.courseTimeList, type, time || 0);
      this.musicSurplus = 0;
      for (let key in this.courseTimeList) {
        this.musicSurplus += this.courseTimeList[key];
      }
      this.$forceUpdate();
    },
    changeTag(key) {
      const clas = { ...this.form.classs };
      if (clas[key]) {
        delete clas[key];
      } else {
        clas[key] = this.allClasss[key];
      }
      this.$set(this.form, "classs", clas);
    },
    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;
    },
  },
  watch: {
    watch: {
      courseTypeList() {
        this.setCourseTypeListByName();
      },
      detail() {
        this.formatClasss();
      },
    },
  },
  computed: {
    musicGroup() {
      return MusicStore.state.musicGroup;
    },
    isEmpty() {
      return isEmpty(this.form.classs);
    },
    surplustime() {
      return this.detail.preSubMinutes;
    },
    activeCourseTime() {
      let time = this.detail.preSubMinutes - this.musicSurplus;
      return time;
    },
  },
};
</script>
<style lang="scss" scoped>
.coursetitle {
  padding: 0 20px;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
}
.title {
  color: red;
  margin-bottom: 30px;
  font-size: 16px;
  font-weight: bold;
}
.tag {
  margin-right: 5px;
  cursor: pointer;
}
.dialog-footer {
  margin-top: 20px;
  display: block;
  text-align: right;
}
</style>
