<template>
  <div class='course-container'>
    <div class="left">
      <el-form :model="leftFrom"
               ref='leftFrom'
               :rules="leftRules"
               :inline="true">
        <el-form-item label="合奏班"
                      prop='all'>
          <el-select v-model="leftFrom.all"
                     @change="changeMixClass">
            <el-option v-for="(item,index) in maxClassList"
                       :key='index'
                       :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排课时间"
                      prop="time">
          <!-- value-format="yyyy-MM-dd" -->
          <el-date-picker v-model="leftFrom.time"
                          style="width:180px;"
                          align="right"
                          type="date"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="排课次数"
                      prop="num">
          <el-input type="number"
                    v-model="leftFrom.num"></el-input>
        </el-form-item>
      </el-form>
      <p>周次循环<span style="margin-left:10px;">上课时间</span></p>
      <div class="checkWrap">
        <el-checkbox-group v-model="checkList">
          <div class="chioseday"
               v-for="(item,index) in week"
               :key="index">
            <el-checkbox :label="index"
                         v-model="item.isCheck">{{item.name}}</el-checkbox>
            <el-time-select placeholder="起始"
                            v-model="item.startTime"
                            :picker-options="{
                             start: '06:30',
                             step: '00:05',
                             end: '18:30'
                                            }">
            </el-time-select>

            <el-time-select placeholder="结束"
                            v-model="item.endTime"
                            :picker-options="{
                            start: '06:30',
                            step: '00:15',
                            end: '23:30',
                            minTime: item.startTime
                                            }">
            </el-time-select>
          </div>
        </el-checkbox-group>
        <div class="holidayWrap">
          <el-checkbox v-model="isholiday">跳过节假日</el-checkbox>
          <div class="quickBtn"
               @click="classCard">一件排课</div>
        </div>
        <div class="btnWrap">
          <div class="closeBtn"
               @click='resetaLL'>取消排课</div>
          <div class="okBtn"
               @click="submitCardList">确定</div>
        </div>
      </div>

    </div>
    <div class="right">
      <el-table :data='tableList'>
        <el-table-column label="课次">
          <template slot-scope="scope">
            <div>
              {{ scope.$index+1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="classDate"
                         label="日期"
                         width="180">
        </el-table-column>
        <el-table-column prop="week"
                         label="星期"
                         width="180">
        </el-table-column>
        <el-table-column label="课程类型"
                         width="180">
          <template slot-scope="scope">
            <div>
              {{scope.row.type |coursesType }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name"
                         label="课程名称"
                         width="180">
        </el-table-column>
        <el-table-column prop="classTime"
                         label="上课时间"
                         width="180">
        </el-table-column>
        <el-table-column label="操作"
                         width="180">
          <template slot-scope="scope">
            <div>
              <el-button type="text"
                         @click="OpenSign(scope.row)">展开</el-button>
              <el-button type="text"
                         @click='resetMixCourse(scope.row)'>修改</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="btnWrap"
           style="margin-top:40px;">
        <div class="nextBtn"
             @click='gotoNext'>下一步</div>
        <div class="okBtn">返回</div>
      </div>
    </div>
    <el-dialog :visible.sync="resetAllClassVisible"
               width="450px">
      <p style='margin-bottom:20px'>{{resetAllTitle}}</p>
      <div class="resetWrap">
        <!-- signBtnActive: false,
      skipBtnActive: false -->
        <div class="restBtn"
             :class="signBtnActive?'active':''"
             v-if='buttonType == "SINGLE"'
             @click="resetClass">修改为合奏课</div>
        <!--  -->
        <div class="restBtn"
             v-if='buttonType == "MIX"'
             :class="signBtnActive?'active':''"
             @click="resetClass">修改为单技课</div>
        <div class="restBtn"
             @click='skipClass'
             :class="skipBtnActive?'active':''">跳过此天</div>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <div class="okBtns"
             @click="resetMix">确定</div>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="openSignListVisible"
               width="450px">
      <el-table :data='SignList'>
        <el-table-column prop="name"
                         label="班级">
        </el-table-column>
        <el-table-column prop="startClassTime"
                         label="开始时间">
          <template slot-scope="scope">
            <div>
              <p v-if="scope.row.option == 1">{{scope.row.startClassTimeStr  }}</p>
              <el-input v-if="scope.row.option == 2"
                        v-model="scope.row.startClassTimeStr"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="endClassTimeStr"
                         label="结束时间">
          <template slot-scope="scope">
            <div>
              <p v-if="scope.row.option == 1">{{scope.row.endClassTimeStr  }}</p>
              <el-input v-if="scope.row.option == 2"
                        v-model="scope.row.endClassTimeStr"></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="date"
                         label="操作">
          <template slot-scope="scope">
            <div>
              <el-button type="text"
                         v-if="scope.row.option == 2"
                         @click="savecolumn(scope.row)">保存</el-button>
              <el-button type="text"
                         v-if="scope.row.option == 1"
                         @click="savecolumn(scope.row)">修改</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer"
            class="dialog-footer">
        <div class="okBtns"
             @click="resetSiginClass">确定</div>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getAllClass, getAllSignClass, workOut, checkCourse } from '@/api/buildTeam'
import axios from 'axios'
import qs from 'qs'
export default {
  props: {
    teamid: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      resetAllClassVisible: false, //修改合奏课弹窗
      openSignListVisible: false, // 修改单个单技课的弹窗
      first: true,
      leftFrom: {
        all: '',
        time: '',
        num: ''
      },
      tableList: [],
      checkList: [],
      week: [
        {
          startTime: '',
          endTime: '',
          isCheck: false,
          name: '星期日'
        },
        {
          startTime: '',
          endTime: '',
          isCheck: false,
          name: '星期一'
        },
        {
          startTime: '',
          endTime: '',
          isCheck: false,
          name: '星期二'
        },
        {
          startTime: '',
          endTime: '',
          isCheck: false,
          name: '星期三'
        },
        {
          startTime: '',
          endTime: '',
          isCheck: false,
          name: '星期四'
        },
        {
          startTime: '',
          endTime: '',
          isCheck: false,
          name: '星期五'
        },
        {
          startTime: '',
          endTime: '',
          isCheck: false,
          name: '星期六'
        },

      ],
      weekDay: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
      maxClassList: [], // 所有的合奏班
      activeSingleList: [], // 合奏班下的所有单技班
      isholiday: false,
      classCardList: [], //这个是传给后台的真正数据集合
      allChioseDate: [], // 记录所有准备排课的日期
      holidayList: [],
      leftRules: {
        all: [{ required: true, message: '请输选择合奏班', trigger: 'blur' }],
        time: [{ required: true, message: '请选择排课时间', trigger: 'blur' }],
        num: [{ required: true, message: '请输入排课次数', trigger: 'blur' }]
      },
      resetAllTitle: '', // 弹窗名
      buttonType: '',
      activeTime: '', // 选中的当前时间课
      signBtnActive: false,
      skipBtnActive: false,
      SignList: [] // 存储当前合奏课里当天的所有单机课
    }
  },
  mounted () {
    // 根据乐团id 查询 此乐团所有的合奏班
    getAllClass({ musicGroupId: this.teamid }).then(res => {
      if (res.code == 200) {
        this.maxClassList = res.data;
      }
    })
    let year = new Date().getFullYear();
    axios.post('/jiari/', qs.stringify({ d: year })).then(res => {
      if (res) {
        this.holidayList = Object.keys(res.data[year])
      }

    })

  },
  methods: {
    classCard () {
      let flag = false
      this.$refs['leftFrom'].validate(val => {
        if (val) {
          flag = true
        }
      })
      if (!flag) {
        this.$message.error('请填写必要参数在进行排课')
        return;
      }

      let classCount = parseInt(this.leftFrom.num);
      let date = this.leftFrom.time;
      console.log(date);
      this.workOut(date, classCount, this.checkList, this.leftFrom.all);
      this.$refs['leftFrom'].resetFields();
      this.week = this.$options.data().week;
      this.checkList = [];
    },
    chioseWeek (val) {
    },
    getThinkDate (date, num, type = 1) {

      let Stamp = new Date(date.getTime());
      console.log(num);
      // console.log(Stamp.getDate() + parseInt(num))
      Stamp.setDate(Stamp.getDate() + parseInt(num)) // 获取当前月数的第几天

      var year = Stamp.getFullYear(); //获取完整的年份(4位,1970-????)
      var month = Stamp.getMonth() + 1; //获取当前月份(0-11,0代表1月)
      var mvar = '';
      if (month < 10) {
        mvar = '0' + month;
      } else {
        mvar = month + '';
      }
      var day = Stamp.getDate();
      var dvar = '';
      if (day < 10) {
        dvar = '0' + day;
      } else {
        dvar = day + '';
      }
      if (type == 2) {
        return mvar + dvar;
      } else {

        return year + "-" + mvar + '-' + dvar;
      }

    },
    changeMixClass (val) {
      // 根据合奏班id获取合奏班下的所有单技班
      console.log(this.first);
      let activeVal = val;
      if (!this.first) {
        Object.assign(this.$data, this.$options.data());
        getAllClass({ musicGroupId: this.teamid }).then(res => {
          if (res.code == 200) {
            this.maxClassList = res.data;
          }
        })
        this.leftFrom.all = activeVal

      }
      this.first = false;
      this.activeSingleList = [];
      getAllSignClass({ musicGroupId: this.teamid, mixClassGroupId: val }).then(res => {
        if (res.code == 200) {
          this.activeSingleList = res.data.map(item => {
            item.mixid = val
            return item;
          });
        }
      })
    },
    resetMixCourse (row) {
      this.resetAllClassVisible = true;
      this.resetAllTitle = `将${row.classDate} ,${row.week}修改`;
      this.buttonType = row.type;
      this.activeTime = row.classDate;

      // console.log(row)
    },
    resetClass () {
      this.signBtnActive = !this.signBtnActive;
    },
    skipClass () {
      this.skipBtnActive = !this.skipBtnActive;
      // 选中跳过此天
    },
    resetMix () {
      // 修改
      if (this.signBtnActive) {
        // 点击了修改单技课或者合奏课
        let startClassTime;
        let endClassTime;
        if (this.buttonType == 'SINGLE') {
          // 单技改合奏 
          for (let i = 0; i < this.classCardList.length; i++) {
            if (this.activeTime == this.classCardList[i].classDate) {
              this.classCardList.splice(i, 1);
              i--;
            }
          }
          // 修改提交表里的时间
          // 单技改合奏
          for (let i in this.tableList) {
            if (this.activeTime == this.tableList[i].classDate) {

              this.tableList[i].type = "MIX";
              startClassTime = this.tableList[i].startClassTime;
              endClassTime = this.tableList[i].endClassTime;
              // this.tableList[i].classGroupId =  this.tableList[i].id;
              this.classCardList.push(this.tableList[i]);
            }
          }

        } else if (this.buttonType == 'MIX') {
          // 合奏改单技
          for (let i in this.tableList) {
            // console.log(this.activeTime)
            if (this.activeTime == this.tableList[i].classDate) {
              // console.log(this.tableList[i])
              this.tableList[i].type = "SINGLE";
              startClassTime = this.tableList[i].startClassTime;
              endClassTime = this.tableList[i].endClassTime;
            }
          }
          let activeTableItem = {};
          // 修改提交表里的状态
          for (let j = 0; j < this.classCardList.length; j++) {
            for (let i in this.tableList) {
              console.log(this.classCardList[j].classDate, this.tableList[i].classDate)
              if (this.activeTime == this.classCardList[j].classDate && this.activeTime == this.tableList[i].classDate) {
                // this.classCardList[j].type = "SINGLE";
                // this.classCardList[j].startClassTime = startClassTime;
                // this.classCardList[j].endClassTime = endClassTime;
                activeTableItem = this.tableList[i];
                this.classCardList.splice(j, 1);
                j--
              }
            }
          }
          //添加单机班课
          for (let z in this.activeSingleList) {
            let obj = {
              'classDate': activeTableItem.classDate,
              'week': activeTableItem.week,
              'type': 'SINGLE',
              'id': this.activeSingleList[z].id,
              'date': activeTableItem.date,
              'name': this.activeSingleList[z].name,
              'classTime': activeTableItem.classTime,
              'startClassTimeStr': activeTableItem.startClassTimeStr,
              'endClassTimeStr': activeTableItem.endClassTimeStr,
              'weekNum': activeTableItem.weekNum,
              'classGroupId': this.activeSingleList[z].id,
            }
            this.classCardList.push(obj);
          }
          console.log(this.classCardList)
        }

      }
      if (this.skipBtnActive) {
        // 这里是跳过此天
        let lastTime = this.tableList[this.tableList.length - 1].date;
        let weekNum = this.tableList[this.tableList.length - 1].weekNum;
        let id = this.tableList[this.tableList.length - 1].id;
        let startClassTime = this.tableList[this.tableList.length - 1].startClassTimeStr;
        let endClassTime = this.tableList[this.tableList.length - 1].endClassTimeStr;
        for (let i in this.tableList) {
          if (this.tableList[i].classDate == this.activeTime) {
            this.tableList.splice(i, 1);
          }
        }
        for (let j in this.classCardList) {
          if (this.classCardList[j].classDate == this.activeTime) {
            console.log(this.classCardList[j].classDate, this.activeTime)
            this.classCardList.splice(j, 1);
          }
        }
        // console.log(lastTime, weekNum, id);
        this.workOut(lastTime, 1, [weekNum], id, startClassTime, endClassTime);
        this.$message.success('修改成功');
      }
      this.resetAllClassVisible = false;
    },
    // 排课逻辑
    workOut (date, classCount, weekArr, id, startTime = '', endTime = '') {


      while (classCount && classCount > 0) {
        for (let i in weekArr) {
          let date1 = new Date(date.getTime());
          let num; // 下次上课上几天后

          weekArr[i] - date.getDay() >= 0 ? num = weekArr[i] : num = weekArr[i] - date.getDay() + 7
          // console.log(num);
          // return
          let dataStr = this.getThinkDate(date, num);
          let monthDay = this.getThinkDate(date1, num, 2)


          if (this.isholiday) {
            if (this.holidayList.indexOf(monthDay) != -1) {
              // 这里说明有节假日
              continue
            }
          }
          let className;
          this.maxClassList.map(item => {
            if (item.id == id) {
              className = item.name;
              return item.name
            }
          })
          // 排的是合奏班 
          if (!startTime) {
            // 有这个说明是修改=> 没有说明是添加
            if (!this.week[weekArr[i]].startTime || !this.week[weekArr[i]].endTime) {
              // 提示 上课时间必填
              // console.log('进入时间判断')
              this.$message.error('勾选日期的上课时间段必填');
              return;
            }
          }
          let nowStartTime = this.week[weekArr[i]].startTime || startTime;
          let nowEndTime = this.week[weekArr[i]].endTime || endTime;
          this.tableList.push({
            'classDate': dataStr,
            'week': this.week[weekArr[i]].name,
            'type': 'SINGLE',
            'id': id,
            date,
            'name': className,
            'classTime': nowStartTime + '-' + nowEndTime,
            'startClassTimeStr': nowStartTime,
            'endClassTimeStr': nowEndTime,
            'weekNum': weekArr[i],
            'classGroupId': id
          })
          // 这里我排单技课
          for (let j in this.activeSingleList) {
            this.classCardList.push({
              'classDate': dataStr,
              'classGroupId': this.activeSingleList[j].id,
              'startClassTimeStr': nowStartTime,
              'endClassTimeStr': nowEndTime,
              'type': 'SINGLE',
              'mixid': this.activeSingleList[j].mixid,
              date,
              'weekNum': weekArr[i],
              'name': this.activeSingleList[j].name,
              'option': 1
            })
          }
          classCount--
          if (classCount == 0) break
        }
        date.setDate(date.getDate() + 7);


      }
    },
    // 取消排课
    resetaLL () {
      Object.assign(this.$data, this.$options.data());
      getAllClass({ musicGroupId: this.teamid }).then(res => {
        if (res.code == 200) {
          this.maxClassList = res.data;
        }
      })
      let year = new Date().getFullYear();
      axios.post('/jiari/', qs.stringify({ d: year })).then(res => {
        this.holidayList = Object.keys(res.data[year])
      })
    },
    // 点击展开
    OpenSign (row) {
      let id = row.id;
      this.SignList = [];
      for (let i in this.classCardList) {
        if (this.classCardList[i].mixid == row.id && this.classCardList[i].classDate == row.classDate) {
          console.log(this.classCardList[i])
          this.SignList.push(this.classCardList[i])
        }
      }
      console.log(this.SignList);
      this.openSignListVisible = true;
    },
    savecolumn (row) {
      // console.log(row);
      row.option == 1 ? row.option = 2 : row.option = 1
      console.log(this.SignList);
    },
    // 重置单技课
    resetSiginClass () {
      for (let i in this.classCardList) {
        for (let j in this.SignList) {
          if (this.SignList[j].classDate == this.classCardList[i].classDate && this.SignList[j].classGroupId == this.classCardList[i].classGroupId) {
            this.classCardList[i] = this.SignList[j];
            this.$message.success('修改成功');
            this.openSignListVisible = false;
          }
        }
      }

    },
    submitCardList () {
      workOut({ musicGroupID: this.teamid, courseSchedules: this.classCardList }).then(res => {
        if (res.code == 200) {
          this.$message.success('恭喜您排课成功')
          this.classCardList = [];
        }
      })
    },
    gotoNext () {
      checkCourse({ musicGroupId: this.teamid }).then(res => {
        if (res.code == 200) {
          // ...跳转
        }
      }).catch(res => {
        this.$message.error(res.msg)
      })
    }
  },
  watch: {
    resetAllClassVisible (val) {
      if (!val) {
        this.signBtnActive = false;
        this.skipBtnActive = false;
      }
    }
  }

}
</script>
<style lang="scss" scoped>
.course-container {
  padding: 47px 58px;
  background-color: #fff;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  .left {
    width: 330px;
    min-width: 330px;
    margin-right: 90px;
    .chioseday {
      margin-top: 20px;
      .el-date-editor.el-input,
      .el-date-editor.el-input__inner {
        width: 100px;
        margin-left: 20px;
      }
    }
    .holidayWrap {
      margin-top: 34px;
      margin-bottom: 40px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .quickBtn {
        font-size: 16px;
        color: #f85043;
        text-decoration: underline;
        padding-right: 25px;
        cursor: pointer;
      }
    }
    .btnWrap {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      div {
        width: 120px;
        height: 40px;
        border-radius: 4px;
        text-align: center;
        line-height: 40px;
        cursor: pointer;
        color: #fff;
      }
      .closeBtn {
        background-color: #777;
      }
    }
  }
  .right {
    .is-selected {
      color: #1989fa;
    }
    .el-calendar {
      max-width: 950px;
    }
    .btnWrap {
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      div {
        width: 120px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: #fff;
        border-radius: 4px;
        margin-right: 20px;
        cursor: pointer;
      }
      .nextBtn {
        background-color: #444;
      }
      .okBtn {
        background-color: #f97215;
      }
    }
  }
  .resetWrap {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    .restBtn {
      width: 150px;
      height: 50px;
      background: rgba(255, 255, 255, 1);
      border-radius: 5px;
      border: 1px solid rgba(20, 146, 138, 1);
      text-align: center;
      cursor: pointer;
      line-height: 50px;
      color: #14928a;
    }
    .restBtn.active {
      background-color: #14928a;
      color: #fff;
    }
  }
  .okBtns {
    background-color: #f97215;
    width: 120px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #fff;
    border-radius: 4px;
    margin-right: 20px;
    cursor: pointer;
    margin: 0 auto;
  }
}
</style>