<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      班级管理
      <filter-search v-if="permission('/teamCLassList/abnormal')" :keys="['lessThenThreeHighOnline']"
        @reload="reloadSearch" :moreKeys="['organId']" />
    </h2>
    <div class="m-core">
      <save-form ref="searchForm" :inline="true" :model="searchForm" @submit="search" @reset="onReSet">
        <el-form-item prop="search">
          <el-input v-model.trim="searchForm.search" clearable @keyup.enter.native="(e) => {
              e.target.blur();
              $refs.searchForm.save();
              search();
            }
            " placeholder="乐团&班级编号名称"></el-input>
        </el-form-item>
        <el-form-item prop="organIdList">
          <select-all class="multiple" filterable multiple v-model.trim="searchForm.organIdList" clearable
            placeholder="请选择分部">
            <el-option v-for="(item, index) in selects.branchs" :key="index" :label="item.name"
              :value="item.id"></el-option>
          </select-all>
        </el-form-item>
        <el-form-item>
          <el-select v-model.trim="searchForm.groupType" @change="() => {
              searchForm.type = '';
            }
            " filterable placeholder="课程组类型">
            <el-option v-for="(item, index) in courseListType" :key="index" :value="item.value"
              :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <!-- musicClassTypeList -->
        <el-form-item prop="type">
          <el-select v-model.trim="searchForm.type" filterable clearable :disabled="searchForm.groupType != 'MUSIC'"
            placeholder="班级类型">
            <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-item prop="mainTeacherUserId">
          <remote-search :commit="'setTeachers'" v-model="searchForm.mainTeacherUserId" :demissionFlag="true"
            :isForzenWithQueryCondition="true" />
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary">搜索</el-button>
          <el-button native-type="reset" type="danger">重置</el-button>
          <el-button type="primary" v-permission="'export/classGroup'" @click="exportClassGroup">导出</el-button>
        </el-form-item>
      </save-form>
      <div class="tableWrap">
        <el-table style="width: 100%" :header-cell-style="{ background: '#EDEEF0', color: '#444' }" :data="tableList">
          <el-table-column align="center" prop="musicGroupId" label="课程组编号">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.musicGroupId }}</copy-text>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="musicGroupId" label="课程编号">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.id }}</copy-text>
            </template>
          </el-table-column> -->
          <el-table-column align="center" prop="musicGroupName" label="课程组名称"></el-table-column>
          <el-table-column align="center" prop="organName" label="分部名称">
            <template slot-scope="scope">
              <copy-text>{{ scope.row.organName }}</copy-text>
            </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" v-if="item.teacherRole == 'BISHOP'"
                  :key="index">
                  {{ item.userName }}
                </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" v-if="item.teacherRole == 'TEACHING'"
                  :key="index">
                  {{ item.userName }}
                </p>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="已上课时">
            <template slot-scope="scope">
              <div>{{ scope.row.currentClassTimes }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="总课数">
            <template slot-scope="scope">
              <div>{{ scope.row.totalClassTimes }}</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="160px" align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" v-if="permission('classGroup/update')
                " @click="resetClassName(scope.row, true)">班级名称调整</el-button>
              <el-button type="text" v-if="permission('classGroup/update')
                " @click="resetClassName(scope.row, false)">备注</el-button>
              <el-button type="text" @click="addCompound(scope.row)" v-if="scope.row.type != 'MUSIC_NETWORK' &&
                scope.row.groupType == 'MUSIC' &&
                !isAddCom(scope.row) &&
                permission('classGroup/spanGroupMergeClassSplitClassAffirm')
                ">添加合班</el-button>
              <el-button type="text" v-if="isAddCom(scope.row) &&
                permission('classGroup/spanGroupMergeClassSplitClassAffirm')
                " @click="cancleCompound(scope.row)">取消合班</el-button>
              <el-button type="text" v-if="permission('classGroup/delSingle?page=teamCLassList') &&
                scope.row.groupType === 'MUSIC' &&
                (scope.row.studentNum == '0' ||
                  scope.row.totalClassTimes == '0')
                " @click="removeClass(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination sync :total.sync="rules.total" :page.sync="rules.page" :limit.sync="rules.limit"
          :page-sizes="rules.page_size" @pagination="getList" />
      </div>
    </div>
    <classCompound :compoundList="compoundList" v-if="permission('classGroup/spanGroupMergeClassSplitClassAffirm') &&
      compoundList.length > 0
      " @clearCom="clearCom" @getList="getList" @cancleCompound="cancleCompound" />
    <!-- 修改班级名称 -->
    <el-dialog :title="!resetName ? '班级名称调整' : '备注'" width="500px" :visible.sync="classNameVisible" v-if="classNameVisible">
      <changeClassName :classGroupId="activeClass" :detail="classDetail" @submited="submitedResetClassName"
        :resetName="resetName" @close="classNameVisible = false" />
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import load from "@/utils/loading";
import { courseListType } from "@/utils/searchArray";
import { musicClassTypeList } from "@/utils/searchArray";
import {
  getClassGroupPage,
  removeSingleClass,
  getAgreement,
} from "@/api/buildTeam";
import { permission } from "@/utils/directivePage";
import classCompound from "./componentClass/classCompound";
import { Export } from "@/utils/downLoadFile";
import changeClassName from "@/views/teamDetail/components/modals/class-resetclass-name.vue";
import { resetClassName } from '@/views/teamDetail/api'
import qs from "qs";
export default {
  components: { pagination, classCompound, changeClassName },
  data() {
    return {
      searchForm: {
        search: null,
        organIdList: [],
        type: "",
        groupType: "MUSIC",
        mainTeacherUserId: ''
      },
      courseListType: courseListType,
      musicClassTypeList,
      tableList: [],
      compoundList: [],
      hightCount: 0,
      hightOnlineCount: 0,
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      classNameVisible: false,
      classDetail: null,
      activeClass: '',
      resetName: false
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() { },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    const { query, params } = this.$route;
    if (params.search) {
      this.searchForm.search = params.search;
    }
    if (query.type) {
      this.searchForm.type = query.type;
    }
    if (query.organId) {
      this.searchForm.organIdList = [Number(query.organId)];
    }
    // 获取分部
    this.$store.dispatch("setBranchs");
    this.init();
  },
  methods: {
    async getAgreement() {
      try {
        const res = await getAgreement();
        if (!res.data) {
          this.$bus.$emit("showguide", ["agreement"]);
        }
      } catch (e) { }
    },
    reloadSearch() {
      this.rules.page = 1;
      this.getList();
    },
    init() {
      this.getList();
      this.getAgreement();
    },
    async getList() {
      try {
        let { organIdList, ...result } = this.searchForm;
        let obj = {
          ...result,
          lessThenThreeHighOnline: this.$route.query.lessThenThreeHighOnline,
          organIds: this.searchForm.organIdList.join(","),
          page: this.rules.page,
          rows: this.rules.limit,
        };
        const res = await getClassGroupPage(obj);
        this.rules.total = res.data.total;
        this.tableList = res.data.rows;
      } catch (err) {
        console.log(err);
      }
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
      this.$refs.searchForm.resetFields();
      this.searchForm.groupType = "MUSIC";
      this.search();
    },
    async removeClass(scope) {
      try {
        await this.$confirm("是否确定删除该班级?", "提示", {
          type: "warning",
        });
        await removeSingleClass({ classGroupId: scope.row.id });
        this.$message.success("删除成功");
        this.getList();
      } catch (error) { }
    },
    addCompound(row) {
      //  scope.row.type != 'HIGH_ONLINE' &&scope.row.type != 'HIGH'&&
      this.hightOnlineCount = 0;
      this.hightCount = 0;
      this.compoundList.push(row);
      this.compoundList = [...new Set(this.compoundList)];

      this.compoundList.forEach((classes) => {
        if (classes.type == "HIGH") {
          this.hightCount++;
        }
        if (classes.type == "HIGH_ONLINE") {
          this.hightOnlineCount++;
        }
      });
      if (
        this.hightOnlineCount &&
        this.hightOnlineCount != this.compoundList.length
      ) {
        this.$message.error("线上基础技能班仅能和线上基础技能班合并");
        // this.hightOnlineCount = 0;
        // this.hightCount = 0;
        // this.compoundList = [];
        this.compoundList.splice(this.compoundList.length - 1, 1);
      }
      if (this.hightCount && this.hightCount != this.compoundList.length) {
        this.$message.error("基础技能班仅能和基础技能班合并");
        this.compoundList.splice(this.compoundList.length - 1, 1);
        // this.hightOnlineCount = 0;
        // this.hightCount = 0;
        // this.compoundList = [];
      }
    },
    isAddCom(row) {
      let flag = false;
      this.compoundList.forEach((com) => {
        if (com.id == row.id) {
          flag = true;
        }
      });
      return flag;
    },
    cancleCompound(row) {
      let indexNum = null;
      this.compoundList.forEach((com, index) => {
        if (com.id == row.id) {
          indexNum = index;
          if (row.type == "HIGH") this.hightCount--;
          if (row.type == "HIGH_ONLINE") this.hightOnlineCount--;
        }
      });
      if (indexNum + "") {
        this.compoundList.splice(indexNum, 1);
      }
    },
    clearCom() {
      this.compoundList = [];
      this.hightOnlineCount = 0;
      this.hightCount = 0;
    },
    permission(str, parent) {
      return permission(str, parent);
    },
    exportClassGroup() {
      let params = this.searchForm;
      Export(
        this,
        {
          method: "post",
          url: "/api-web/export/classGroup",
          params: qs.stringify({
            ...params,
            organIds: this.searchForm.organIdList.join(","),
            lessThenThreeHighOnline: this.$route.query.lessThenThreeHighOnline,
          }),
        },
        "是否确认导出报表？"
      );
    },
    resetClassName(row, flag) {
      this.classDetail = row;
      this.resetName = !flag;
      this.classNameVisible = true;
    },
    async submitedResetClassName(data) {
      const obj = { ...data };
      resetClassName(obj).then((res) => {
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.classNameVisible = false;
          this.getList();
        }
      });
    },
  },
};
</script>
<style lang='scss' scoped></style>
