<template>
  <div class="classWrap">
    <div class="left">
      <el-table :data='leftList'
                :header-cell-style="{background:'#EDEEF0',color:'#444'}">
        <el-table-column label="乐团声部"
                         prop="subName"
                         align='center'>
        </el-table-column>

        <el-table-column label="实际缴费人数"
                         prop="paidStudentNum"
                         align='center'>
        </el-table-column>
        <el-table-column label="未分班人数"
                         prop="noClassStudentNum"
                         align='center'>
        </el-table-column>
      </el-table>
    </div>
    <div class="center">
      <el-table :data='centerList'
                :header-cell-style="{background:'#EDEEF0',color:'#444'}">
        <el-table-column label="
                  班级名称"
                         prop="name"
                         align='center'>
        </el-table-column>
        <el-table-column label="声部"
                         prop="subjectName"
                         align='center'>
        </el-table-column>
        <el-table-column label="班级人数"
                         prop="studentNum"
                         align='center'>
        </el-table-column>
        <el-table-column label="操作"
                         align='center'>
          <template slot-scope="scope">
            <div>
              <el-button type="text"
                         @click="removeSingleClass(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="centerInfo">
        <p>当前班级总数（个）：{{ centerList.length }}</p>
        <div class="btnWrap">
          <div class="setBtn"
               @click="setSingleClass">学员分班</div>
          <!-- <div class="okBtn">确定</div> -->
        </div>
      </div>
    </div>
    <!-- v-if="centertList.length>0 " -->
    <div class="right">
      <el-table :data='rightList'
                :header-cell-style="{background:'#EDEEF0',color:'#444'}">
        <el-table-column label="
                  合奏班"
                         prop="name"
                         align='center'>
        </el-table-column>
        <el-table-column label="班级组成"
                         prop="classNames"
                         align='center'>

        </el-table-column>
        <el-table-column label="操作"
                         align='center'>
          <template slot-scope="scope">
            <div>
              <el-button type="text"
                         @click="removeAllClass(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="centerInfo">

        <div class="btnWrap">
          <!-- <el-form :inline="true">
            <el-form-item label="基础技能班数">
              <el-input v-model.trim="hightNum"></el-input>
            </el-form-item>
          </el-form> -->
          <div class="okBtn"
               @click="getNoclassSign">添加</div>
          <div class="setBtn"
               @click="setBossTeacher">下一步</div>
        </div>
      </div>
    </div>
    <el-dialog title="班级设置"
               :visible.sync="classVisible">
      <div class="classMaskWrap">
        <div class="maskLeft">
          <h3>声部 已选{{ soundSize }}
          </h3>
          <el-checkbox-group v-model.trim="maskList.subjectCheckList"
                             class='checkGroup'
                             @change="chioseSound">
            <el-checkbox v-for="(item,index) in leftList"
                         :key="index"
                         :label="item.subjectId">{{ item.subName }}</el-checkbox>
          </el-checkbox-group>
        </div>
        <div class="maskRight">
          <div class="rightGroup"
               v-for="(item,index) in studentsGroup"
               :key='index'>
            <!-- @change="handleCheckAllChange(item.rows,index)" -->
            <h3>{{item.subjectName}}的学员名单 <el-checkbox v-model.trim="maskList.studentsGroup[index]"
                           @change="handleCheckAllChange(item.rows,index)">全选</el-checkbox>
            </h3>
            <el-checkbox-group v-model.trim="maskList.checkList[index]"
                               @change="handleCheckedCitiesChange(index,item.rows)"
                               class='checkGroup'>
              <el-checkbox v-for="(stu,num) in item.rows"
                           :key='num'
                           :label="stu.userId">{{ stu.name }}</el-checkbox>
            </el-checkbox-group>
          </div>

        </div>
      </div>
      <div class="classMaskbottom">
        <h3></h3>
        <el-form :inline="true"
                 :model="className"
                 :rules="classNameRules"
                 ref='className'>
          <el-form-item label="班级名称"
                        prop='name'>
            <el-input v-model.trim="className.name"></el-input>
          </el-form-item>
          <el-form-item label="已选声部"
                        prop="sound">
            <el-input :disabled="true"
                      v-model.trim="className.sound"></el-input>
          </el-form-item>
          <el-form-item label="班级人数">
            <el-input :disabled="true"
                      v-model.trim="activeStudents.length"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="classVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addNewClass">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="合奏班设置"
               width="600px"
               :visible.sync="allVisible">
      <el-checkbox-group v-model.trim="allMaskList.signClassList"
                         class='checkGroup'>
        <el-checkbox v-for="(item,index) in NoClassSingle"
                     :key='index'
                     :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-form :model="allList"
               ref="allRules"
               style="margin-top:30px;"
               :rules="allRules"
               :inline="true">
        <el-form-item label="请输入合奏班名称"
                      prop="name">
          <el-input type="text"
                    v-model.trim="allList.name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="allVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addAllClass">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="乐队指导"
               width="600px"
               :visible.sync="teacherVisible">
      <el-form :inline="true"
               ref='teacherForm'
               :model="teacherForm">
        <el-form-item label="乐队指导"
                      prop='name'
                      :rules="[{required: true, message: '请选择乐队指导', trigger: 'blur'}]">
          <el-select v-model.trim="teacherForm.name"
                     filterable
                     clearable>
            <el-option v-for="(item,index) in teacherList"
                       :key="index"
                       :value="item.id"
                       :label="item.realName"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="teacherVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="gotoNext">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryEmployByOrganId } from '@/api/systemManage'
