<template>
  <div class="m-container">
    <div class="infoWrap">
      <el-form :model="accompanyForm"
               :inline="true"
               label-position="left">
        <el-form-item label="每周可预约课次"
                      style="position: relative"
                      label-width="130px">
          <el-tooltip placement="top"
                      popper-class="mTooltip">
            <div slot="content">不填时，默认不限制上课次数</div>
            <!-- <img :src="imageIcon" class="micon el-tooltip" style="width:8px height:8px" alt /> -->
            <i class="el-icon-question micon el-tooltip"
               style="font-size: 18px; color: #F56C6C"></i>
          </el-tooltip>
          <el-input type="number"
                    @mousewheel.native.prevent
                    v-model.trim="accompanyForm.count"></el-input>
        </el-form-item>
        <el-form-item label="每周休息的周次">
          <el-select v-model="accompanyForm.week"
                     clearable
                     @change="setHoliday">
            <el-option label="周一"
                       value="1" />
            <el-option label="周二"
                       value="2" />
            <el-option label="周三"
                       value="3" />
            <el-option label="周四"
                       value="4" />
            <el-option label="周五"
                       value="5" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="submitOk" v-permission="'teacherFreeTime/updateSet'">确定</el-button>
        </el-form-item>-->
      </el-form>
    </div>
    <!-- 开始布局上课时间段 -->
    <div class="timerWrap">
      <el-row class="music-title">
        <el-col :span="2">周次</el-col>
        <el-col :span="18">时间段</el-col>
      </el-row>
      <el-row v-for="(item,i) in weekList"
              :key="i">
        <el-col :span="2">{{item.name}}</el-col>
        <el-col :span="18">
          <el-tag v-for="(s,index) in item.timeList"
                  :key="index"
                  :type="item.isHoliday?'info':''"
                  effect="dark"
                  :closable="!item.isHoliday"
                  :disable-transitions="true"
                  @close="subjectDelete(item,index)">{{s.startTime.substring(0,s.startTime.length - 3)+'-'+s.endTime.substring(0,s.endTime.length - 3)}}</el-tag>
          <span style="display: inline-block;">
            <el-button v-if="!item.isHoliday"
                       key="tag"
                       type="primary"
                       style="background:#ececec;border:1px solid #ececec;color:#666"
                       size="mini"
                       round
                       icon="el-icon-plus"
                       @click="subjectAdd(item)">添加</el-button>
          </span>
        </el-col>
      </el-row>
    </div>
    <el-dialog :visible.sync="timeVisible"
               width="600px"
               :before-close="closetimeVisible">
      <el-form :inline="true"
               v-model="timeForm"
               ref="timeForm">
        <el-form-item label="开始时间">
          <el-time-picker v-model="startTime"
                          @change="changeStartTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          :picker-options="{
              selectableRange:`04:00:00 - 23:59:00`
  }"
                          placeholder="选择时间"></el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-time-picker v-model="endTime"
                          format="HH:mm"
                          value-format="HH:mm"
                          :picker-options="{
              selectableRange:`${startTime ? startTime+':00' : '04:00:00'}-23:59:00`
  }"
                          placeholder="选择时间"></el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="timeVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addTimerSub">确 定</el-button>
      </div>
    </el-dialog>
    <div class="btnWrap">
      <div class="newBand"
           @click="submitOk"
           v-permission="'teacherFreeTime/updateSet'">确定</div>
      <div class="newBand"
           @click="resetTime">重置</div>
    </div>
  </div>
