<template>
  <div>
    <div class="listWrap">
      <el-table :data='activeSoundList'
                ref="multipleTable"
                @selection-change="handleSelectionChange"
                :header-cell-style="{background:'#EDEEF0',color:'#444'}"
                highlight-current-row>
        <el-table-column type="selection"
                         width="55">
        </el-table-column>
        <el-table-column label="声部"
                         width="150"
                         prop="sound">
        </el-table-column>
        <!-- <el-table-column label="乐团课程费用"
                         width="150"
                         prop="yuji">
          <template slot-scope="scope">
            <div>
              <el-input type="number"
                        @mousewheel.native.prevent
                        v-model.trim="scope.row.yuji"></el-input>
            </div>
          </template>

        </el-table-column> -->
        <el-table-column label="声部学员">
          <template slot-scope="scope">
            <div>
              <el-button type="text"
                         @click="resetStudent(scope.row)">添加</el-button>
              <!-- <el-button type="text">删除</el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="floor">
        <div class="remove"
             @click="removeListItem">删除</div>
        <div class='add'
             @click="addListItem">添加</div>
      </div>
    </div>
    <el-dialog title="声部选择"
               :visible.sync="dialogTableVisible"
               :modal-append-to-body="false">
      <div class="soundWrap">
        <div class="itemList">
          <div class="categroy"
               v-for="(item,index) in soundList"
               :key="index">
            <p>{{item.name }}</p>
            <el-checkbox-group v-model.trim="soundLists[index]"
                               @change='changeList'>
              <el-checkbox :label="sound.id"
                           @change="checkinlist({'id':sound.id,'sound':sound.name,'yuji':0,studentList:[]})"
                           v-for="(sound,indexs) in item.subjects"
                           :key="indexs">{{sound.name }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <p class='soundSubP'>当前选择声部数:{{chioseSoundNum}}</p>
      <div class="btnWraps">
        <div class="dialogBtn"
             @click="generates">确定</div>
      </div>
    </el-dialog>
    <el-dialog title="学员选择"
               width="800px"
               :visible.sync="studentVisible"
               :modal-append-to-body="false">
      <div class="studentMask">
        <div class="left">
          <h4>当前已选学员</h4>
          <div class="chioseStudentList">
            <div class="studentItem"
                 v-for="(item,index) in activeListStudent"
                 :key="index">
              {{ item.name }}
              <el-button type="text"
                         @click="removeStudent(item)">删除</el-button>
            </div>
          </div>
        </div>
        <div class="right">
          <el-select v-model.trim="activeTeam"
                     filterable
                     style="width:180px"
                     clearable
                     @change="chioseTeam"
                     placeholder="乐团选择">
            <el-option v-for='(item,index) in teamList'
                       :key="index"
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
          <!--  multiple
                     collapse-tags -->
          <el-select v-model.trim="activeChioseSound"
                     style="width:180px"
                     :disabled="!activeTeam"
                     filterable
                     clearable
                     placeholder="声部选择">
            <el-option v-for='(item,index) in chioseSoundList'
                       :key='index'
                       :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
          <el-button type="danger"
                     style="margin-left:20px;"
                     @click="searchStudent">搜索</el-button>

          <!--   列表开始  -->
          <div class="tableList">
            <el-table tooltip-effect="dark"
                      style="width: 100%; margin-top:10px;"
                      :data='studentList'
                      ref='studentList'
                      @selection-change="SelectionStudent">
              <el-table-column type="selection"
                               align='center'
                               width="55">
              </el-table-column>
              <el-table-column prop="name"
                               align='center'
                               width="80"
                               label="姓名">
              </el-table-column>
              <el-table-column prop="gender"
                               align='center'
                               width="55"
                               label="性别">
              </el-table-column>
              <el-table-column prop="musicGroupName"
                               align='center'
                               label="所在乐团">
              </el-table-column>
              <el-table-column prop="soundName"
                               align='center'
                               label="学员声部">
              </el-table-column>
            </el-table>
          </div>

        </div>
      </div>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="studentVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="studentVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <!--   @click="goback1"  @click="submitInfo1" -->
    <div class="btnWrap">
      <div class="PrevBtn"
           @click="goback">上一步</div>
      <div class="submitBtn"
           @click="submitInfo">提交</div>
    </div>
  </div>
</template>
<script>
import store from '@/store'
import { getSubject, getDefaultSubject, getGoods, createTeam, getSoundTree, findSound, teamSoundStudent } from '@/api/buildTeam'
export default {
  name: 'teamResetSound',
  props: ['getTeamList'],
  data () {
    return {
      dialogTableVisible: false,
      studentVisible: false,
      checkList: [],
      isLoop: '',
      activeSoundList: [],
      soundList: [],
      soundLists: [],
      changeList: [],
      multipleSelection: [], // 列表选择的集合 声部
      teamList: [], // 选择的乐团集合
      activeTeam: '', // 选中的乐团
      chioseSoundList: [],//根据选中的乐团id获取的声部集合
      activeChioseSound: '', // 选中声部的集合
      studentList: [], // 选择列表中的学生  展示中的列表
      activeListStudent: [], // 列表中选中的学生,
      allActiveStudent: [], // 所有选中的学生  全局
      activeSoundId: '', //
      Fsearch: null,
      Frules: null
    }
  },
  created () {
    this.init();
  },
  activated () {
    this.init();
  },
  mounted () {

  },
  methods: {
    init () {
      // 判断是否带缓存参数
      if (this.$route.query.search) {
        this.Fsearch = this.$route.query.search;
      }
      if (this.$route.query.rules) {
        this.Frules = this.$route.query.rules
      }
      this.teamList = this.getTeamList;

      this.payfor = this.$store.getters.payList;

      getSoundTree({ tenantId: 1 }).then(res => {
        if (res.code == 200) {
          this.soundList = res.data.rows;
          // // 生成动态的checkList
          for (let key in this.soundList) {
            this.$set(this.soundLists, key, [])
          }
        }
      })

      this.payfor = this.$store.getters.payList;
      this.topfor = this.$store.getters.topinfo;
      this.checkfor = this.$store.getters.checkinfo;
      this.newStudentfor = this.$store.getters.newStudentinfo;
      let type = this.topfor.type;

    },
    // 删除声部
    removeListItem () {
      this.$confirm(`是否删除该声部?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 先获取选择的声部 从全局把 this.allActiveStudent
        for (let i = 0; i < this.activeSoundList.length; i++) {
          for (let j = 0; j < this.multipleSelection.length; j++) {
            if (this.activeSoundList[i].id == this.multipleSelection[j].id) {
              // 在这里把(this.activeSoundList[i]的学生释放出来
              // console.log(this.activeSoundList[i].studentList)
              for (let x in this.allActiveStudent) {
                for (let y in this.activeSoundList[i].studentList) {
                  if (this.allActiveStudent[x].userId == this.activeSoundList[i].studentList[y].userId) {
                    this.allActiveStudent.splice(x, 1);
                  }

                }
              }
              this.activeSoundList.splice(i, 1);
              // 遍历循环所有的group 删除所选id
              for (let key in this.soundLists) {
                if (this.soundLists[key].indexOf(this.multipleSelection[j].id) != -1) {
                  // console.log(this.soundLists[key], this.multipleSelection[j].id, this.soundLists[key].indexOf(this.multipleSelection[j].id));
                  this.soundLists[key].splice(this.soundLists[key].indexOf(this.multipleSelection[j].id), 1)
                }
              }
            }

          }
        }
      }).catch(() => { })

    },
    addListItem () {
      this.dialogTableVisible = true;
    },
    // 点击确认按钮生成表单
    generates () {
      this.dialogTableVisible = false;
    },
    checkinlist (obj) {
      let flag = false;
      this.activeSoundList.map(item => {
        if (item.id == obj.id) {
          flag = true
        }
      })
      if (!flag) {
        this.activeSoundList.push(obj)
      } else {
        for (let i = 0; i < this.activeSoundList.length; i++) {
          if (this.activeSoundList[i].id == obj.id) {
            this.activeSoundList.splice(i, 1);
          }
        }
      }
    },
    handleSelectionChange (e) {
      console.log(e);
      // 点击改变勾选
      this.multipleSelection = e;
    },
    // 点击添加学生
    resetStudent (row) {
      // 乐团id 声部id 
      this.studentVisible = true;
      this.activeSoundId = row.id;

      for (let i in this.activeSoundList) {
        if (this.activeSoundList[i].id == row.id) {
          this.activeListStudent = this.activeSoundList[i].studentList;
        }
      }
    },
    chioseTeam () {
      // console.log(this.activeTeam)
      // 发请求 获取乐团下的所有声部
      findSound({ musicGroupId: this.activeTeam }).then(res => {
        if (res.code == 200) {
          this.chioseSoundList = res.data;
        }
      })
    },
    searchStudent () {
      // activeTeam activeChioseSound
      if (!this.activeTeam || !this.activeChioseSound) {
        this.$message.error('请先选择乐团以及声部进行搜索')
        return;
      }
      console.log('开始搜素学生')
      // activeSoundId 这个id里面的  studentList
      // 在这里要同步当前已选学员的的状态=>  chioseStudentList里赋值
      // 筛选学生1
      for (let i in this.activeSoundList) {
        if (this.activeSoundList[i].id == this.activeSoundId) {
          // console.log(this.activeSoundList[i].id);
          // console.log(this.activeSoundList[i].studentList);
          this.activeListStudent = this.activeSoundList[i].studentList;
        }
      }
      teamSoundStudent({ musicGroupId: this.activeTeam, actualSubjectId: this.activeChioseSound }).then(res => {
        if (res.code == 200) {
          this.studentList = res.data.map(item => {
            let teamName;
            let soundName;
            this.teamList.map(team => {
              if (team.id == this.activeTeam) {
                teamName = team.name
              }
            })
            item.soundName = this.chioseSoundList.map(sound => {
              if (sound.id == this.activeChioseSound) {
                soundName = sound.name
              }
            })
            item.soundName = soundName;
            item.musicGroupName = teamName;
            return item;
          });
          // console.log(this.studentList)
          // 若学生在全局中被选中  则下次更新列表的时候不显示该学生
          for (let i in this.studentList) {
            for (let j in this.allActiveStudent) {
              if (this.allActiveStudent[j].id == this.studentList[i].id) {
                this.studentList.splice(i, 1);
              }
            }
          }
        }
      })
    },
    SelectionStudent (e) {
      // 先找到外面是哪一行的
      for (let i in this.activeSoundList) {
        if (this.activeSoundList[i].id == this.activeSoundId) {
          if (this.activeSoundList[i].studentList.length > 0) {
            this.activeSoundList[i].studentList = this.activeSoundList[i].studentList.concat(e);
          } else {
            this.activeSoundList[i].studentList = e;
          }

          // 去重
          let result = this.objArrayRemoval(this.activeSoundList[i].studentList, 'id')
          // console.log(result);

          // 不对
          this.activeSoundList[i].studentList = result;
          this.activeListStudent = result;
          // // 添加全局 

          if (this.allActiveStudent.length <= 0) {
            // console.log('第一次添加数据')
            this.allActiveStudent = result;
          } else {
            this.allActiveStudent = this.allActiveStudent.concat(result);
          }
          this.allActiveStudent = this.objArrayRemoval(this.allActiveStudent, 'id');
        }
      }

    },
    // 点击删除按钮 重学生集合里删除
    removeStudent (item) {
      // 删除全局
      for (let i in this.allActiveStudent) {
        if (this.allActiveStudent[i].id == item.id) {
          this.allActiveStudent.splice(i, 1);
        }
      }
      // 删除当前
      for (let i in this.activeSoundList) {
        if (this.activeSoundList[i].id == this.activeSoundId) {
          for (let j in this.activeSoundList[i].studentList) {
            if (item.id == this.activeSoundList[i].studentList[j].id) {
              this.activeSoundList[i].studentList.splice(j, 1);
              // 这里做判断 this.studentList 里有没有这个学生(没有)=>判断学生的声部是不是和当前搜索的声部一样 添加
              // 有..  则取消勾选
              let flag = false;
              for (let x in this.studentList) {
                if (this.studentList[x].id == item.id) {
                  flag = true;
                }
              }
              if (flag) {
                // 表里有这个学生
                this.toggleSelection(item, this.studentList);
              } else {
                if (item.actualSubjectId == this.activeChioseSound) {
                  this.studentList.unshift(item)
                }
              }
              this.activeListStudent = this.activeSoundList[i].studentList;
            }

          }

        }
      }
    },
    toggleSelection (item, table) {
      table.forEach(row => {
        if (row.id == item.id) {
          this.$refs['studentList'].toggleRowSelection(row, false);
        }
      })
    },
    // 对象数组去重
    objArrayRemoval (arr, attr) {
      let obj = {};
      let result = [];
      // console.log(this.allActiveStudent.length);
      for (let x in arr) {
        if (!obj[arr[x][attr]]) {
          result.push(arr[x]);
          obj[arr[x][attr]] = true;
        }
      }
      return result;
    },
    submitInfo () {
      let obj = {};
      this.payfor.student.chiose == 'loop' ? obj.months = this.payfor.chioseMonth : obj.months = [];
      // 解析数据
      let courseJson = {};
      for (let i in this.checkfor) {
        if (this.checkfor[i].ischeck) {
          courseJson[i] = this.checkfor[i]
        }
      }
      for (let j in this.newStudentfor) {
        if (this.newStudentfor[j].ischeck) {
          courseJson[j] = this.newStudentfor[j]
        }
      }

      obj.musicGroup = {
        status: 'DRAFT',
        settlementType: this.topfor.salary,
        applyExpireDate: this.topfor.time + ' 00:00:01',
        chargeTypeId: this.topfor.type,
        cooperationOrganId: this.topfor.school,
        teamTeacherId: this.topfor.boss,
        educationalTeacherId: this.topfor.teacher,
        enrollClasses: this.topfor.startClass.join(','),
        name: this.topfor.name,
        organId: this.topfor.section,
        // paymentMonths:obj.months  有待确认
        schoolId: this.topfor.address,
        courseForm: JSON.stringify(courseJson),
        ownershipType: this.topfor.ownershipType
      }
      obj.musicGroupPaymentEntities = []
      // 添加学校主体付费方式
      // console.log(this.payfor.company.ischeck)
      if (this.payfor.school.ischeck) {

        obj.musicGroupPaymentEntities.push({
          'amount': this.payfor.school.price,
          'memo': this.payfor.school.value,
          'paymentMethod': this.payfor.school.chiose,
          'name': '学校'
        })
      }
      // 添加公司主体付费方式
      if (this.payfor.company.ischeck) {
        obj.musicGroupPaymentEntities.push({
          'amount': this.payfor.company.price,
          'memo': this.payfor.company.value,
          'paymentMethod': this.payfor.company.chiose,
          'name': '公司'
        })
      }
      // 添加商品以及教辅
      // 添加声部
      obj.musicGroupSubjectPlans = [];
      if (this.activeSoundList.length <= 0) {
        this.$message.error('乐团至少有一个声部')
        return
      }
      for (let i in this.activeSoundList) {
        let item = {};
        // expectedStudentNum
        item.subName = this.activeSoundList[i].sound;
        item.subjectId = this.activeSoundList[i].id;
        item.fee = this.activeSoundList[i].yuji;
        obj.musicGroupSubjectPlans.push(item);
      }
      // 添加学员
      obj.subjectRegisters = [];
      for (let i in this.activeSoundList) {
        let item = {};
        // expectedStudentNum
        item.subjectId = this.activeSoundList[i].id;
        item.registerIdList = []

        if (this.activeSoundList[i].studentList.length <= 0) {
          this.$message.error(`${this.activeSoundList[i].sound}声部至少有一个学生`)
          return
        }
        for (let j in this.activeSoundList[i].studentList) {
          item.registerIdList.push(this.activeSoundList[i].studentList[j].id)
        }
        obj.subjectRegisters.push(item);
      }
      // 发请求修改
      createTeam(obj).then(res => {
        if (res.code == 200) {
          // 成功 跳转到筹备中
          let id = res.data;
          this.$router.push({ path: '/business/teamDetail', query: { search: this.Fsearch, rules: this.Frules } })
        }
      })
    },
    goback () {
      this.$emit('chiosetab', 0);
    }
  },
  computed: {
    // 返回当前选中声部数量
    chioseSoundNum () {
      let num = 0;
      for (let key in this.soundList) {
        // console.log(this.soundLists[key])
        num += this.soundLists[key].length;
      }
      return num;
    },


  },
  watch: {
    studentVisible (val) {
      if (!val) {
        // 1.选择的团
        this.activeTeam = ''
        // 2.选择的声部
        this.activeChioseSound = ''
        // 3.选择的选中的列表
        this.studentList = [];
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.chioseWrap {
  margin-bottom: 30px;
  display: flex;
  flex-direction: row;
  padding: 0 25px;
  p {
    font-size: 14px;
    margin-right: 30px;
  }
}
.subTitle {
  // width: 1203px;
  height: 40px;
  line-height: 40px;
  background-color: #fefceb;
  padding: 0 25px;
  box-sizing: border-box;
  font-size: 16px;
  color: #474747;
  margin-bottom: 20px;
}
.floor {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  width: 100%;
  height: 48px;
  line-height: 48px;
  background: rgba(237, 238, 240, 1);
  font-size: 14px;
  color: #444;
  align-items: center;
  position: relative;
  z-index: 1;
  .remove {
    width: 98px;
    height: 32px;
    background: rgba(248, 80, 67, 1);
    border-radius: 3px;
    color: #fff;
    line-height: 32px;
    text-align: center;
    margin-left: 164px;
    cursor: pointer;
  }
  .add {
    width: 98px;
    height: 32px;
    background: rgba(20, 146, 138, 1);
    border-radius: 3px;
    color: #fff;
    line-height: 32px;
    text-align: center;
    margin-left: 20px;
    cursor: pointer;
  }
}
.studentMask {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  .left {
    width: 200px;
    margin-right: 20px;
    h4 {
      font-size: 16px;
      color: #444;
      line-height: 38px;
      margin-bottom: 10px;
    }
    .chioseStudentList {
      height: 500px;
      overflow-y: auto;
      border: 1px solid #ccc;
      .studentItem {
        padding-left: 10px;
        line-height: 25px;
      }
    }
  }
  .right {
    .tableList {
      max-height: 500px;
      overflow-y: auto;
    }
  }
}
.soundWrap {
  width: 100%;
  overflow: auto;
  .itemList {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: nowrap;
    flex-grow: 1;
    height: 300px;
    max-height: 300px;
    overflow: auto;
    .categroy {
      width: 150px;
      min-width: 150px;
      .el-checkbox {
        height: 30px;
        line-height: 30px;
        display: block;
        padding-left: 20px;
      }
      p {
        height: 40px;
        line-height: 40px;
        background-color: #edeef0;
        margin-bottom: 15px;
        text-align: center;
      }
    }
  }
}
.soundSubP {
  height: 40px;
  line-height: 40px;
  background-color: #edeef0;
  padding-left: 25px;
}
.btnWraps {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 150px;
  .dialogBtn {
    width: 188px;
    height: 40px;
    background: rgba(249, 114, 21, 1);
    border-radius: 4px;
    line-height: 40px;
    color: #fff;
    text-align: center;
    cursor: pointer;
  }
}
.btnWrap {
  margin-top: 40px;
  .PrevBtn {
    background-color: #444444;
    width: 120px;
  }
  .submitBtn {
    background-color: #f85043;
    width: 120px;
  }
}
</style>