import { getTeamRecruit, getSingleClass, getNoClassStudent, addSingleClass, removeSingleClass, addAllClass, getAllClass, findNoClassSingle, removeAllClass, getTeacher, checkAllStudent, getTeamBaseInfo } from "@/api/buildTeam"
export default {
  name: 'setClass',
  props: {
    teamid: {
      type: String,
      required: true
    },
    isSetSalary: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      classVisible: false, // 班级设置弹窗
      allVisible: false, // 合奏班弹窗设置
      teacherVisible: false,
      leftList: [],
      centerList: [],
      rightList: [],
      maskList: {
        subjectCheckList: [],
        checkList: [],
        checkAll: false,
        isIndeterminate: [],
        studentsGroup: []
      },
      allMaskList: {
        signClassList: []
      },
      soundSize: 0,
      activeStudents: [],  // 选中的所有学生
      studentsGroup: {}, // 存储所有声部 所有学生的集合表
      className: {
        name: '',
        sound: ''
      },
      classNameRules: {
        name: [
          { required: true, message: '请输入班级名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      allList: { //合奏班名字确认
        name: ''
      },
      allRules: {
        name: [
          { required: true, message: '请输入班级名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      NoClassSingle: [],
      teacherList: [],
      teacherForm: {
        name: ''
      },
      hightNum: '',
      organId: ''

    }
  },
  watch: {
    classVisible (val) {
      if (!val) {
        this.classVisible = false;
        this.maskList.subjectCheckList = [];
        this.studentsGroup = [];
        this.activeStudents = [];
        this.$refs['className'].resetFields();
        this.getSingleClass();
      }
    }
  },
  created () {
    this.organId = sessionStorage.getItem('createTeamOrgnId') || null
  },
  mounted () {
    sessionStorage.setItem('setStep', 0)
    getTeamRecruit({ musicGroupId: this.teamid }).then(res => {
      // 获取乐团声部集合
      if (res.code == 200) {
        this.leftList = res.data;
      }
    })
    this.getSingleClass();
    this.getAllClass();
    // 获取所有老师的列表
    queryEmployByOrganId({ organId: this.organId, rows: 1000 }).then(res => {
      if (res.code == 200) {
        this.teacherList = res.data.rows;
      }
    })
    getTeamBaseInfo({ musicGroupId: this.teamid }).then(res => {
      if (res.code == 200) {
        res.data.musicGroup.directorUserId ? this.teacherForm.name = res.data.musicGroup.directorUserId : this.teacherForm.name = ''
      }
    })

  }, methods: {
    getAllClass () {
      getAllClass({ musicGroupId: this.teamid }).then(res => {
        if (res.code == 200) {
          this.rightList = res.data;
        }
      })
    },
    getSingleClass () {
      getSingleClass({ musicGroupId: this.teamid }).then(res => {
        if (res.code == 200) {
          // 单技班列表
          this.centerList = res.data;
        }
      })
    },
    handleCheckAllChange (val, index) {
      // 全选
      // 1.val:选项框里的所有选项
      // 2.哪一个
      if (this.maskList.studentsGroup[index]) {
        this.maskList.checkList[index] = []
        for (let i in val) {
          // 存储的数组 activeStudents
          this.maskList.checkList[index].push(val[i].userId);
          this.activeStudents.push(val[i].userId)
          this.activeStudents = Array.from(new Set(this.activeStudents))
          // 并且把所有的学生 添加到勾选的学生列表
        }
      } else {
        for (let i in this.activeStudents) {
          for (let j in this.maskList.checkList[index]) {
            if (this.maskList.checkList[index][j] == this.activeStudents[i]) {
              this.activeStudents.splice(i, 1);
            }
          }
        }
        this.maskList.checkList[index] = []
      }

    },
    handleCheckedCitiesChange (index, list) {
      // 单选学生触发事件
      // 此处需要同步全选按钮状态
      // maskList.studentsGroup[index]

      if (list.length == this.maskList.checkList[index].length) {
        //全选选中
        this.maskList.studentsGroup[index] = true;
      } else {
        this.maskList.studentsGroup[index] = false;
      }

      let arr = [];
      for (let i in this.maskList.checkList) {
        for (let j in this.maskList.checkList[i]) {
          arr.push(this.maskList.checkList[i][j])
        }
      }
      this.activeStudents = arr;
    },
    // 设置单技课
    setSingleClass () {
      if (this.isSetSalary) {
        this.$message.error('课酬确认后无法编辑')
        return;
      }
      this.classVisible = true;
    },
    chioseSound (val) {
      // 清空选中学生
      this.activeStudents = [];
      // 清空全选
      // this.maskList.studentsGroup
      for (let i in this.maskList.studentsGroup) {
        this.maskList.studentsGroup[i] = false;
      }
      for (let j in this.maskList.checkList) {
        this.maskList.checkList[j] = []

      }
      this.soundSize = val.length;
      getNoClassStudent({
        musicGroupId: this.teamid,
        actualSubjectId: val.join(',')
      }).then(res => {
        if (res.code == 200) {
          this.studentsGroup = res.data
          let str = ''
          // 生成动态的checkList
          for (let key in this.studentsGroup) {
            this.$set(this.maskList.checkList, key, []);
            str += this.studentsGroup[key].subjectName + '+';
          }
          str = str.substring(0, str.length - 1);
          this.className.sound = str;
        }
      })
    },
    // 添加单技班
    addNewClass () {
      this.$refs['className'].validate(valid => {
        if (valid) {
          addSingleClass({
            musicGroupId: this.teamid,
            name: this.className.name,
            subjectIdList: this.maskList.subjectCheckList.join(','),
            teachMode: 'OFFLINE',
            userIds: this.activeStudents.join(','),
            studentNum: this.activeStudents.length,
            type: 'NORMAL'
          }).then(res => {
            if (res.code == 200) {
              // 成功刷新班级列表 清空数据
              this.$message.success('添加成功');
              this.classVisible = false;
              this.maskList.subjectCheckList = [];
              this.studentsGroup = [];
              this.activeStudents = [];
              this.$refs['className'].resetFields();
              this.getSingleClass();
              getTeamRecruit({ musicGroupId: this.teamid }).then(res => {
                // 获取乐团声部集合
                if (res.code == 200) {
                  this.leftList = res.data;
                }
              })

            }
          })
        } else {
          this.$message.error('请输入班级名称')
        }
      })
      return;

    },
    removeSingleClass (row) {
      if (this.isSetSalary) {
        this.$message.error('课酬确认后无法编辑')
        return;
      }
      removeSingleClass({ classGroupId: row.id }).then(res => {
        if (res.code == 200) {
          this.$message.success('删除成功');
          this.getSingleClass();
          getTeamRecruit({ musicGroupId: this.teamid }).then(res => {
            // 获取乐团声部集合
            if (res.code == 200) {
              this.leftList = res.data;
            }
          })
        }
      })
    },
    getNoclassSign () {
      if (this.isSetSalary) {
        this.$message.error('课酬确认后无法编辑')
        return;
      }
      this.allMaskList.signClassList = [];
      findNoClassSingle({ musicGroupId: this.teamid }).then(res => {
        if (res.code == 200) {
          this.NoClassSingle = res.data;
          this.allVisible = true;
        }
      })
    },
    // 添加合奏班
    addAllClass () {

      if (!this.allMaskList.signClassList.join(',')) {
        this.$message.error('请至少选择一个单技班')
        return;
      }
      addAllClass({
        musicGroupId: this.teamid,
        name: this.allList.name,
        classGroupIds: this.allMaskList.signClassList.join(',') || null
      }).then(res => {
        if (res.code == 200) {
          this.$message.success('恭喜您创建成功');

          this.allVisible = false;
          this.getAllClass();
          this.$refs['allRules'].resetFields();
        }
      })
    },
    // 删除合奏班
    removeAllClass (row) {
      if (this.isSetSalary) {
        this.$message.error('课酬确认后无法编辑')
        return;
      }
      removeAllClass({ classGroupId: row.id }).then(res => {
        if (res.code == 200) {
          this.$message.success('删除成功')
          this.getAllClass();
        }
      });
    },
    setBossTeacher () {
      if (this.isSetSalary) {
        this.$message.error('课酬确认后无法编辑')
        return;
      }
      this.teacherVisible = true;

    },
    gotoNext () {

      // 跳转到下一步
      // if (!this.hightNum) {
      //   this.$message.error('基础技能班数必填');
      //   return
      // }
      this.$refs['teacherForm'].validate(res => {
        if (res) {
          // 发请求
          checkAllStudent({ musicGroupId: this.teamid, teacherId: this.teacherForm.name, improventClassesNum: this.hightNum }).then(res => {
            if (res.code == 200) {
              this.$refs['teacherForm'].resetFields()
              this.teacherVisible = false;
              this.$emit('gotoNav', 1);
            }

          }).catch(res => {
            this.teacherVisible = false;
            this.teacherForm.name = '';
          })
        }

      });
    },
  },

}
</script>
<style lang="scss" scoped>
.classWrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  .left {
    width: 275px;
    background-color: #fff;
    height: 80vh;
    overflow: auto;
  }
  .center {
    // background-color: #fff;
    width: 400px;
    margin-left: 12px;
    .centerInfo {
      background-color: #fff;
      color: #444;
      padding: 15px;
      .btnWrap {
        margin-top: 38px;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        .setBtn {
          width: 120px;
          height: 40px;
          background: rgba(68, 68, 68, 1);
          border-radius: 4px;
          color: #fff;
          line-height: 40px;
          text-align: center;
          cursor: pointer;
        }
        .okBtn {
          width: 120px;
          height: 40px;
          background: rgba(249, 114, 21, 1);
          border-radius: 4px;
          color: #fff;
          line-height: 40px;
          text-align: center;
          cursor: pointer;
        }
      }
    }
  }
  .right {
    flex-grow: 1;
    margin-left: 12px;
    .centerInfo {
      background-color: #fff;
      color: #444;
      padding: 15px;
      .btnWrap {
        margin-top: 38px;
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        .setBtn {
          width: 120px;
          height: 40px;
          background: rgba(68, 68, 68, 1);
          border-radius: 4px;
          color: #fff;
          line-height: 40px;
          text-align: center;
          cursor: pointer;
        }
        .okBtn {
          width: 120px;
          height: 40px;
          background: rgba(249, 114, 21, 1);
          border-radius: 4px;
          color: #fff;
          line-height: 40px;
          text-align: center;
          cursor: pointer;
        }
      }
    }
  }
  .classMaskWrap {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    max-height: 350px;
    overflow: auto;

    .maskLeft {
      width: 200px;

      h3 {
        height: 40px;
        line-height: 40px;
        background-color: #edeef0;
        font-size: 16px;
        font-weight: normal;
        color: #444;
        padding-left: 25px;
      }
      .checkGroup {
        .el-checkbox {
          padding-left: 25px;
          height: 30px;
          line-height: 30px;
          width: 100%;
        }
      }
    }
    .maskRight {
      margin-left: 30px;
      flex: 1;
      .rightGroup {
        h3 {
          height: 40px;
          line-height: 40px;
          background-color: #edeef0;
          font-size: 16px;
          font-weight: normal;
          color: #444;
          padding-left: 25px;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          padding-right: 15px;
        }
        .checkGroup {
          padding-left: 25px;
          .el-checkbox {
            height: 30px;
            line-height: 30px;
            width: 75px;
          }
        }
      }
    }
  }
  .classMaskbottom {
    h3 {
      height: 40px;
      line-height: 40px;
      background-color: #edeef0;
      margin-bottom: 30px;
    }
  }
}
</style>