<template>
  <div class="periodadjust">
    <div :class="[dataShow ? 'container' : '']">
      <!-- <m-header /> -->
      <m-calendar
        @onSelectDay="onSelectDay"
        :dayList="getMonthDay"
        @onChangeMonth="onChangeMonth"
      />
      <van-radio-group
        v-if="dataShow"
        key="data"
        v-model="radioSelect"
        class="cellList"
      >
        <van-cell-group v-for="(item, index) in dataList" :key="index">
          <van-cell @click="onCheckRadio(item)" class="titleCell">
            <template slot="default">
              <div class="signImgBox">
                <img
                  class="signImg"
                  :src="getSignInIcon(item.isSignIn)"
                  alt=""
                />
              </div>
            </template>
            <template slot="title">
              <div class="classTitleWrap" style="word-break: break-all">
                <img
                  class="teacherModelImg"
                  :src="getTeacherImg(item.teachMode)"
                  alt=""
                />
                <img class="courseImg" :src="squrtList.squrt2" alt="" />
                {{ item.name }}
              </div>

              <!--  -->
            </template>
          </van-cell>
          <van-cell>
            <template slot="title">
              <p
                class="studentTitle"
                style="word-break: break-all"
                v-if="item.schoolName"
              >
                上课地点 : &nbsp;{{ item.schoolName }}
              </p>
              <p class="studentTitle" style="word-break: break-all">
                上课学生 : &nbsp;{{ item.studentNames }}
              </p>
            </template>
          </van-cell>
          <van-cell
            class="input-cell"
            title-class="title-content"
            value-class="value-content"
            :center="true"
            @click="onCheckRadio(item)"
          >
            <template slot="title">
              <div class="chioseWrap">
                <img class="clockIcon" :src="squrtList.squrt8" alt="" />
                <p class="timer">
                  {{ item.startClassTime | formatDate }}-{{
                    item.endClassTime | formatDate
                  }}
                </p>
              </div>
            </template>
            <template slot="default">
              <van-radio
                ref="radioes"
                :disabled="radioDisabled"
                :name="item.id"
              ></van-radio>
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
      <m-empty v-else key="data" />
    </div>
    <van-sticky v-if="dataShow">
      <div class="button-group">
        <van-button
          type="default"
          class="changeBtn"
          @click="onDateChange"
          size="large"
          >课时调整</van-button
        >
        <van-button type="primary" @click="onSubmit" size="large"
          >去换课</van-button
        >
      </div>
    </van-sticky>
    <van-popup v-model="dataForm.status" position="bottom">
      <van-datetime-picker
        v-model="dataForm.currentDate"
        type="datetime"
        :min-date="dataForm.minDate"
        :max-date="dataForm.maxDate"
        :formatter="formatter"
        @cancel="dataForm.status = false"
        @confirm="onCurrentConfirm"
      />
    </van-popup>
  </div>
