<template>
  <div>
    <el-form
      :model="form"
      inline
      ref="form"
      label-suffix=": "
      label-width="130px"
    >
      <el-row v-if="classType == 5">
        <el-form-item
          label="班级名称"
          prop="className"
          label-width="88px"
          :rules="[{ required: true, message: '请填写班级名称' }]"
        >
          <el-input
            v-model.trim="form.className"
            placeholder="请输入班级名称"
            style="width: 180px"
          ></el-input>
        </el-form-item>
      </el-row>
      <el-form-item
        label="主教老师"
        prop="coreTeacher"
        label-width="88px"
        :rules="[{ required: true, message: '请选择主教老师' }]"
      >
        <el-select
          v-model.trim="form.coreTeacher"
          placeholder="请选择主教老师"
          clearable
          filterable
          @change="changecoreTeacher"
        >
          <el-option
            v-for="(item, index) in teacherList"
            :key="index"
            :label="item.realName"
            :value="String(item.id)"
          >
            <span style="float: left">{{ item.realName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              String(item.id)
            }}</span>
          </el-option>
        </el-select>
        <!-- <remote-search :commit="'setTeachers'" v-model="form.coreTeacher"  /> -->
      </el-form-item>
      <el-form-item
        label="助教老师"
        prop="assistant"
        v-if="
          activeType != 'HIGH' &&
          activeType != 'HIGH_ONLINE' &&
          activeType != 'MUSIC_NETWORK'
        "
      >
        <!-- <remote-search :commit="'setTeachers'" v-model="form.assistant"  :multiple='true'/> -->
        <el-select
          v-model.trim="form.assistant"
          placeholder="请选择助教老师"
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="(item, index) in cooperationList"
            :key="index"
            :label="item.realName"
            :value="item.id"
          >
            <span style="float: left">{{ item.realName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              String(item.id)
            }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <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-form-item> -->
      <empty v-if="isEmpty" desc="暂无可排课时长" />
      <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="title">
              {{ courseTypeListByName[key] }},
              <span>可排课时长{{ musicCourseSettings[key] }}分钟</span>
            </p>
          </template>
          <courseItem
            :surplustime="surplustime[key]"
            :type="key"
            :form="item"
            :prices="prices"
            :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>
  </div>
</template>
<script>
import {
  getMusicCourseSettingsWithStudents,
  classGroupUpdate,
  revisionClassGroup,
  revisionAddClassGroup,
  findClassCourseMinute,
  mergeClassSplitClassAffirm,
} from "@/api/buildTeam";
import courseItem from "./classroom-setting-item-merge";
import { classTimeList } from "@/utils/searchArray";
import MusicStore from "@/views/resetTeaming/store";
import { queryByOrganIdAndCourseType } from "@/views/resetTeaming/api";
import { isEmpty } from "lodash";

const classTimeListByType = {};
for (const item of classTimeList) {
  classTimeListByType[item.value] = item.label;
}

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;
};

const plusNum = (items = [], key) => {
  let money = 0;
  for (const item of items) {
    money += parseFloat(parseFloat(item[key] || 0).toFixed(2) || 0);
  }
  return money;
};

