<template>
  <div id="index">
    <el-row>
      <el-col :span="24" class="style">
        <el-col :span="24" class="top">
          <NavBar v-show="navShow" :title="title" :isleftarrow="isleftarrow"> </NavBar>
        </el-col>
        <el-col :span="24" class="main">
          <el-tabs v-model="activeName" @tab-click="tabchange">
            <el-tab-pane label="班级名单" name="first">
              <el-col :span="24">
                <name-list :data="studentList" @updateStu="toUpdateStu"></name-list>
              </el-col>
            </el-tab-pane>
            <el-tab-pane label="班级分组" name="second">
              <classGroup
                :groupList="groupList"
                :stuIdAndGroupId="stuIdAndGroupId"
                :noGroupStu="noGroupStu"
                :groupForm="groupForm"
                @saveGroup="saveGroup"
                @joinGroup="joinGroup"
                @exitGroup="exitGroup"
                @affirm="affirm"
                @deleteGroup="deleteGroup"
              ></classGroup>
            </el-tab-pane>
            <el-tab-pane label="平时成绩" name="third">
              <daily :data="studentList" :scoreList="pscoreList" :classInfo="classInfo" :lesson="lesson" @save="dailyUpdate"></daily>
            </el-tab-pane>
            <el-tab-pane label="作业成绩" name="forth">
              <homework
                :homeworkList="homeworkList"
                :homeworkLessonList="homeworkLessonList"
                @onsist="onsist"
                :homeworkForm="homeworkForm"
                @homeworkBtn="homeworkBtn"
                @homeworkOnsubmit="homeworkOnsubmit"
              ></homework>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="24" class="foot">
          <footInfo></footInfo>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import NavBar from '@/layout/common/topInfo.vue';
import footInfo from '@/layout/common/footInfo.vue';
// 班级分组
import classGroup from './newClass/classGroup.vue';
import nameList from './newClass/nameList.vue';
import daily from './newClass/daily.vue';
// 作业成绩
import homework from './newClass/homework.vue';
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: group } = createNamespacedHelpers('group');
const { mapActions: classes } = createNamespacedHelpers('classes');
const { mapActions: util } = createNamespacedHelpers('util');
const { mapActions: student } = createNamespacedHelpers('student');
const { mapActions: pscore } = createNamespacedHelpers('personalscore');
const { mapActions: uploadtask } = createNamespacedHelpers('uploadtask');

