<template>
  <div class="leave">
    <m-header v-if="headerStatus" />

    <van-cell-group class="search">
      <van-field label="开始时间" placeholder="选择开始时间" input-align="right" v-model="searchList.startText" readonly is-link @click="startShow = true" />
      <van-field label="结束时间" input-align="right" placeholder="选择结束时间" v-model="searchList.endText" readonly is-link @click="endShow = true" />
      <!-- <van-field label="请假类型" is-link input-align="right" placeholder="选择请假类型"
                      v-model="searchList.dealText" readonly clickable
                      @click="dealShow = true" /> -->

      <van-field type="textarea" v-model="searchList.remark" placeholder="请详细说明原因" rows="4" autosize />
    </van-cell-group>

    <van-panel title="课时安排" v-if="vipList.length > 0 && vipListType">
      <template v-for="(item, index) in vipList">
        <div class="leaveCell" v-if="item.type == 'VIP'" :key="index">
          <div class="leaveCell-l">{{ item.name }}</div>
          <div class="leaveCell-r">
            <div class="left-wrap">
              <p class="classTime">上课时间</p>
              <p>{{ item.classDate | getFormatTime(item.startClassTime) }}</p>
              <div class="line"></div>
              <img src="@/assets/images/switch-icon.png" alt="" class="icon" />
            </div>
            <div class="left-wrap" v-if="item.changeTime">
              <p class="classTime">已调整为</p>
              <p>
                {{ item.changeTime }}
                <van-icon @click="onUpdate(item)" name="edit" />
              </p>
            </div>
            <div class="left-wrap" v-else>
              <van-button @click="onAdd(item)" round type="info" size="small">调整</van-button>
            </div>
          </div>
        </div>
      </template>
    </van-panel>

    <div class="button-group">
      <van-button type="primary" @click="onSubmit" round size="large">确认</van-button>
    </div>
    <!-- 开始时间弹窗 -->
    <van-popup v-model="startShow" position="bottom">
      <van-datetime-picker v-model="startDate.currentDate" type="datetime" :item-height="40" title="开始时间" :min-date="startDate.minDate" :max-date="startDate.maxDate" @cancel="startShow = false" @confirm="onStartConfirm" :formatter="formatter" />
    </van-popup>
    <!-- 结束时间弹窗 -->
    <van-popup v-model="endShow" position="bottom">
      <van-datetime-picker v-model="endDate.currentDate" type="datetime" :item-height="40" title="结束时间" :min-date="endDate.minDate" :max-date="endDate.maxDate" @cancel="endShow = false" @confirm="onEndConfirm" :formatter="formatter" />
    </van-popup>
    <van-action-sheet v-model="dealShow" :actions="leaveCategoryList" cancel-text="取消" @cancel="dealShow = false" @select="onDealSelect" />

    <!-- 调整时间 -->
    <van-popup v-model="changeShow" position="bottom">
      <van-datetime-picker v-model="changeDate.currentDate" type="datetime" :item-height="40" title="结束时间" :min-date="changeDate.minDate" :max-date="changeDate.maxDate" @cancel="changeShow = false" @confirm="onChangeConfirm" :formatter="formatter" />
    </van-popup>
  </div>