export default {
  props: [
    "activeType",
    "courseTypeList",
    "musicGroupId",
    "detail",
    "studentSubmitedData",
    "classType",
    "musicGroupPaymentCalenderDtos",
    "classIdList",
    "classGroupStudents",
    "selectPrices",
    "classCouresTimeList",
    "teacherList",
    "cooperationList",
  ],
  components: {
    courseItem,
  },
  data() {
    return {
      form: {
        coreTeacher: "",
        assistant: "",
        classs: {},
      },
      allClasss: {},
      prices: {},
      collapses: [0],
      courseTimes: {},
      courseTypeListByName: {},
      classTimeListByType,
      musicCourseSettings: {},
    };
  },
  watch: {
    courseTypeList() {
      this.setCourseTypeListByName();
    },
    studentSubmitedData() {
      this.formatClasss();
    },
    detail() {
      this.formatClasss();
    },
  },
  computed: {
    surplustime() {
      const _ = {};
      for (const key in this.form.classs) {
        if (this.form.classs.hasOwnProperty(key)) {
          const item = this.form.classs[key];
          _[key] = item.courseTotalMinuties - plusNum(item.cycle, "time");
        }
      }
      return _;
    },
    isEmpty() {
      return isEmpty(this.form.classs);
    },
    musicGroup() {
      return MusicStore.state.musicGroup;
    },
  },
  async mounted() {
    try {
      await MusicStore.dispatch("getBaseInfo", {
        data: { musicGroupId: this.musicGroupId },
      });
      const res = await queryByOrganIdAndCourseType({
        organId: this.musicGroup.organId,
      });
      this.prices = res.data;
      if (JSON.stringify(this.prices) == "{}") {
        // 课程时长
        this.$bus.$emit("showguide", ["teamCourseTimer"]);
        return;
      }
    } catch (error) {}
    this.setCourseTypeListByName();
    this.formatClasss();
  },
  methods: {
    setCourseTypeListByName() {
      const courseTypeListByName = {};
      for (const item of this.courseTypeList) {
        courseTypeListByName[item.value] = item.label;
      }
      this.courseTypeListByName = courseTypeListByName;
    },
    async formatClasss() {
      if (this.detail) {
        let coreid = "";
        const assistant = [];
        const { classGroupTeacherMapperList } = this.detail;
        for (const item of classGroupTeacherMapperList || []) {
          if (item.teacherRole === "BISHOP") {
            coreid = String(item.userId);
          }
          if (item.teacherRole === "TEACHING") {
            assistant.push(item.userId);
          }
        }
        this.$set(this.form, "coreTeacher", String(coreid));
        this.$set(this.form, "assistant", assistant);
      }
      const studentIds = this.detail
        ? undefined
        : this.studentSubmitedData?.seleched.join(",");
      const classGroupId = this.detail?.id;
      if (!studentIds && !classGroupId) {
        return;
      }

      let res = {};
      if (this.classType == 5) {
        // res = await findClassCourseMinute(this.classIdList);
        res.data = this.classCouresTimeList;
      } else {
        try {
          res = await getMusicCourseSettingsWithStudents({
            musicGroupId: this.musicGroupId,
            studentIds,
            classGroupId,
          });
        } catch (error) {
          console.log(error);
        }
      }
      // console.log(res);
      if (Object.keys(res).length <= 0) return;
      this.musicCourseSettings = res.data;

      const classs = {};
      for (const item of this.courseTypeList) {
        const key = item.value;
        if (res.data[key]) {
          classs[key] = {
            courseTotalMinuties: res.data[key],
            cycle: [
              {
                time: this.selectPrices ? this.selectPrices[key] : undefined,
              },
            ],
          };
        }
      }
      this.allClasss = { ...classs };
      this.$set(this.form, "classs", classs);
      // this.courseTimes = courseTimes
    },
    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);
    },
    submit() {
      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];
              list.push({
                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((_) => ({
                  courseType: key,
                  dayOfWeek: _.dayOfWeek,
                  endClassTime: _.endClassTime,
                  startClassTime: _.startClassTime,
                })),
              });
            }
          }
          try {
            if (this.detail) {
              let result = await classGroupUpdate(list);
              if (result.code == 206) {
                this.$confirm(`当前课程课酬预计为0,是否继续`, "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(async () => {
                    // obj.allowZeroSalary = true;
                    list.forEach((item) => {
                      item.allowZeroSalary = true;
                    });
                    await classGroupUpdate(list);
                    this.$listeners.submited();
                    this.$listeners.close();
                  })
                  .catch(() => {
                    return;
                  });
                return;
              }
              this.$message.success("排课修改成功");
            } else {
              if (this.classType == 1) {
                // 0新建班级 2 3 4新增班级修改
                await revisionClassGroup(list);
                this.$message.success("排课成功");
              } else if (
                this.classType == 2 ||
                this.classType == 3 ||
                this.classType == 4
              ) {
                await revisionAddClassGroup(list);
                this.$message.success("排课成功");
              } else if (this.classType == 5) {
                // 这里是合班拆班
                let obj = {};
                obj.musicGroupPaymentCalenderDtos =
                  this.musicGroupPaymentCalenderDtos;
                obj.classGroup4MixDtos = list;
                obj.classGroupIds = this.classIdList;
                obj.studentIds = this.studentSubmitedData.seleched;
                obj.classGroupStudents = this.classGroupStudents;
                obj.classCourseMinuteMap = this.selectPrices;
                await mergeClassSplitClassAffirm(obj);
                let grend =
                  this.$parent.$parent.$parent.$parent.$parent.$parent.$parent;
                grend.closeStudentReset();
                grend.getList();
                return;
              }
            }
            this.$listeners.submited();
            this.$listeners.close();
          } catch (error) {
            console.log(error);
          }
        } else {
          this.$message.error("请先填写所有表单");
        }
      });
    },
    collapseChange(val) {
      this.collapses = val;
    },
    changecoreTeacher(val) {},
  },
};
</script>
<style lang="less" scoped>
.dialog-footer {
  margin-top: 20px;
  display: block;
  text-align: right;
}
.title {
  font-size: 16px;
  padding: 10px;
  font-weight: normal;
  > span {
    color: tomato;
    font-size: 14px;
  }
}
.tag {
  margin-right: 5px;
  cursor: pointer;
}
</style>
