<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'
        "
      >

        <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>
              <span style="color: #333"
                >已排课时长:{{ musicSurplus[key] }}分钟</span
              >
            </p>
          </template>
          <courseItem
            :surplustime="surplustime[key]"
            @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="班级预览"
      :visible.sync="previewVisible"
      append-to-body
      width="900px"
    >
      <classrome-preview
        :types="form.classs"
        :details="previewList"
        :courseTypeListByName="courseTypeListByName"
        :teacherList="teacherList"
        :cooperationList="cooperationList"
        :coreTeacher="form.coreTeacher"
        :assistant="form.assistant"
      />
      <div slot="footer" class="dialog-footer" v-if="classType != 5">
        <el-button @click="previewVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit('confirmGenerate')"
          >确认排课</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getMusicCourseSettingsWithStudents,
  classGroupUpdate,
  revisionClassGroup,
  revisionAddClassGroup,
  findClassCourseMinute,
  mergeClassSplitClassAffirm,
} from "@/api/buildTeam";
import courseItem from "./classroom-setting-item";
import { classTimeList } from "@/utils/searchArray";
import MusicStore from "@/views/resetTeaming/store";
import { sysConfigList } from "@/api/generalSettings";
import { queryByOrganIdAndCourseType } from "@/views/resetTeaming/api";
import { isEmpty } from "lodash";
import classromePreview from "./classroom-preview";

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,
    "classrome-preview": classromePreview,
  },
  data() {
    return {
      form: {
        coreTeacher: "",
        assistant: "",
        classs: {},
      },
      allClasss: {},
      prices: {},
      collapses: [0],
      courseTimes: {},
      courseTypeListByName: {},
      classTimeListByType,
      musicCourseSettings: {},
      musicSurplus: {},
      previewVisible: false,
      previewList: [],
      holidays: [],
    };
  },
  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];
          // - plusNum(item.cycle, "time");
          _[key] = item.courseTotalMinuties;
        }
      }
      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;
    } catch (error) {}
    this.setCourseTypeListByName();
    this.formatClasss();
    this.FetchHoliday();
  },
  methods: {
    async FetchHoliday() {
      try {
        const res = await sysConfigList({
          group: "holiday",
        });
        this.holidays = JSON.parse(res.data[0].paranValue);
      } catch (error) {}
    },
    setCourseTypeListByName() {
      const courseTypeListByName = {};
      for (const item of this.courseTypeList) {
        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 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;
      for (let key in this.musicCourseSettings) {
        this.musicSurplus[key] = 0;
      }
      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,
                coreTeacher: this.coreid,
                assistant: this.assistant,
              },
            ],
          };
        }
      }
      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(type) {
      for (const key in this.musicCourseSettings) {
        if (Object.hasOwnProperty.call(this.musicCourseSettings, key)) {
          const allTime = this.musicCourseSettings[key];
          const useTime = this.musicSurplus[key];

          if (useTime > allTime) {
            this.$message.error(
              this.courseTypeListByName[key] + " 课程时长不足"
            );
            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 = {
                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,
                })),
              };
              if (type && typeof type === "string") {
                data[type] = true;
              }
              list.push(data);
            }
          }
          try {
            if (this.detail) {
              let result = await classGroupUpdate(list);
              this.previewVisible = false;
              if (result.code == 207) {
                await this.$confirm(
                  result.msg || `当前课程课酬预计为0,是否继续`,
                  "提示",
                  {
                    type: "warning",
                  }
                );
                // obj.allowZeroSalary = true;
                list.forEach((item) => {
                  item.allowZeroSalary = true;
                });
                await classGroupUpdate(list);
                this.$listeners.submited();
                this.$listeners.close();
                return;
              }
              if (result.code == 206) {
                this.previewVisible = true;
                this.previewList = result.data;
                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) {},
    updateMusicSurplus() {},
    setUserTime(time, type) {
      // console.log(time, type)
      this.$set(this.musicSurplus, type, time || 0);
      // console.log(this.musicSurplus)
      this.$forceUpdate();
      // this.$nextTick(res=>{
      //   this.musicSurplus[type] = time;
      //       console.log(this.musicSurplus[type])
      // })
    },
    formatTeacher(row) {
      console.log(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:{
  //   musicSurplus(){
  //     deep
  //   }
  // }
};
</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>