</template>
<script>
/* eslint-disable */
import MHeader from "@/components/MHeader";
import { queryVipCourseScheduleList, leaveCategoryPage, askForLeave } from "@/api/teacher";
import { browser } from "@/common/common";
// let nowTime = new Date()
// let changeTime = new Date(nowTime.setDate(nowTime.getDate() + 1))
export default {
  name: "leave",
  components: { MHeader },
  data() {
    return {
      headerStatus: false,
      startShow: false,
      startDate: {
        // 开始时间
        minDate: new Date(),
        maxDate: new Date(2025, 12, 31),
        currentDate: new Date(),
      },
      endShow: false,
      endDate: {
        // 结束时间
        minDate: new Date(),
        maxDate: new Date(2025, 12, 31),
        currentDate: new Date(),
      },
      dealShow: false,
      searchList: {
        startText: null,
        endText: null,
        dealText: null,
        remark: null,
      },
      vipList: [], // 申请调整的vip列表
      vipListType: false, // 判断是否只有乐团课
      changeShow: false,
      changeDate: {
        // 结束时间
        minDate: new Date(),
        maxDate: new Date(2025, 12, 31),
        currentDate: new Date(),
      },
      leaveCategoryList: [],
      changeItem: null,
    };
  },
  mounted() {
    let params = this.$route.query;
    if (params.Authorization) {
      localStorage.setItem("Authorization", params.Authorization);
      localStorage.setItem("userInfo", params.Authorization);
    }
    document.title = "课程请假";
    // if(browser().android) {
    //     this.headerStatus = true
    // }
    this.__init();
  },
  methods: {
    __init() {
      leaveCategoryPage({
        rows: 9999,
        page: 1,
      }).then((res) => {
        let result = res.data;
        if (result.code == 200) {
          result.data.rows.forEach((item) => {
            this.leaveCategoryList.push({
              name: item.name,
              id: item.id,
            });
          });
        }
      });
    },
    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";
    },
    onSubmit() {
      let searchList = this.searchList;
      if (!searchList.startText || !searchList.endText) {
        this.$toast("时间不能为空");
        return;
      }

      // if(!searchList.dealText) {
      //     this.$toast('请选择请假类型')
      //     return
      // }

      if (!searchList.remark) {
        this.$toast("请填写原因");
        return;
      }
      let leaveCategoryId;
      this.leaveCategoryList.forEach((item) => {
        if (item.name == searchList.dealText) {
          leaveCategoryId = item.id;
        }
      });

      let coursesScheduleJson = [];
      let status = false;
      this.vipList.forEach((item) => {
        if (!item.changeAllTime && item.type == "VIP") {
          this.$toast("操作无效:您还有VIP未调整");
          status = true;
        }
        let tempI = {};
        if (item.type == "VIP") {
          tempI = Object.assign({}, item);
          let startStr = "2019/12/18 " + this.getDateInfo(item.startClassTime),
            endStr = "2019/12/18 " + this.getDateInfo(item.endClassTime);
          let startDate = new Date(startStr),
            endDate = new Date(endStr);
          let m = parseInt(Math.abs(startDate.getTime() - endDate.getTime()) / 1000 / 60);
          tempI.classDate = this.getFormatDate(item.changeAllTime) + ":00";
          tempI.startClassTime = this.getFormatDate(item.changeAllTime) + ":00";
          let currentDate = new Date(item.changeAllTime);
          currentDate.setMinutes(currentDate.getMinutes() + m);
          tempI.endClassTime = this.getFormatDate(currentDate) + ":00";
        }
        coursesScheduleJson.push({
          before: item,
          after: tempI,
        });
      });
      if (status) return;

      askForLeave({
        coursesScheduleJson: JSON.stringify(coursesScheduleJson),
        startTime: searchList.startText,
        endTime: searchList.endText,
        leaveCategoryId: leaveCategoryId,
        leaveCategoryName: searchList.dealText,
        remark: searchList.remark,
      }).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);
        }
      });
    },
    onAdd(item) {
      // 调整
      this.changeShow = true;
      this.changeItem = item;
    },
    onUpdate(item) {
      this.changeDate.currentDate = item.changeAllTime;
      this.changeShow = true;
      this.changeItem = item;
    },
    onChangeConfirm(val) {
      let tempDate = new Date(val);
      let month = tempDate.getMonth() + 1 >= 10 ? tempDate.getMonth() + 1 : "0" + (tempDate.getMonth() + 1);
      let day = tempDate.getDate() >= 10 ? tempDate.getDate() : "0" + tempDate.getDate();
      let hours = tempDate.getHours() >= 10 ? tempDate.getHours() : "0" + tempDate.getHours();
      let min = tempDate.getMinutes() >= 10 ? tempDate.getMinutes() : "0" + tempDate.getMinutes();
      this.changeItem.changeTime = month + "-" + day + " " + hours + ":" + min;
      this.changeItem.changeAllTime = val;
      this.changeShow = false;
    },
    onStartConfirm(val) {
      // 开始时间
      let searchList = this.searchList;
      searchList.startText = this.getFormatDate(val);
      this.startShow = false;
      if (val >= this.endDate.currentDate) {
        searchList.endText = null;
        this.endDate.currentDate = new Date();
      } else {
        if (searchList.startText && searchList.endText) {
          this.queryVipCourseScheduleList();
        }
      }
    },
    onEndConfirm(val) {
      // 结束时间
      let searchList = this.searchList;
      searchList.endText = this.getFormatDate(val);
      this.endShow = false;
      if (val <= this.startDate.currentDate) {
        searchList.startText = null;
        this.startDate.currentDate = new Date();
      } else {
        if (searchList.startText && searchList.endText) {
          this.queryVipCourseScheduleList();
        }
      }
    },
    queryVipCourseScheduleList() {
      // 获取需要调整的VIP课
      queryVipCourseScheduleList({
        endTime: this.searchList.endText,
        startTime: this.searchList.startText,
      }).then((res) => {
        let result = res.data;
        this.vipList = [];
        if (result.code == 200 && result.data.length > 0) {
          this.vipList = result.data;
          result.data.forEach((item) => {
            if (item.type == "VIP") {
              this.vipListType = true;
            }
          });
        }
      });
    },
    onDealSelect(val) {
      // 交易收支
      this.searchList.dealText = val.name;
      this.dealShow = false;
    },
    getFormatDate(data) {
      let tempDate = new Date(data);
      let month = tempDate.getMonth() + 1 >= 10 ? tempDate.getMonth() + 1 : "0" + (tempDate.getMonth() + 1);
      let day = tempDate.getDate() >= 10 ? tempDate.getDate() : "0" + tempDate.getDate();
      let tDate = tempDate.getFullYear() + "-" + month + "-" + day;
      let hours = tempDate.getHours() >= 10 ? tempDate.getHours() : "0" + tempDate.getHours();
      let min = tempDate.getMinutes() >= 10 ? tempDate.getMinutes() : "0" + tempDate.getMinutes();
      return tDate + " " + hours + ":" + min;
    },
    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;
    },
  },
  filters: {
    getFormatTime(tempA, tempB) {
      (tempA = new Date(tempA.replace(/-/g, "/"))), (tempB = new Date(tempB.replace(/-/g, "/")));
      let month = Number(tempA.getMonth() + 1) >= 10 ? Number(tempA.getMonth() + 1) : "0" + Number(tempA.getMonth() + 1);
      let day = Number(tempA.getDate()) >= 10 ? tempA.getDate() : "0" + tempA.getDate();
      let hours = Number(tempB.getHours()) >= 10 ? tempB.getHours() : "0" + tempB.getHours();
      let min = Number(tempB.getMinutes()) >= 10 ? tempB.getMinutes() : "0" + tempB.getMinutes();
      return month + "-" + day + " " + hours + ":" + min;
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../assets/commonLess/variable.less");
.leave {
  min-height: 100vh;
  overflow: hidden;
}
.search .van-cell {
  padding: 0.13rem 0.16rem;
  font-size: 0.14rem;
  line-height: 0.24rem;
  display: flex;
  align-items: center;
}

.result {
  margin-top: 0.1rem;
  .count {
    font-size: 0.12rem;
    color: @tFontColor;
  }
  .add {
    color: @orangeColor;
  }
}
/deep/.van-panel {
  margin-top: 0.1rem;
  .van-cell__title {
    font-size: 0.16rem;
    color: @mFontColor;
  }
}
.leaveCell {
  position: relative;
  display: flex;
  flex-direction: row;
  // justify-content: space-between;
  align-items: center;
  padding: 0.15rem;
  border-bottom: 1px solid #f3f4f8;
  font-size: 0.14rem;
  &:last-child {
    border-bottom: 0;
  }
  .leaveCell-l {
    word-break: break-all;
    flex-basis: 0.8rem;
    padding-right: 0.08rem;
  }
  .leaveCell-r {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    .left-wrap {
      .van-button--info {
        width: 0.72rem;
        height: 0.28rem;
        font-size: 0.14rem;
      }
      .classTime {
        margin-bottom: 0.06rem;
      }
      min-width: 1rem;
      position: relative;
      &:first-child {
        padding-right: 0.15rem;
      }
      &:last-child {
        padding-left: 0.15rem;
      }
      .line {
        position: absolute;
        width: 1px;
        height: 0.56rem;
        background-color: #f3f3f8;
        right: 0;
        top: -0.07rem;
      }
      .icon {
        position: absolute;
        width: 0.15rem;
        height: 0.15rem;
        right: -0.07rem;
        top: 0.15rem;
      }
    }
  }
}
/deep/.van-field__label {
  width: 0.9rem;
}
/deep/.van-icon-edit {
  color: @mColor;
  font-size: 0.16rem;
  vertical-align: text-bottom;
  margin-left: 0.08rem;
}
/deep/.van-button--info {
  background-color: @mColor;
  border: 1px solid @mColor;
}
.button-group {
  margin: 0.3rem 0.26rem 0.2rem;
  .van-button--primary {
    background: @mColor;
    font-size: 0.18rem;
    height: 0.5rem;
    line-height: 0.48rem;
  }
}
</style>
