<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="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="soundLists[index]"
                               @change='changeList'>
              <!--  sound: this.activeSoundList[item].name,  // id
                 jihua: '10', //计划招生人数
                 yuji: '10', // 预计收费
                 zhonglei: [], // 可选乐器种类
                 fangshi: 2, // 乐器提供方式
                 jiaopu: 'jiaopu1', // 教辅组合
                 type: 1, // 操作
                 id: this.activeSoundList[item].id, //声部id
                 visible: false, // 当前乐器提供方式的pop提示框显示隐藏 -->
              <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="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="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 () {
    // 判断是否带缓存参数
    if (this.$route.query.search) {
      this.Fsearch = this.$route.query.search;
    }
    if (this.$route.query.rules) {
      this.Frules = this.$route.query.rules
    }
  },
  mounted () {
    this.teamList = this.getTeamList;

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

    getSoundTree().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;
    let type = this.topfor.type;

  },
  methods: {
    // 删除声部
    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);
                  }

                }
              }
              console.log('删除');
              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 = [];
      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(this.checkfor),
        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">
.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;
    }
  }
}
</style>