<template>
  <div id="plan">
    <!-- 根据计划,获取所有期数及期数下批次,然后提供选择期数;查询出该期数下学校上报的学生,选择学生手动分班  :filter="filterFields"-->
    <list-frame :title="pageTitle" @query="stuSearch" :total="total" :needAdd="false" :needFilter="false" returns="./index">
      <el-card style="padding:10px">
        <el-row>
          <el-form :inline="true" size="mini">
            <el-form-item>
              <el-button type="primary" @click="toAutoSetClass">一键分班</el-button>
            </el-form-item>
          </el-form>
          <el-form :inline="true" size="mini">
            <el-form-item label="批次">
              <el-select v-model="selectInfo.batchid" placeholder="请先选择期数" @change="getClasses">
                <el-option v-for="(i, index) in batchList" :key="index" :label="i.batch" :value="i._id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班级">
              <el-select v-model="selectInfo.classid" placeholder="请先选择批次" @change="getLimit">
                <el-option v-for="(i, index) in classList" :key="index" :label="i.name" :value="i._id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="toSetClass">确认分班</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <el-row type="flex" justify="space-around" :gutter="10" align="middle" style="padding:10px 0;">
          <el-col :span="7">班级需求:{{ selectInfo.personReq }}人</el-col>
          <el-col :span="7">已选择学生:{{ selected.length }}人</el-col>
          <el-col :span="7">男性:{{ selectInfo.male }}人</el-col>
          <el-col :span="7">女性:{{ selectInfo.female }}人</el-col>
        </el-row>

        <data-table
          ref="table"
          :fields="fields"
          :data="list"
          :opera="opera"
          :select="true"
          :selected="selected"
          @edit="toEdit"
          @delete="toDelete"
          @handleSelect="toSelect"
        ></data-table>
      </el-card>
    </list-frame>
  </div>
</template>