</template>
<script>
/* eslint-disable */
// import MHeader from '@/components/MHeader' courseSwap
import MCalendar from "@/components/MCalendar";
import MEmpty from "@/components/MEmpty";
import dayjs from "dayjs";
import { browser } from "@/common/common";
import {
  getCourseSchedulesWithDate,
  getCourseScheduleDateByMonth,
  classStartDateAdjust,
} from "@/api/teacher";
import setLoading from "@/utils/loading";
export default {
  name: "periodadjust",
  components: { MCalendar, MEmpty },
  data() {
    return {
      dataForm: {
        // 时间下拉框
        status: false,
        minDate: new Date(2018, 0, 1),
        maxDate: new Date(2035, 10, 1),
        currentDate: new Date(),
      },
      radioSelect: null,
      radioSelectList: [], // 选中的列表
      dataList: [],
      dataShow: true, // 是否有数据
      radioDisabled: true, // 今天或今天之前的数据禁用
      getMonthDay: [], // 当月有月份列表
      squrtList: {
        squrt2: require("@/assets/images/squrt2.png"),
        squrt3: require("@/assets/images/squrt3.png"),
        squrt4: require("@/assets/images/squrt4.png"),
        squrt5: require("@/assets/images/squrt5.png"),
        squrt6: require("@/assets/images/squrt6.png"),
        squrt7: require("@/assets/images/squrt7.png"),
        squrt8: require("@/assets/images/squrt8.png"),
      },
    };
  },
  created() {},
  mounted() {
    let params = this.$route.query;
    if (params.Authorization) {
      localStorage.setItem("Authorization", decodeURI(params.Authorization));
      localStorage.setItem("userInfo", decodeURI(params.Authorization));
    }
    document.title = "课程调整";
    let toDay = this.getFormartDate(new Date());
    this.getCourseDate(toDay);
    this.getCourseMonth(toDay);
  },
  methods: {
    onSelectDay(value) {
      if (
        new Date(this.getFormartDateIOS(new Date())) >=
        new Date(this.getFormartDateIOS(value))
      ) {
        this.radioDisabled = true;
      } else {
        this.radioDisabled = false;
      }
      this.getCourseDate(this.getFormartDate(value));
    },
    onChangeMonth(value) {
      this.getCourseMonth(dayjs(value).format("YYYY-MM-DD"));
    },
    onCheckRadio(item) {
      console.log("点击", this.radioDisabled);
      // 单选按钮选中
      if (this.radioDisabled) return;
      this.radioSelect = item.id;
      this.radioSelectList = item;
    },
    async getCourseMonth(month) {
      await getCourseScheduleDateByMonth({ month: month, type: "VIP" }).then(
        (res) => {
          let result = res.data;
          if (result.code == 200) {
            this.getMonthDay = [];
            result.data.forEach((item) => {
              this.getMonthDay.push(dayjs(item).format("DD"));
            });
            this.isCalendar = true;
          }
        }
      );
    },
    async getCourseDate(date) {
      setLoading(true);
      try {
        this.dataList = [];
        await getCourseSchedulesWithDate({ date: date, type: "VIP" }).then(
          (res) => {
            let result = res.data;
            if (result.code == 200 && result.data) {
              this.dataList = result.data.rows.map((item) => {
                let studentNames = [];
                if (item.students) {
                  studentNames = item.students.map((stu) => {
                    return stu.userName;
                  });
                }
                return { ...item, studentNames: studentNames.join(",") };
              });
              this.dataShow = result.data.rows.length > 0 ? true : false;
            }
            setLoading(false);
          }
        );
      } catch (err) {
        setLoading(false);
      }
    },
    onSubmit() {
      if (!this.radioSelect) {
        this.$toast("请选择需要交换的课程");
        return;
      }
      let dataInfo = this.radioSelectList;
      let classDate = dataInfo.classDate.split(" ")[0];
      let startTime = dataInfo.startClassTime.split(" ")[1];

      // 确认选择
      this.$router.push({
        path: "/PeriodChange",
        query: {
          checkId: this.radioSelect,
          classDate: classDate,
          startTime: startTime,
          name: dataInfo.name,
        },
      });
    },
    getFormartDateIOS(date) {
      let checkDate = new Date(date);
      let checkDay =
        checkDate.getFullYear() +
        "/" +
        (checkDate.getMonth() + 1) +
        "/" +
        checkDate.getDate();
      return checkDay;
    },
    getFormartDate(date) {
      let checkDate = new Date(date);
      let checkDay =
        checkDate.getFullYear() +
        "-" +
        (checkDate.getMonth() + 1) +
        "-" +
        checkDate.getDate();
      return checkDay;
    },
    onDateChange() {
      if (!this.radioSelect) {
        this.$toast("请选择需要调整的课程");
        return;
      }
      this.dataForm.status = true;
    },
    onCurrentConfirm(value) {
      // 课时调整
      let selectDate = [];
      this.dataList.forEach((item) => {
        if (item.id == this.radioSelect) {
          selectDate = item;
        }
      });

      let startStr =
          "2019/12/18 " + this.getDateInfo(selectDate.startClassTime),
        endStr = "2019/12/18 " + this.getDateInfo(selectDate.endClassTime);
      let startDate = new Date(startStr),
        endDate = new Date(endStr);
      let m = parseInt(
        Math.abs(endDate.getTime() - startDate.getTime()) / 1000 / 60
      );
      let currentStartDate = new Date(value),
        currentEndDate = new Date(value);

      currentEndDate.setMinutes(currentStartDate.getMinutes() + m);
      if (currentStartDate.toDateString() !== currentEndDate.toDateString()) {
        this.$toast("课时调整不允许跨天调整");
        return;
      }

      console.log(
        this.getDateInfo(currentStartDate),
        this.getDateInfo(currentEndDate)
      );
      let currentStartDateStr =  this.getDateInfo(currentStartDate)
      let currentEndDateStr =  this.getDateInfo(currentEndDate)

      const endTime1 = currentEndDateStr ? Number(currentEndDateStr.split(":")[0]) : 0;
      const endTime2 = currentEndDateStr ? Number(currentEndDateStr.split(":")[1]) : 0;
      if (endTime1 >= 21 && endTime2 > 0) {
        this.$toast("课程安排结束时间不可超过21:00");
        return;
      }
      const starTime1 = currentStartDateStr ? Number(currentStartDateStr.split(":")[0]) : 0;
      const starTime2 = currentStartDateStr ? Number(currentStartDateStr.split(":")[1]) : 0;
      if (starTime1 <6 ) {
        this.$toast("课程安排开始时间不可早于06:00");
        return;
      }
      



      classStartDateAdjust({
        actualTeacherId: selectDate.actualTeacherId,
        id: this.radioSelect,
        classDate: this.getFormartDate(currentStartDate),
        startClassTimeStr: this.getDateInfo(currentStartDate),
        endClassTimeStr: this.getDateInfo(currentEndDate),
      }).then((res) => {
        let result = res.data;
        if (result.code == 200) {
          this.$toast("调整成功");
          setTimeout(() => {
            if (browser().iPhone) {
              window.webkit.messageHandlers.DAYA.postMessage(
                JSON.stringify({ api: "back" })
              );
            } else if (browser().android) {
              DAYA.postMessage(JSON.stringify({ api: "back" }));
            } else {
              this.$router.push("/business");
            }
          }, 500);
        } else {
          this.$toast(result.msg);
        }
      });
    },
    getDateInfo(value) {
      let tempValue = value;
      if (typeof value !== "object") {
        tempValue = value.replace(/-/gi, "/");
      }
      let d = new Date(tempValue);
      let hour = d.getHours() >= 10 ? d.getHours() : "0" + d.getHours();
      let minute = d.getMinutes() >= 10 ? d.getMinutes() : "0" + d.getMinutes();
      return hour + ":" + minute + ":00";
    },
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      }
      return value;
    },
    getSignInIcon(status) {
      if (status == 1) {
        return this.squrtList.squrt3;
      } else if (status == 0) {
        return this.squrtList.squrt5;
      } else {
        return this.squrtList.squrt4;
      }
    },
    getTeacherImg(mode) {
      if (mode == "ONLINE") {
        return this.squrtList.squrt6;
      } else {
        return this.squrtList.squrt7;
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../assets/commonLess/variable.less");
.periodadjust {
  min-height: 100vh;
  //   height: 100vh;
  position: relative;
  background-color: #f3f4f8;
  .container {
    min-height: calc(100vh - 0.5rem);
    overflow-y: auto;
    overflow-x: hidden;
    position: relative;
  }
  .button-group {
    width: 100%;
    // position: absolute;
    // bottom: 0;
    // left: 0;
    // z-index: 99;
    .van-button {
      font-size: 0.16rem;
      width: 50%;
      height: 0.5rem;
      line-height: 0.48rem;
    }
    .van-button--primary {
      background: @mColor;
      border-color: @mColor;
    }
  }
  .van-cell__title {
    width: 2.58rem;
    -webkit-box-flex: auto;
    -webkit-flex: auto;
    flex: auto;
    font-size: 0.18rem;
    color: #333;
    font-weight: 500;
  }
}
/deep/.van-icon-underway-o {
  font-size: 0.18rem;
}
/deep/.van-cell {
  line-height: inherit;
}
/deep/.van-cell__title {
  font-size: 0.16rem;
  color: @mFontColor;
}
/deep/.van-cell-group {
  margin-top: 0.05rem;
  border-radius: 0.1rem;
  margin: 0.1rem 0.12rem 0;
  overflow: hidden;
}
.title-content {
  flex: 1 auto;
  font-weight: bold;
  .van-cell__label {
    font-weight: 400;
    margin-top: 0.06rem;
    display: flex;
    align-items: center;
  }
  .van-icon-location {
    margin-right: 0.05rem;
  }
}
.value-content {
  width: 50px;
}
/deep/.van-cell__value,
/deep/.van-cell__label {
  color: #444;
  font-size: 0.14rem;
  flex: 1 auto;
  span {
    padding-right: 0.1rem;
  }
}

.input-cell {
  padding: 0.12rem 0.16rem 0.2rem;
  .van-radio {
    justify-content: flex-end;
  }
}
/deep/.van-radio__icon--disabled .van-icon {
  border-color: #fff;
  background: #fff;
}
/deep/.van-radio__icon .van-icon {
  border-color: transparent;
  border: 1px solid #d3d3d3;
}
/deep/.van-radio__icon--checked .van-icon {
  background: @mColor;
  border-color: @mColor;
}
/deep/.icon {
  margin-top: 0.3rem;
}
.signImgBox {
  .signImg {
    margin-top: 0.04rem;
    width: 0.48rem;
    height: 0.22rem;
  }
}
.teacherModelImg {
  width: 0.35rem;
  height: 0.2rem;
  margin-right: 0.05rem;
  position: absolute;
  left: 0;
  top: 0.04rem;
}
.courseImg {
  width: 0.42rem;
  height: 0.18rem;
  position: absolute;
  left: 0.4rem;
  top: 0.05rem;
}
.classTitleWrap {
  position: relative;
  text-indent: 0.88rem;
  line-height: 0.28rem;
  // align-items: center;
}
.titleCell {
  padding-bottom: 0 !important;
  &:after {
    border-bottom: none;
  }
}
.studentTitle {
  font-size: 0.13rem;
  color: #666;
  line-height: 0.19rem;
  margin-bottom: 5px;
}
.clockIcon {
  width: 0.16rem;
  height: 0.16rem;
}
.chioseWrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  img {
    position: relative;
    top: -0.02rem;
    margin-right: 0.08rem;
  }
}
.cellList {
  margin-bottom: 20px;
}
.changeBtn {
  background-color: #fff;
  color: @mColor;
  border: 1px solid #fff;
}
</style>