</template>
<script>
import { teacherFreeTime, resetTeacherFreeTime } from "@/api/teacherManager";
export default {
  props: ["teacherId"],
  data () {
    return {
      accompanyForm: {
        count: null,
        week: null
      },
      accompanyId: null,
      // imageIcon: require("@/assets/images/base/warning.png"),
      weekList: {
        monday: {
          timeList: [],
          name: "周一",
          isHoliday: false
        },
        tuesday: {
          timeList: [],
          name: "周二",
          isHoliday: false
        },
        wednesday: {
          timeList: [],
          name: "周三",
          isHoliday: false
        },
        thursday: {
          timeList: [],
          name: "周四",
          isHoliday: false
        },
        friday: {
          timeList: [],
          name: "周五",
          isHoliday: false
        },
        saturday: {
          timeList: [],
          name: "周六",
          isHoliday: false
        },
        sunday: {
          timeList: [],
          name: "周日",
          isHoliday: false
        }
      },
      activeItem: null,
      timeVisible: false,
      startTime: "",
      endTime: "",
      timeForm: {}
    };
  },
  created () {
    this.init();
  },
  activated () {
    this.init();
  },
  methods: {
    init () {
      //  this.teacherId = this.$route.query.teacherId ;
      if (this.$route.query.search) {
        this.Fsearch = this.$route.query.search;
      }
      if (this.$route.query.rules) {
        this.Frules = this.$route.query.rules;
      }
      if (this.teacherId) {
        teacherFreeTime({ id: this.teacherId }).then(res => {
          if (res.code == 200 && res.data) {
            this.accompanyId = res.data.id;
            res.data.totalTimes
              ? (this.accompanyForm.count = res.data.totalTimes)
              : (this.accompanyForm.count = null);
            res.data.holiday
              ? (this.accompanyForm.week = res.data.holiday.toString())
              : (this.accompanyForm.week = null);
            this.setHoliday(res.data.holiday);
            // 写入默认数据
            res.data.monday
              ? (this.weekList.monday.timeList = JSON.parse(res.data.monday))
              : (this.weekList.monday.timeList = []);
            res.data.tuesday
              ? (this.weekList.tuesday.timeList = JSON.parse(res.data.tuesday))
              : (this.weekList.tuesday.timeList = []);
            res.data.wednesday
              ? (this.weekList.wednesday.timeList = JSON.parse(
                res.data.wednesday
              ))
              : (this.weekList.wednesday.timeList = []);
            res.data.thursday
              ? (this.weekList.thursday.timeList = JSON.parse(
                res.data.thursday
              ))
              : (this.weekList.thursday.timeList = []);
            res.data.friday
              ? (this.weekList.friday.timeList = JSON.parse(res.data.friday))
              : (this.weekList.friday.timeList = []);
            res.data.saturday
              ? (this.weekList.saturday.timeList = JSON.parse(
                res.data.saturday
              ))
              : (this.weekList.saturday.timeList = []);
            res.data.sunday
              ? (this.weekList.sunday.timeList = JSON.parse(res.data.sunday))
              : (this.weekList.sunday.timeList = []);
          }
        });
      }
    },
    submitOk () {
      this.$confirm("确认保存设置?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 处理数据
        if (this.accompanyForm.count) {
          let reg = /^\+?[1-9]\d*$/;
          if (!reg.test(this.accompanyForm.count)) {
            this.$message.error("每周可预约课次可以不填,或大于0的正整数");
            return;
          }
        }
        let monday, tuesday, wednesday, thursday, friday, saturday, sunday;
        this.weekList.monday.isHoliday
          ? (monday = null)
          : (monday = this.weekList.monday.timeList);
        this.weekList.tuesday.isHoliday
          ? (tuesday = null)
          : (tuesday = this.weekList.tuesday.timeList);
        this.weekList.wednesday.isHoliday
          ? (wednesday = null)
          : (wednesday = this.weekList.wednesday.timeList);
        this.weekList.thursday.isHoliday
          ? (thursday = null)
          : (thursday = this.weekList.thursday.timeList);
        this.weekList.friday.isHoliday
          ? (friday = null)
          : (friday = this.weekList.friday.timeList);
        this.weekList.saturday.isHoliday
          ? (saturday = null)
          : (saturday = this.weekList.saturday.timeList);
        this.weekList.sunday.isHoliday
          ? (sunday = null)
          : (sunday = this.weekList.sunday.timeList);
        resetTeacherFreeTime({
          holiday: this.accompanyForm.week,
          userId: this.teacherId,
          id: this.accompanyId,
          totalTimes: this.accompanyForm.count,
          monday: monday && monday.length > 0 ? JSON.stringify(monday) : null,
          tuesday:
            tuesday && tuesday.length > 0 ? JSON.stringify(tuesday) : null,
          wednesday:
            wednesday && wednesday.length > 0
              ? JSON.stringify(wednesday)
              : null,
          thursday:
            thursday && thursday.length > 0 ? JSON.stringify(thursday) : null,
          friday: friday && friday.length > 0 ? JSON.stringify(friday) : null,
          saturday:
            saturday && saturday.length > 0 ? JSON.stringify(saturday) : null,
          sunday: sunday && sunday.length > 0 ? JSON.stringify(sunday) : null
        }).then(res => {
          if (res.code == 200) {
            this.$message.success("保存成功");
            this.$router.push({
              path: "/business/teacherList",
              query: { rules: this.Frules, search: this.Fsearch }
            });
          }
        });
      });
    },
    setHoliday (val) {
      // console.log(val)

      val = parseInt(val);
      // console.log(val)
      let arr = [
        "monday",
        "tuesday",
        "wednesday",
        "thursday",
        "friday",
        "saturday",
        "sunday"
      ];
      for (let i = 0; i < arr.length; i++) {
        this.weekList[arr[i]].isHoliday = false;
      }
      if (val) {
        this.weekList[arr[val - 1]].isHoliday = true;
      }
    },
    // 删除
    subjectDelete (item, index) {
      for (let date in this.weekList) {
        if (this.weekList[date].name == item.name) {
          this.weekList[date].timeList.splice(index, 1);
        }
      }
    },
    // 添加
    subjectAdd (item) {
      this.activeItem = item;
      this.timeVisible = true;
      // console.log(item)
    },
    // 提交添加的时间
    addTimerSub () {
      // this.$refs["timeForm"].validate(res => {
      //   if (!res) {
      //     return;
      //   }
      // });
      // 判断是否在时间内   开始时间是否在时间段内  结束时间是否在时间段内
      if (!this.startTime || !this.endTime) {
        this.$message.error("请填写开始时间或结束时间");
        return;
      }
      // 开始时间必须不在所有时段内
      let isStartTime = this.activeItem.timeList.some(item => {
        return this.timeIsrange(item.startTime, item.endTime, this.startTime);
      });
      // 结束时间必须不在所有时段内
      let isEndTime = this.activeItem.timeList.some(item => {
        return this.timeIsrange(item.startTime, item.endTime, this.endTime);
      });
      // 所有时段的开始时间必须不在新增时段内
      let hasStartTime = this.activeItem.timeList.some(item => {
        return this.timeIsrange(this.startTime, this.endTime, item.startTime);
      });
      // 所有时段的结束时间必须不在新增时段内
      let hasEndtTime = this.activeItem.timeList.some(item => {
        return this.timeIsrange(this.startTime, this.endTime, item.endTime);
      });
      // 开始时间
      if (isStartTime || isEndTime || hasStartTime || hasEndtTime) {
        this.$message.error("时间冲突");
        return;
      }
      this.activeItem.timeList.push({
        startTime: this.startTime + ":00",
        endTime: this.endTime + ":00"
      });
      // 排序
      this.activeItem.timeList.sort((a, b) => {
        let ahour = a.startTime.substring(0, 2);
        let amin = a.startTime.substring(3, 5);
        let bhour = b.startTime.substring(0, 2);
        let bmin = b.startTime.substring(3, 5);
        let dateA = new Date();
        dateA.setHours(ahour);
        dateA.setMinutes(amin);
        let dateB = new Date();
        dateB.setHours(bhour);
        dateB.setMinutes(bmin);
        return dateA.getTime() - dateB.getTime();
      });

      this.closetimeVisible();
    },
    // 判断时间是否在时间段内
    timeIsrange (beginTime, endTime, nowTime) {
      var strb = beginTime.split(":");
      if (strb.length != 2) {
        return false;
      }
      var stre = endTime.split(":");
      if (stre.length != 2) {
        return false;
      }
      var strn = nowTime.split(":");
      if (stre.length != 2) {
        return false;
      }
      var b = new Date();
      var e = new Date();
      var n = new Date();
      b.setHours(strb[0]);
      b.setMinutes(strb[1]);
      e.setHours(stre[0]);
      e.setMinutes(stre[1]);
      n.setHours(strn[0]);
      n.setMinutes(strn[1]);

      if (n.getTime() - b.getTime() >= 0 && n.getTime() - e.getTime() <= 0) {
        // 在时间范围内
        return true;
      } else {
        // 不在时间范围内
        return false;
      }
    },
    resetTime () {
      this.weekList = {
        monday: {
          timeList: [],
          name: "周一",
          isHoliday: false
        },
        tuesday: {
          timeList: [],
          name: "周二",
          isHoliday: false
        },
        wednesday: {
          timeList: [],
          name: "周三",
          isHoliday: false
        },
        thursday: {
          timeList: [],
          name: "周四",
          isHoliday: false
        },
        friday: {
          timeList: [],
          name: "周五",
          isHoliday: false
        },
        saturday: {
          timeList: [],
          name: "周六",
          isHoliday: false
        },
        sunday: {
          timeList: [],
          name: "周日",
          isHoliday: false
        }
      };
      this.accompanyForm.week = null;
    },
    changeStartTime () {
      this.endTime = "";
    },
    closetimeVisible () {
      this.startTime = null;
      this.endTime = null;
      console.log(111);
      this.timeVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.micon {
  position: absolute;
  top: 12px;
  left: -26px;
  z-index: 100;
}
.music-title {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  color: #444;
  .el-col {
    background-color: #edeef0;
    padding-left: 36px;
  }
  /deep/.el-button {
    float: right;
    margin-top: 10px;
    margin-right: 16px;
  }
}

/deep/.el-row {
  margin-bottom: 12px;
  font-size: 14px;
  .el-col:nth-child(1) {
    padding-left: 36px;
  }
  .el-col {
    line-height: 48px;
  }
  .el-col-18 {
    width: calc(90% - 20px);
    margin-left: 20px;
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  // margin-left: 10px;
  vertical-align: bottom;
}
.el-tag--dark.el-tag--info {
  background-color: #f0f2f5;
  border-color: #f0f2f5;
  color: #5a5e66;
  /deep/.el-tag__close {
    background-color: #c0c4cc;
  }
}
// #14928a
.el-tag--dark {
  background-color: #14928a;
  border-color: #14928a;
}
</style>