<template>
  <div>
    <el-form
      :model="form"
      inline
      ref="form"
      label-suffix=": "
      label-width="110px"
    >
      <el-form-item
        label="主教老师"
        prop="coreTeacher"
        :rules="[{ required: true, message: '请选择主教老师' }]"
      >
        <el-select
          v-model.trim="form.coreTeacher"
          placeholder="请选择主教老师"
          clearable
          filterable
        >
          <el-option
            v-for="(item, index) in teacherList"
            :key="index"
            :label="item.realName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="助教老师"
        prop="assistant"
      >
        <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"
          ></el-option>
        </el-select>
      </el-form-item>
      <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>{{courseTypeListByName[key]}}, 剩余可排课时长{{surplustime[key]}}分钟</p>
          </template>
          <courseItem
            :surplustime="surplustime[key]"
            :type="key"
            :form="item"
          />
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$listeners.close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </div>
</template>
<script>
import { getMusicCourseSettingsWithStudents, classGroupUpdate, revisionClassGroup, revisionAddClassGroup } from '@/api/buildTeam'
import courseItem from "./classroom-setting-item";
import { classTimeList } from '@/utils/searchArray'

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: ["teacherList", "activeType", "courseTypeList", 'cooperationList', 'musicGroupId', 'detail', 'studentSubmitedData', 'classType'],
  components: {
    courseItem,
  },
  data() {
    return {
      form: {
        coreTeacher: '',
        assistant: '',
        classs: {}
      },
      collapses: [0],
      courseTimes: {},
      courseTypeListByName: {},
      classTimeListByType
    };
  },
  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 _
    }
  },
  async mounted() {
    this.setCourseTypeListByName()
    this.formatClasss()
  },
  methods: {
    setCourseTypeListByName() {
      const courseTypeListByName = {}
      for (const item of this.courseTypeList) {
        courseTypeListByName[item.value] = item.label
      }
      this.courseTypeListByName = courseTypeListByName
    },
    async formatClasss() {
      try {
        const res = await getMusicCourseSettingsWithStudents({
          musicGroupId: this.musicGroupId,
          studentIds: (this.detail ? undefined : this.studentSubmitedData?.seleched.join(',')),
          classGroupId: this.detail?.id
        })
        const classs = {}
        const courseTimes = {}
        for (const item of res.data) {
          courseTimes[item.courseType] = item
        }
        for (const item of this.courseTypeList) {
          const key = item.value
          if (courseTimes[key]) {
            classs[key] = {
              courseTotalMinuties: courseTimes[key].courseTotalMinuties,
              cycle: [{
                time: classTimeListByType[key]
              }]
            }
          }
        }
        this.$set(this.form, 'classs', classs)
        // this.courseTimes = courseTimes
      } catch (error) {
        console.log(error)
      }
    },
    submit() {
      for (const key in this.surplustime) {
        if (this.surplustime.hasOwnProperty(key)) {
          const item = this.surplustime[key];
          if (item > 0) {
            this.$message.error(`${this.courseTypeListByName[key]}，还剩余${item}分钟剩余可排时长`)
            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];
              list.push({
                type: key,
                courseType: key,
                classGroupName: (this.studentSubmitedData?.name || this.detail?.classGroupName),
                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) {
              await classGroupUpdate(list)
              this.$message.success('排课修改成功')
            } else {
              if (this.classType === 1) {
                await revisionClassGroup(list)
                this.$message.success('排课成功')
              } else if (this.classType === 2 || this.classType === 3) {
                await revisionAddClassGroup(list)
                this.$message.success('排课成功')
              }
            }
            this.$listeners.submited()
            this.$listeners.close()
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    collapseChange(val) {
      this.collapses = val
    }
  },
};
</script>
<style lang="less" scoped>
  .dialog-footer{
    margin-top: 20px;
    display: block;
    text-align: right;
  }
</style>
