<template>
  <div id="default-select">
    <el-row type="flex" align="middle" justify="start" class="user-menu" v-if="user" v-loading="loading">
      <el-col :span="15" v-loading="!topOptions">
        当前默认:
        <span>
          <!--  @change="data => changeList('plan', data)" -->
          <el-tooltip :disabled="this.user.type != 0" content="点击更改默认批次" effect="dark" placement="bottom">
            <el-select v-model="topOptions.planyearid" :disabled="this.user.type != 0" placeholder="未设置培训计划" size="mini" @change="initPlan" clearable>
              <el-option v-for="(i, index) in planYearList" :key="index" :label="i.title" :value="i._id"></el-option>
            </el-select>
          </el-tooltip>
        </span>
        <span>
          <!-- @change="getTermList" -->
          <el-tooltip :disabled="this.user.type != 0" content="点击更改默认年度计划" effect="dark" placement="bottom">
            <el-select v-model="topOptions.planid" :disabled="this.user.type != 0" placeholder="未设置年度计划" size="mini" clearable>
              <el-option v-for="(i, index) in planList" :key="index" :label="i.title" :value="i._id"></el-option>
            </el-select>
          </el-tooltip>
        </span>
        <span>
          <!--  @change="toCheckUserType()" -->
          <el-tooltip content="点击更改默认期" effect="dark" placement="bottom">
            <el-select v-model="topOptions.termid" placeholder="未设置默认期" size="mini" @change="initClass" clearable>
              <el-option v-for="(i, index) in termList" :key="index" :label="`第${i.term}期`" :value="i._id"></el-option>
            </el-select>
          </el-tooltip>
        </span>
        <span v-if="user.type == 1 || user.type == 3">
          <!--  @change="setVuexOpt()" -->
          <el-tooltip content="选择要查看的班级" effect="dark" placement="bottom">
            <el-select v-model="topOptions.classid" placeholder="选择要查看的班级" size="mini" clearable>
              <el-option v-for="(i, index) in classList" :key="index" :label="`${i.name}班`" :value="i._id"></el-option>
            </el-select>
          </el-tooltip>
        </span>
        <span>
          <el-button type="text" size="mini" @click="settingSave" v-if="this.user.type == 0">保存默认值</el-button>
        </span>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import _ from 'lodash';
const moment = require('moment');
import { mapState, mapMutations, mapGetters, createNamespacedHelpers } from 'vuex';
const { mapActions: trainBatch } = createNamespacedHelpers('trainBatch');
const { mapActions: trainplan } = createNamespacedHelpers('trainplan');
const { mapActions: setting } = createNamespacedHelpers('setting');
const { mapActions: classes } = createNamespacedHelpers('classes');
const { mapActions: lesson } = createNamespacedHelpers('lesson');
export default {
  name: 'default-select',
  props: {},
  components: {},
  data: function() {
    return {
      loading: false,
      options: undefined,
      planYearList: [],
      planList: [],
      termList: [],
      classList: [],
    };
  },
  async created() {
    await this.init({ type: 'planYear' });
    this.loading = false;
  },
  methods: {
    ...mapMutations(['deleteUser', 'changeOpt']),
    ...trainBatch({ getplanYear: 'query' }),
    ...trainplan({ getPlan: 'query' }),
    ...setting({ sFetch: 'fetch', sUpdate: 'update' }),
    ...classes({ getClassList: 'query' }), //仅供班主任使用
    ...lesson({ teaclass: 'teaclass' }), //仅供老师使用

    async init() {
      let res = await this.getplanYear();
      if (this.$checkRes(res)) this.$set(this, `planYearList`, res.data);
      if (!this.topOptions) return;
      const { planyearid } = this.topOptions;
      if (planyearid) this.initPlan();
    },
    async initPlan() {
      const { planyearid, planid, termid } = this.topOptions;
      if (!planyearid) return;
      const res = await this.getPlan({ planyearid });
      if (this.$checkRes(res)) {
        this.$set(this, `planList`, res.data);
        // 没有有计划id,清空后面的值
        if (!planid) {
          this.toClear('planid');
          this.toClear('termid');
          this.toClear('classid');
          return;
        }
        const plan = res.data.find(f => f._id == planid);
        // 现在的计划id没有找对应的计划,清空后面的值
        if (!plan) {
          this.toClear('planid');
          this.toClear('termid');
          this.toClear('classid');
          return;
        }
        // 找到计划了
        const { termnum } = plan;
        const tlist = _.orderBy(
          termnum.map(i => ({ ...i, term: i.term * 1 })),
          ['term'],
          ['asc']
        );
        this.$set(this, `termList`, tlist);
        if (termid) this.initClass();
      }
    },
    async initClass() {
      const { termid, classid, planid } = this.topOptions;
      let res;
      // 检查身份
      let query = { termid };
      if (this.user.type == 1) {
        query.headteacherid = this.user.userid;
        res = await this.getClassList(query);
      } else if (this.user.type == 3) {
        res = await this.teaclass({ termid: termid, teaid: this.user.userid });
      }
      if (!res) return;
      if (this.$checkRes(res)) {
        const d = res.data.filter(f => f.termid === termid);
        this.$set(this, `classList`, d);
      }
      // 检查是否是初始化,如果是初始化(由上级来),需要检查classid是不是在这里,不在就清除掉
      const r = this.classList.find(f => f._id === classid);
      if (!r) this.toClear('classid');
      if (this.needInit) {
        this.checkToday();
      }
    },
    checkToday() {
      //教师/班主任,如果今天有班级选择
      for (const i of this.classList) {
        const { startdate, enddate } = i;
        const r = moment(moment().format('YYYY-MM-DD')).isBetween(startdate, enddate, null, '[]');
        if (r) {
          const { _id, termid } = i;
          this.$set(this.topOptions, `classid`, _id);
          break;
        }
      }
      sessionStorage.setItem('needInit', false);
    },
    toClear() {
      this.$set(this.topOptions, `classid`, undefined);

      // this.$set(this, `topOptions`, _.omit(this.topOptions, type));
    },
    // setVuexOpt() {
    //   console.log(this.topOptions);
    //   this.changeOpt(this.topOptions);
    // },
    async settingSave() {
      let res = await this.sUpdate(this.topOptions);
      this.$checkRes(res, '设置成功', res.errmsg);
    },
  },
  watch: {
    topOptions: {
      deep: true,
      handler(val, oval) {
        this.changeOpt(val);
      },
    },
  },
  computed: {
    ...mapState(['user', 'defaultOption']),
    ...mapGetters(['topOptions']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
    needInit() {
      let needInit = sessionStorage.getItem('needInit');
      if (needInit === false) return true;
      else return !needInit;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped>
.user-menu {
  height: 4rem;
  .el-col {
    margin-left: 10px;
    span {
      margin-left: 10px;
    }
  }
}
</style>