<script>
import listFrame from '@frame/layout/admin/list-frame';
import dataTable from '@frame/components/data-table';
import _ from 'lodash';
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: trainPlan } = createNamespacedHelpers('trainplan');
const { mapActions: schPlan } = createNamespacedHelpers('schPlan');
const { mapActions: student } = createNamespacedHelpers('student');
const { mapActions: classes } = createNamespacedHelpers('classes');
const { mapActions: director } = createNamespacedHelpers('director');
const { mapActions: dept } = createNamespacedHelpers('dept');
export default {
  metaInfo: { title: '安排班级' },
  name: 'plan',
  props: {},
  components: { listFrame, dataTable },
  data: () => ({
    opera: [],
    fields: [
      { label: '学生姓名', prop: 'name' },
      { label: '学校', prop: 'school_name' },
      { label: '性别', prop: 'gender' },
    ],
    filterFields: [], //{ label: '期数', model: 'termid', type: 'select' }
    list: [],
    selected: [],
    selectedTest: [],
    total: 0,
    selectInfo: {
      male: 0,
      female: 0,
      personReq: 0,
    },
    termList: [],
    batchList: [],
    classList: [],
    directorList: [],
    deptList: [],
    options: undefined,
    classtype: '0',
  }),
  created() {},
  methods: {
    ...trainPlan(['fetch']),
    ...schPlan({ schQuery: 'query' }),
    ...student({ getStudentList: 'noClass' }), //noClass
    ...classes({ getClassesList: 'query', createClass: 'divide', addStudent: 'addStudent' }),
    ...director({ getDirectorList: 'query' }),
    ...dept({ getDeptList: 'query' }),
    async search({ skip = 0, limit = 10, ...info } = {}) {
      const res = await this.fetch(this.id);
      if (this.$checkRes(res)) {
        let { termnum } = res.data;
        this.$set(this, `termList`, termnum);
        let termid = _.get(this.options, `termid`);
        if (termid) {
          this.getBatch(termid);
          // this.stuSearch();
        }
      }
    },
    //查询选择期上报的学生,提供批次选择
    async stuSearch({ skip = 0, limit = 10, ...info } = {}) {
      const res = await this.getStudentList({ termid: this.options.termid, skip, limit, type: this.classtype });
      if (this.$checkRes(res)) {
        this.$set(this, `list`, res.data);
        this.$set(this, `total`, res.total);
      }
      if (skip !== 0) return;
    },
    getBatch() {
      let termid = _.get(this.options, 'termid');
      if (!termid) return;
      let batchs = this.termList.find(f => f._id === termid);
      if (batchs) {
        let { batchnum } = batchs;
        this.$set(this, `batchList`, batchnum);
      }
    },
    //根据批次id,查询下面的班级
    async getClasses(data) {
      let res = [];
      for (const term of this.termList) {
        let { batchnum } = term;
        let r = batchnum.find(f => f._id == data);
        if (r) res = r.class;
      }
      this.$set(this, `classList`, res);
    },
    toEdit({ data }) {
      this.$router.push({ path: '/dept/detail', query: { id: data.id } });
    },
    async toDelete({ data }) {
      const res = await this.delete(data.id);
      this.$checkRes(res, '删除成功', '删除失败');
      this.search();
    },
    toSelect(selecteds) {
      this.$set(this, `selected`, selecteds);
      let male = 0,
        female = 0;
      for (const i of selecteds) {
        if (i.gender === '1' || i.gender === '男') male++;
        else female++;
      }
      this.$set(this.selectInfo, `male`, male);
      this.$set(this.selectInfo, `female`, female);
    },
    async toAutoSetClass() {
      // 整理数据生成班级;将学生列表重新查询=>为了将已经有班级的学生剔除,以便继续分班(重新查询)
      let info = {};
      info.termid = _.get(this.defaultOption, `termid`);
      info.planid = this.id;
      //手动添加学生使用这部分,接口换了,之后转移到新加的手动
      // let stuList = JSON.parse(JSON.stringify(this.selected));
      // // if (this.isOutRange(stuList)) return;
      // info.students = stuList;
      let res = await this.createClass(info);
      if (this.$checkRes(res, '分班成功', '分班失败')) this.resetData();
      //重置信息
      // this.selectInfo = {
      //   male: 0,
      //   female: 0,
      // };
      // this.selected = [];
      // this.$refs.table.selectReset();
    },
    async toSetClass() {
      let data = {};
      data.id = _.pick(this.selectInfo, ['classid']).classid;
      let stuList = JSON.parse(JSON.stringify(this.selected));
      data.ids = stuList.map(i => i._id);
      let res = await this.addStudent(data);
      if (this.$checkRes(res, '分配成功', res.errmsg || '分配失败')) {
        this.resetData();
        this.search();
      }
    },
    isOutRange(selected) {
      let res = true;
      if (selected.length <= 0) this.$message.warning('请选择学生');
      else if (_.inRange(selected.length, 1, this.selectInfo.personReq * 1)) this.$message.error('选择人数不足');
      else if (selected.length > this.selectInfo.personReq * 1) this.$message('超出班级规定人数');
      else res = false;
      return res;
    },
    getLimit(selected) {
      let res = this.classList.find(f => f._id == selected);
      if (res) {
        this.$set(this.selectInfo, `personReq`, res.number);
        this.$set(this, `classtype`, res.type);
        this.stuSearch();
      }
    },
    resetData() {
      this.list = [];
      this.selected = [];
      this.batchList = [];
      this.classList = [];
      this.selectInfo = {
        male: 0,
        female: 0,
        personReq: 0,
      };
    },
  },
  watch: {
    defaultOption: {
      immediate: true,
      deep: true,
      handler(val) {
        if (!_.get(this, 'options')) {
          this.$set(this, `options`, _.cloneDeep(val));
          this.search();
        } else {
          let nplanid = _.get(val, 'planid');
          let oplanid = _.get(this.options, 'planid');
          if (nplanid && !_.isEqual(nplanid, oplanid)) {
            this.termList = [];
            this.resetData();
            this.search();
          }
          let ntermid = _.get(val, 'termid');
          let otermid = _.get(this.options, 'termid');
          if (ntermid && !_.isEqual(ntermid, otermid)) {
            this.$set(this, `options`, _.cloneDeep(val));
            this.resetData();
            this.getBatch();
            this.stuSearch();
          }
        }
      },
    },
  },
  computed: {
    ...mapState(['user', 'defaultOption']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
    id() {
      return this.defaultOption.planid;
    },
  },
};
</script>

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