<template>
  <div class="m-container">
    <div class="line"></div>
    <h2>
      <el-page-header @back="goBack" :content="$route.query.name">
      </el-page-header>
    </h2>
    <div class="topWrap">
      <el-form :inline="true" :model="topForm">
        <el-form-item label="班级类型">
          <el-select
            v-model.trim="topForm.classType"
            clearable
            filterable
            @change="changeMixClass"
          >
            <el-option
              v-for="(item, index) in musicClassTypeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="btnList">
      <el-form :inline="true">
        <el-form-item label="开课日期:">
          <p>{{ form.startCourseDate }}</p>
        </el-form-item>
        <el-form-item>
          <auth auths="musicGroupSchoolTermCourseDetail/upset/4444">
            <el-button type="primary" @click="resetStartTime">修改</el-button>
          </auth>
        </el-form-item>
        <el-form-item v-if="form.endSchoolTerm">
          <p style="color: red">该学期结束日期为:{{ form.endSchoolTerm }}</p>
        </el-form-item>
      </el-form>
    </div>
    <div class="tableWrap" style>
      <el-table
        :data="activeSingleList"
        @expand-change="changeDetail"
        style
        ref="multipleTable"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        tooltip-effect="dark"
        ><el-table-column type="expand">
          <template slot-scope="props">
            <el-table
              :data="props.row.courseData"
              :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
            >
              <el-table-column align="center" prop="name" label="课程类型">
                <template slot-scope="scope">
                  <div>{{ scope.row.type | courseTypeFormat }}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="name" label="课程名称">
                <template slot-scope="scope">
                  <div>{{ scope.row.name }}</div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="name"
                label="预开始时间"
                width="200px"
              >
                <template slot-scope="scope"
                  >{{
                    scope.row.startClassTime
                      ? scope.row.startClassTime.substr(0, 16)
                      : ""
                  }}-{{
                    scope.row.endClassTime
                      ? scope.row.endClassTime.substr(11, 5)
                      : ""
                  }}</template
                >
              </el-table-column>
              <el-table-column
                align="center"
                prop="name"
                label="课程时长(分钟)"
              >
                <template slot-scope="scope">
                  <div>
                    {{ getCourseTime(scope.row) }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="actualTeacherName"
                label="主教老师"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="teachingTeacherNames"
                label="助教老师"
              ></el-table-column>
            </el-table>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="name"
          label="班级名称"
        ></el-table-column>
        <el-table-column align="center" prop="type" label="班级类型">
          <template slot-scope="scope">
            <div>{{ scope.row.type | classType }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="studentNum" label="当前班级人数">
          <template slot-scope="scope">
            <div>{{ scope.row.studentNum }}人</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop label="主教老师">
          <template slot-scope="scope">
            <div v-if="scope.row.classGroupTeacherMapperList">
              <p
                v-for="(item, index) in scope.row.classGroupTeacherMapperList"
                :key="index"
              >
                <span v-if="item.teacherRole == 'BISHOP'">
                  {{ item.userName }}
                </span>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="助教老师">
          <template slot-scope="scope">
            <div v-if="scope.row.classGroupTeacherMapperList">
              <p
                v-for="(item, index) in scope.row.classGroupTeacherMapperList"
                :key="index"
              >
                <span v-if="item.teacherRole == 'TEACHING'">
                  {{ item.userName }}
                </span>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="已预排课次(节)">
          <template slot-scope="scope">
            <div>{{ scope.row.preTotalClassTimes }}</div>
          </template>
        </el-table-column>
               <el-table-column align="center" label="已预排课时长(分钟)">
          <template slot-scope="scope">
            <div>{{ scope.row.preMinutes  }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="剩余可排课时长(分钟)">
          <template slot-scope="scope">
            <div>{{ scope.row.preSubMinutes }}</div>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="240px"
          label="操作"
          v-if="team_status == 'PREPARE' || team_status == 'PROGRESS'"
        >
          <template slot-scope="scope" v-if="scope.row.lockFlag != 1">
            <div>
              <el-button
                type="text"
                v-if="scope.row.preTotalClassTimes == 0"
                @click="planCourse(scope.row)"
                >预排课</el-button
              >
              <el-button type="text" v-else @click="cancleCourse(scope.row)"
                >取消排课</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="lastBtnWrap">
        <el-button type="primary" @click="submitCourse">确认排课</el-button>
      </div>
    </div>
    <el-dialog
      title="请设置开课日期"
      :visible.sync="startVisible"
      width="500px"
    >
      <el-form :model="form" ref="form">
        <el-form-item
          label="开课日期"
          prop="startCourseDate"
          :rules="[{ required: true, message: '请选择开课日期' }]"
        >
          <el-date-picker
            v-model.trim="form.startCourseDate"
            type="date"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            placeholder="请选择时间"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setStartTime">确 定</el-button>
      </div>
    </el-dialog>
    <!--    /**
    :classType="classType" // 调整类型
        :teacherList="teacherList"
        :cooperationList="cooperationList" // 助教列表
        :musicGroupId="teamid"
        :activeType="activeType" // 班级类型
        :courseTypeList="courseTypeList" // 班级可排课类型
        :detail="infoDetail" // activeRow
        :studentSubmitedData="studentSubmitedData" 班级的学生信息
        @close="infoVisible = false" // 显示隐藏
        @submited="getList"  刷新列表 */ -->
    <el-dialog
      title="班级排课"
      width="1200px"
      :modal-append-to-body="false"
      :visible.sync="courseVisible"
    >
      <memberClassSetting
        v-if="courseVisible"
        :musicGroupSchoolTermCourseDetailId="musicGroupSchoolTermCourseDetailId"
        :teacherList="teacherList"
        :cooperationList="cooperationList"
        :courseTypeList="courseTypeList"
        :musicGroupId="teamid"
        :activeType="activeType"
        :detail="classDteail"
        :startCourseDate="form.startCourseDate"
        :endSchoolTerm="form.endSchoolTerm"
        @close="courseVisible = false"
        @submited="getList"
      />
    </el-dialog>
  </div>
</template>
<script>
import {
  getAllSignClassandTeacher,
  getTeamBaseInfo,
  musicGroupSchoolTermCourseDetail,
  getTeacher,
  cancelPreCourseSchedule,
  getPreCourseList,
  confirmPreCourseSchedule,
} from "@/api/buildTeam";
import { classTimeList, musicClassTypeList } from "@/utils/searchArray";
import memberClassSetting from "./modals/member-class-setting.vue";
import { getCourseType } from "@/utils/utils";
import { diffTimerFormMinute } from "@/utils/date";
import dayjs from "dayjs";
export default {
  components: { memberClassSetting },
  data() {
    return {
      musicClassTypeList,
      topForm: {
        classType: "",
      },
      team_status: "",
      activeSingleList: [],
      form: { startCourseDate: "", endSchoolTerm: "" },
      startVisible: false,
      pickerOptions: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() + 86400000 <= new Date().getTime(); //开始时间不选时，结束时间最大值小于等于当天
        },
      },
      lastDate: "",
      musicGroupSchoolTermCourseDetailId: "",
      courseVisible: false,
      teacherList: [],
      courseTypeList: [],
      cooperationList: [],
      activeType: "",
      teamid: "",
      classDteail: null,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      this.teamid = this.$route.query.id;
      this.team_status = this.$route.query.team_status;
      if (this.musicGroupInfo) {
        this.organId = this.musicGroupInfos.organId;
        this.chargeTypeId = this.musicGroupInfos.chargeTypeId;
        this.courseViewType = this.musicGroupInfos.courseViewType;
      } else {
        getTeamBaseInfo({ musicGroupId: this.teamid }).then((res) => {
          if (res.code == 200) {
            this.musicGroupInfos = res.data.musicGroup;
            this.organId = this.musicGroupInfos.organId;
            this.chargeTypeId = this.musicGroupInfos.chargeTypeId;
            this.courseViewType = this.musicGroupInfos.courseViewType;
          }
        });
      }
      // 请求接口 获取乐团排课时长
      try {
        const res = await musicGroupSchoolTermCourseDetail({
          musicGroupId: this.teamid,
        });
        if (!res.data) {
          // 说明没有设置时间  弹窗设置
          this.startVisible = true;
        } else {
          this.form.startCourseDate = dayjs(res.data.startCourseDate).format(
            "YYYY-MM-DD"
          );
          this.form.endSchoolTerm = dayjs(res.data.endSchoolTerm).format(
            "YYYY-MM-DD"
          );
          this.musicGroupSchoolTermCourseDetailId = res.data.id;
        }
      } catch (e) {
        console.log(e);
      }

      // 获取主教老师和助教老师
      getTeacher({ organId: this.organId }).then((res) => {
        if (res.code == 200) {
          this.cooperationList = res.data;
          this.teacherList = res.data;
        }
      });
      await this.getList();
    },
    changeMixClass(val) {
      // 根据合奏班id获取合奏班下的所有声部班
      console.log(val);
      this.getList(val);
      this.activeMixClass = val;
    },
    getList(val) {
      return getAllSignClassandTeacher({
        musicGroupId: this.teamid,
        type: val,
      }).then((res) => {
        if (res.code == 200) {
          this.activeSingleList = [];
          res.data.map((item) => {
            if (
              item.type != "HIGH" &&
              item.type != "DEMO" &&
              item.type != "HIGH_ONLINE" &&
              item.type != "MUSIC_NETWORK"
            ) {
              this.activeSingleList.push(item);
            }
          });
          // this.topForm.count = this.activeSingleList.length
        }
      });
    },
    goBack() {
      this.$router.push({
        path: "/business/resetTeaming",
        query: { ...this.$route.query },
      });
      this.$store.dispatch("delVisitedViews", this.$route);
    },
    setStartTime() {
      this.$refs.form.validate(async (res) => {
        if (res) {
          try {
            const res = await musicGroupSchoolTermCourseDetail({
              musicGroupId: this.teamid,
              startCourseDate: this.form.startCourseDate,
            });
            if (res.code == 207) {
              this.$confirm(res.msg, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(async () => {
                  try {
                    const res = await musicGroupSchoolTermCourseDetail({
                      musicGroupId: this.teamid,
                      startCourseDate: this.form.startCourseDate,
                      cleanPreCourseFlag: true,
                    });
                    if (res.data) {
                      this.$message.success("修改成功");
                      this.form.startCourseDate = dayjs(
                        res.data.startCourseDate
                      ).format("YYYY-MM-DD");
                      this.form.endSchoolTerm = dayjs(
                        res.data.endSchoolTerm
                      ).format("YYYY-MM-DD");
                      this.musicGroupSchoolTermCourseDetailId = res.data.id;
                      this.startVisible = false;
                      this.getList();
                    }
                  } catch (e) {
                    this.form.startCourseDate = this.lastDate;
                  }
                })
                .catch(() => {
                  this.form.startCourseDate = this.lastDate;
                });
            }
            console.log(res);
            if (res.code == 200) {
              if (res.data) {
                this.form.startCourseDate = dayjs(
                  res.data.startCourseDate
                ).format("YYYY-MM-DD");
                this.form.endSchoolTerm = dayjs(res.data.endSchoolTerm).format(
                  "YYYY-MM-DD"
                );
                this.musicGroupSchoolTermCourseDetailId = res.data.id;
                this.$message.success("修改成功");
                this.startVisible = false;
                this.getList();
              }
            }
          } catch (e) {
            this.form.startCourseDate = this.lastDate;
            console.log(e);
          }
        }
      });
    },
    resetStartTime() {
      this.lastDate = JSON.parse(JSON.stringify(this.form.startCourseDate));
      this.startVisible = true;
    },
    planCourse(row) {
      this.classDteail = row;
      this.activeType = row.type;
      this.setType(row.type);
      this.courseVisible = true;
    },
    setType(type) {
      this.courseTypeList = getCourseType(type);
    },
    cancleCourse(row) {
      this.$confirm("是否取消预排课", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await cancelPreCourseSchedule({
              classGroupId: row.id,
              musicGroupSchoolTermCourseDetailId:
                this.musicGroupSchoolTermCourseDetailId,
            });
            this.$message.success("取消成功");
            this.getList();
          } catch (e) {}
          // musicGroupSchoolTermCourseDetailId
        })
        .catch(() => {});
    },
    async changeDetail(row, expandedRows) {
      if (expandedRows.length > 0) {
        // 展开 请求接口
        try {
          const res = await getPreCourseList({ classGroupId: row.id });
          this.activeSingleList.forEach((item, index) => {
            if (item.id == row.id) {
              this.activeSingleList[index].courseData = res.data;
            }
          });
          console.log(this.activeSingleList);
        } catch (e) {
          console.log(e);
        }
      }
    },
    submitCourse() {
      // confirmPreCourseSchedule
      this.$confirm("确定提交预排课列表", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            const res = await confirmPreCourseSchedule({
              musicGroupSchoolTermCourseDetailId:
                this.musicGroupSchoolTermCourseDetailId,
            });
            this.$message.success("提交成功");
            await this.getList();
            this.goBack();
          } catch (e) {}
          //
        })
        .catch(() => {});
    },
    getCourseTime(row) {
      return diffTimerFormMinute(
        dayjs(row.classDate).format("YYYY-MM-DD"),
        dayjs(row.startClassTime).format("HH:mm"),
        dayjs(row.endClassTime).format("HH:mm")
      );
    },
  },
  async beforeRouteLeave(to, from, next) {
    let flag = false;
    // if (this.activeSingleList.length > 0) {
    // }
    this.activeSingleList.forEach((item) => {
      if (item.preTotalClassTimes != 0) {
        flag = true;
      }
    });
    if (flag) {
      this.$confirm("预排课程尚未提交，是否确认跳转其他页面？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          next();
          // musicGroupSchoolTermCourseDetailId
        })
        .catch(() => {});
    } else {
      next();
    }
  },
};
</script>
<style lang="scss" scoped>
.lastBtnWrap {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-end;
  margin-right: 1%;
}
</style>
