<template>
  <div id="lesson">
    <transition name="el-zoom-in-center">
      <list-frame
        v-if="view === 'list'"
        returns="/plan/index"
        :title="mainTitle"
        @query="batchSearch"
        :total="total"
        :filter="filterFields"
        :needAdd="false"
        :needPag="false"
      >
        <template #options="{item}">
          <template v-if="item.model === 'term'">
            <el-option v-for="(i, index) in termList" :key="index" :label="`第${i.term}期`" :value="i._id"></el-option>
          </template>
        </template>
        <data-table ref="table" :fields="fields" :data="list" :opera="opera" @date="toDate" @msg="toMsg" @bedroom="toBedroom"></data-table>
      </list-frame>
      <detail-frame v-else title="返回批次列表" :returns="returnList">
        <lesson-plan
          :startDate="batch.startdate"
          :endDate="batch.enddate"
          :classes="classes"
          :trainplanid="id"
          :batchid="batchid"
          @save="handleSave"
        ></lesson-plan>
      </detail-frame>
    </transition>
  </div>
</template>

<script>
import lessonPlan from './lesson-plan';
import listFrame from '@frame/layout/admin/list-frame';
import detailFrame from '@frame/layout/admin/detail-frame';
import dataTable from '@frame/components/data-table';
import _ from 'lodash';
import { createNamespacedHelpers } from 'vuex';
const { mapActions: trainPlan } = createNamespacedHelpers('trainplan');
const { mapActions: mapClasses } = createNamespacedHelpers('classes');
const { mapActions: lesson } = createNamespacedHelpers('lesson'); //教师申请
const { mapActions: bedroom } = createNamespacedHelpers('bedroom'); //分寝

//教师表,地点表,课程表
export default {
  metaInfo: { title: '安排课程' },
  name: 'lesson',
  props: {},
  components: { listFrame, dataTable, detailFrame, lessonPlan },
  data: () => ({
    view: 'list',
    term: '',
    termList: [],
    opera: [
      {
        label: '排课',
        icon: 'el-icon-date',
        method: 'date',
      },
      {
        label: '一键分寝',
        icon: 'el-icon-s-home',
        method: 'bedroom',
      },
      {
        label: '发送确认通知',
        icon: 'el-icon-message-solid',
        method: 'msg',
      },
    ],
    fields: [
      { label: '', prop: 'name' },
      { label: '批数', prop: 'batch' },
    ],
    filterFields: [{ label: '期数', model: 'term', type: 'select' }],
    list: [],
    batch: {},
    total: 0,
    classes: [],
    batchid: [],
  }),
  created() {
    this.search();
  },
  methods: {
    ...trainPlan({ getTrainPlan: 'fetch', sendNotice: 'notice' }),
    ...mapClasses({ getClass: 'query', updateClass: 'update' }),
    ...lesson({ getLessonList: 'query', lessonCreate: 'create', lessonUpdate: 'update' }),
    ...bedroom({ bedroomApart: 'apart' }),
    async search({ skip = 0, limit = 10, ...info } = {}) {
      let res = await this.getTrainPlan(this.id);
      if (this.$checkRes(res)) {
        this.$set(this, `termList`, res.data.termnum);
      }
    },
    batchSearch({ skip, limit, ...info }) {
      let { term } = info;
      this.$set(this, `term`, term);
      let res = this.termList.find(f => f._id === term);
      this.$set(this, `list`, _.sortBy(res.batchnum, ['batch']));
    },
    async toDate({ data }) {
      let res = await this.getClass({ batchid: data._id });
      this.$set(this, 'batchid', data._id);
      // this.view = 'lesson';
      let { startdate, enddate } = data;
      this.$set(this.batch, `startdate`, startdate);
      this.$set(this.batch, `enddate`, enddate);
      //查询到了班级,再查询班级是否有课表
      if (this.$checkRes(res)) {
        let cArr = [];
        for (const tClass of res.data) {
          let lesson = await this.getLessonList({ classid: tClass.id });
          console.log(lesson);
          if (this.$checkRes(lesson)) {
            //根据classid查出的课表一定是唯一的,但是需要用query方法查出,所以如果有值只取出第一条,之后修改这条数据
            let { name, lyteacherid, yclocationid, kzjhlocationid, kbyslocationid, headteacherid, jslocationid } = tClass;
            if (lesson.data.length > 0) {
              //说明这个班已经排过课了,整理数据
              let ldata = JSON.parse(JSON.stringify(lesson.data[0]));
              ldata = { ...ldata, name, lyteacherid, yclocationid, kzjhlocationid, kbyslocationid, headteacherid, jslocationid };
              cArr.push(ldata);
            } else {
              //没排课,需要动手干下,整理好数据
              let object = { name, lyteacherid, yclocationid, kzjhlocationid, kbyslocationid, headteacherid, jslocationid };
              object.classid = tClass.id;
              object.batchid = tClass.batchid;
              object.termid = tClass.termid;
              cArr.push(object);
            }
          }
        }
        this.$set(this, `classes`, cArr);
      }
      this.view = 'lesson';
    },
    returnList() {
      this.view = 'list';
    },
    async handleSave(data) {
      //此处需要3个接口:1,课表添加;2,课表修改;3,班级修改
      //根据data中是否有id,判断是课表的添加还是修改
      //解构出data中class字段,是班级id,将各种地点,礼仪课老师,班主任修改好
      let classid = data.classid;
      let { lessons, termid, batchid, headteacherid, jslocationid, yclocationid, kzjhlocationid, kbyslocationid, lyteacherid } = data;
      let newLessons = { lessons, termid, batchid, classid };
      let newClass = { id: classid, headteacherid, jslocationid, yclocationid, kzjhlocationid, kbyslocationid, lyteacherid };
      let lid = _.get(data, `id`);
      let res;
      if (!lid) {
        res = await this.lessonCreate(newLessons);
      } else {
        newLessons.id = lid;
        res = await this.lessonUpdate(newLessons);
      }
      let check = (res, sucMsg, errMsg) => {
        if (res.errcode === 0) {
          _.isString(sucMsg) ? this.$message.success(sucMsg) : '';
          return true;
        } else {
          this.$message.error(errMsg || '处理失败');
          return false;
        }
      };
      if (check(res, null, `课表${lid ? '修改' : '添加'}失败`)) {
        newClass.lessonid = res.data._id;
        res = await this.updateClass(newClass);
        check(res, '班级信息修改成功', '班级信息修改失败');
      }
    },
    async toMsg({ data }) {
      let res = await this.getClass({ batchid: data._id });
      if (this.$checkRes(res)) {
        let arr = res.data.map(i => i.id);
        if (arr.length > 0) {
          const resNotice = await this.sendNotice({ classids: arr });
          this.$checkRes(resNotice, '发送成功', '发送失败');
        } else this.$message.warning(`该批次下未分班`);
      }
    },
    async toBedroom({ data }) {
      let object = { termid: this.term, trainplanid: this.id, batchid: data._id };
      let res = await this.bedroomApart(object);
      this.$checkRes(res, '分寝成功', res.errmsg);
    },
  },
  computed: {
    mainTitle() {
      let meta = this.$route.meta;
      let main = meta.title || '';
      let sub = meta.sub || '';
      return `${main}${sub}`;
    },
    keyWord() {
      let meta = this.$route.meta;
      let main = meta.title || '';
      return main;
    },
    id() {
      return this.$route.query.id;
    },
  },
};
</script>

<style lang="less" scoped></style>