export default {
  metaInfo: { title: '班级名单' },
  name: 'index',
  props: {},
  components: {
    NavBar, //头部导航
    footInfo, //底部导航
    // 班级分组
    classGroup,
    //班级名单
    nameList,
    // 日常分
    daily,
    // 作业成绩
    homework,
  },
  data: function() {
    return {
      title: '',
      isleftarrow: '',
      navShow: true,
      // 班级信息
      // 头部标签
      activeName: 'forth',
      // 小组列表
      groupList: [],
      // 登陆者所在组，id
      stuIdAndGroupId: {},
      // 未分组成员
      noGroupStu: [],
      // 创建小组form
      groupForm: {},
      //学生列表
      studentList: [],
      // 平时分列表
      pscoreList: [],
      // 作业成绩
      homeworkList: [],
      homeworkLessonList: [],
      homeworkForm: {},
      // 班级信息
      classInfo: {},
      // 课程信息
      lesson: [],
    };
  },
  async created() {
    await this.getClass();
    await this.toGetStudentList();
    // 查看班级小组
    await this.findGroup();
    // 查询学生作业成绩
    await this.searchHomework();
  },
  methods: {
    ...util({ modelFetch: 'fetch' }),
    ...classes({ getClassInfo: 'fetch' }),
    ...pscore({ getPScoreList: 'query', pscoreOpera: 'opera' }),
    ...group({ groupQuery: 'query', groupDelete: 'delete', groupCreate: 'create', groupUpdate: 'update', groupInsert: 'insert', groupExit: 'exit' }),
    ...student({ getStudentList: 'query', updateStudent: 'update' }),
    ...uploadtask({ uploadtasklist: 'query', uploadtaskUpdate: 'update' }),
    async getClass() {
      const res = await this.getClassInfo(this.user.classid);
      if (this.$checkRes(res)) this.$set(this, `classInfo`, res.data);
      const lres = await this.modelFetch({ model: 'lesson', classid: this.user.classid });
      if (this.$checkRes(lres)) {
        let { lessons } = lres.data;
        if (lessons) {
          lessons = _.uniqBy(
            lessons.filter(f => f.subid),
            'subid'
          );
          console.log(lessons);
          this.$set(this, `lesson`, lessons);
        }
      }
    },
    // first 查学生
    async toGetStudentList() {
      const res = await this.getStudentList({ classid: this.user.classid });
      if (res) this.$set(this, `studentList`, res.data);
    },
    // first 修改学生职位
    async toUpdateStu(data) {
      const res = await this.updateStudent(data);
      if (this.$checkRes(res, '修改成功', res.errmsg || '修改失败')) this.toGetStudentList();
    },
    // second 查询小组
    async findGroup() {
      let stuid = this.user.userid;
      let classid = this.user.classid;
      const res = await this.groupQuery({ classid });
      if (res.errcode === 0) {
        this.$set(this, 'groupList', res.data);
        // 登陆者所在组
        // 组id
        let groupId = '';
        // 所有有组学生id
        let studentIds = [];
        var i = this.groupList.findIndex(value => {
          var v = value.students.findIndex(value => {
            studentIds.push(value.stuid);
            return stuid === value.stuid;
          });
          return v != -1;
        });
        if (i != -1) {
          groupId = this.groupList[i].id;
        }
        // 登录者id+組id
        let stuIdAndGroupId = {
          // 登陆者id
          stuid: stuid,
          // 登陆者属于哪个组id
          groupId: groupId,
        };
        this.$set(this, 'stuIdAndGroupId', stuIdAndGroupId);
        // 未分组成员
        var is = this.groupList.map(value => {
          var v = value.students.map(value => {
            studentIds.push(value.stuid);
          });
          return studentIds;
        });
        let havegroupstuid = is[0];
        var data = this.studentList.map(item => item.id);
        let stuidlist = _.xorWith(data, havegroupstuid, _.isEqual);
        let arr = [];
        let stus = [];
        for (const stuid of stuidlist) {
          arr = this.studentList.filter(item => item.id === stuid);
          stus = [...arr, ...stus];
        }
        this.$set(this, 'noGroupStu', stus);
      }
    },
    // second 创建小组
    async saveGroup({ data }) {
      data.termid = this.user.termid;
      data.batchid = this.user.batchid;
      data.classid = this.user.classid;
      const result = await this.groupCreate(data);
      if (result.errcode == 0) {
        this.findGroup();
      }
    },
    // second 确定小组
    async affirm() {
      for (const val of this.groupList) {
        val.status = '1';
        const res = await this.groupUpdate(val);
      }
    },
    // second 加入小组
    async joinGroup({ groupId }) {
      let data = {
        groupid: groupId,
        stuid: this.user.userid,
        stuname: this.user.name,
      };
      const result = await this.groupInsert(data);
      if (result.errcode == 0) {
        this.findGroup();
      }
    },
    //second  退出小组
    async exitGroup({ groupId }) {
      let data = {
        groupid: groupId,
        stuid: this.user.userid,
      };
      const result = await this.groupExit(data);
      if (result.errcode == 0) {
        this.findGroup();
      }
    },
    // second 删除小组
    async deleteGroup({ groupId }) {
      const result = await this.groupDelete(groupId);
      if (result.errcode == 0) {
        this.findGroup();
      }
    },

    //third 获取该班平时分
    async toGetPScoreList() {
      const res = await this.getPScoreList({ classid: this.user.classid });
      if (this.$checkRes(res)) this.$set(this, `pscoreList`, res.data);
    },
    // third 平时分保存(添加/修改)
    async dailyUpdate(data) {
      const res = await this.pscoreOpera(data);
      if (this.$checkRes(res, '修改成功', res.errmsg || '修改失败')) this.toGetPScoreList();
    },
    tabchange(tab) {
      const { name } = tab;
      if (name === 'third') this.toGetPScoreList();
    },
    // forth作业成绩
    async searchHomework() {
      if (this.user.job == '学委') {
        this.$set(this, `homeworkList`, this.studentList);
      } else {
        let classid = this.user.classid;
        const res = await this.uploadtasklist({ classid });
        for (const val of res.data) {
          var arr = this.studentList.filter(item => item.id === val.studentid);
          this.$set(this, `homeworkList`, arr);
        }
      }
    },
    // 当前学生上传科目成绩
    async onsist({ id }) {
      const res = await this.uploadtasklist({ studentid: id });
      if (res.errcode === 0) {
        this.$set(this, `homeworkLessonList`, res.data);
      }
    },
    // 打开上成绩
    homeworkBtn({ data }) {
      console.log(data);
      this.$set(this, `homeworkForm`, data);
    },
    // 提交上成绩
    async homeworkOnsubmit({ data }) {
      let res = await this.uploadtaskUpdate(data);
      this.searchHomework();
    },
  },
  computed: {
    ...mapState(['user']),
  },
  mounted() {
    this.title = this.$route.meta.title;
    this.isleftarrow = this.$route.meta.isleftarrow;
  },
  watch: {
    $route(to, from) {
      this.title = to.meta.title;
      this.isleftarrow = to.meta.isleftarrow;
    },
  },
};
</script>

<style lang="less" scoped>
.style {
  width: 100%;
  min-height: 667px;
  position: relative;
  background-color: #f9fafc;
}
.top {
  height: 46px;
  overflow: hidden;
}
.main {
  min-height: 570px;
}
/deep/.el-tabs__header {
  margin: 0;
}
/deep/.el-tabs__nav {
  width: 100%;
}
/deep/.el-tabs__item {
  padding: 0;
  width: 25%;
  text-align: center;
}
.foot {
  height: 90px;
  overflow: hidden;
}
</style>
