<template>
  <div class="page-body">
    <div class="col row wrap q-mr-lg q-col-gutter-md searchBox">
      <div class="col-2">
        <q-select filled dense v-model="msg.TeacherId" option-value="TId" option-label="TeacherName"
          :options="TeacherList" emit-value map-options label="老师" @input="getData" />
      </div>
      <div class="col-2">
        <q-select filled dense v-model="msg.ClassRoomId" option-value="RoomId" option-label="RoomName"
          :options="classroomList" emit-value map-options label="教室" @input="getData" />
      </div>
      <div class="col-2">
        <q-select filled dense v-model="msg.ClassType" option-value="Id" option-label="label" :options="ClassTypeList"
          emit-value map-options label="课程类型" @input="getData" />
      </div>
      <div class="col-2">
        <q-select filled dense v-model="msg.AppointState" option-value="Id" option-label="label"
          :options="AppointStateList" emit-value map-options label="约课状态" @input="getData" />
      </div>
      <div class="col-2">
        <q-field filled dense label="选择日期" stack-label>
          <template v-slot:control>
            <el-date-picker v-model="selectedDate" type="date" size="mini" placeholder="开始日期" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd" :clearable="false" @change="changeDate">
            </el-date-picker>
          </template>
        </q-field>
      </div>
      <div class="col-2">
        <q-select filled dense v-model="viewType" option-value="value" option-label="name" :options="viewTypeList"
          emit-value map-options label="显示模式" @input="changeDate" />
      </div>
    </div>
    <div class="row justify-center items-center q-mt-sm">
      <q-btn dense text-color="primary" flat unelevated :label="viewType == 'day' ? '上一天' : '上一周'"
        @click="calendarPrev" />
      <q-separator vertical />
      <q-btn dense text-color="primary" flat unelevated :label="viewType == 'day' ? '下一天' : '下一周'"
        @click="calendarNext" />
    </div>
    <div class="viewbox">
      <q-calendar v-model="selectedDate" :view="viewType" ref="calendar" locale="zh-CN" class="calendar-container "
        bordered no-scroll hour24-format :interval-start="8" :interval-count="15" :interval-height="60" animated
        transition-prev="slide-right" transition-next="slide-left" :weekdays="[1, 2, 3, 4, 5, 6, 0]"
        @input="onModelChanged" @click:date2="onClickDate2" @click:day:header2="onClickDayHeader2"
        @click:interval2="onClickInterval2" @click:time2="onClickTime2"
        @click:interval:header2="onClickIntervalHeader2">
        <template #day-header="{ timestamp }">
          <div v-if="viewType == 'week'">
            <q-badge :color="item.bg" :label="item.TeacherName" v-for="(item, index) in legendList" :key="index"
              class="q-mr-xs" />
          </div>
          <div class="flex no-wrap" v-if="viewType == 'day'">
            <q-badge :color="item.bg" :label="item.TeacherName" v-for="(item, index) in legendList" :key="index"
              style="height:20px" :style="{ width: `${(1 / legendList.length) * 100}%` }" />
          </div>
        </template>

        <template #day-body="{ timestamp, timeStartPos, timeDurationHeight }">
          <div v-for="(item, index) in events" :key="index">
            <div v-if="item.ClassDate == timestamp.date">
              <div v-for="(_item, _index) in item.RList" :key="_index">
                <div v-for="(__item, __index) in _item.SubList" :key="__index"
                  class="my-event justify-center ellipsis courseItem"
                  :class="badgeClasses(__item, 'body', _item.TeacherId)"
                  style="overflow:hidden;box-shadow: 0px 10px 10px 0 rgba(36, 36, 36, 0.2);" :style="
                    badgeStyles(
                      __item,
                      'body',
                      timeStartPos,
                      timeDurationHeight,
                      _index,
                      item.RList.length
                    )
                  " @click.stop="
                    showDetail(__item, item.ClassDate, _item.TeacherId)
                  ">
                  <el-popover placement="top-start" width="200" trigger="hover">
                    <div slot="reference" style="height:80vh;position:relative">
                      <q-badge rounded color="red" label="未成班" style="position:absolute;top:0;right:0" v-if="
                          viewType == 'day' &&
                            isShowTag(__item.GuestList, __item.ScrollMinNum)
                        " />
                      <q-icon name="lock_open" color="dark" style="position:absolute;top:0;right:0" v-if="
                          viewType == 'week' &&
                            isShowTag(__item.GuestList, __item.ScrollMinNum)
                        " />
                      <div v-if="viewType == 'day' || item.RList.length == 1" class="q-pa-xs">
                        <div class="flex">
                          <span class="detailLabel">教室：</span>{{ __item.RoomName }}
                        </div>
                        <div class="flex no-wrap" v-if="__item.ClassType == 1">
                          <span class="detailLabel">进度：</span><span>{{ __item.Ranks }}/{{ __item.TotalPlanNum }}</span>
                        </div>
                        <div class="flex no-wrap" v-if="__item.ClassType == 3">
                          <span class="detailLabel">进度：</span><span>第{{ __item.Ranks||0 }}次课</span>
                          <span class="q-ml-sm" v-if="__item.CourseGradeName">({{__item.CourseGradeName}})</span>
                        </div>
                        <div class="row flex no-wrap">
                          <span class="detailLabel">课程：</span>
                          <div class="detailValue">{{ __item.CourseName }}</div>
                        </div>
                        <div class="flex no-wrap">
                          <span class="detailLabel">班级：</span>
                          <span>{{ __item.ClassName }}
                            <span v-if="__item.ClassType === 2">
                              <span v-if="__item.ReserveType === 0">(正常试听)</span>
                              <span v-if="__item.ReserveType === 1">(跟班试听)</span>
                            </span>
                          </span>
                        </div>
                        <div class="flex no-wrap">
                          <span class="detailLabel">时间：</span><span>{{ __item.StartTime }}-{{ __item.EndTime }}</span>
                        </div>
                        <div class="flex no-wrap">
                          <span class="detailLabel">
                            类型：<span></span><span v-if="__item.ClassType == 1">跟班</span><span
                              v-if="__item.ClassType == 2">试听课</span><span v-if="__item.ClassType == 3">约课</span></span>
                        </div>
                        <div class="flex no-wrap" v-if="__item.ClassType !== 2">
                          <span class="detailLabel">学员：</span>
                          <div>
                            <span v-for="(x, y) in __item.GuestList" :key="y"
                              style="white-space:nowrap;display:inline-block" class="q-mr-xs">
                              {{ x.GuestName }}
                              <span v-if="x.AppointType == 2">(补)</span>
                              <span v-if="x.AppointType == 3">(重)</span>
                            </span>
                          </div>
                        </div>
                        <div class="flex no-wrap" v-if="__item.ClassType == 3">
                          <span class="detailLabel">状态：</span>
                          <div>
                            <span v-if="__item.AppointState == 1" style="color:#ef5350">待确认</span>
                            <span v-if="__item.AppointState == 2" style="color:#21ba45">已确认</span>
                            <q-btn color="accent" size="xs" label="确认" v-if="
                                __item.AppointState == 1 &&
                                  __item.GuestList.length >=
                                    __item.ScrollMinNum &&
                                  auth.IsEdit
                              " @click="
                                confirmSub(
                                  item.ClassDate,
                                  _item.TeacherId,
                                  __item
                                )
                              " />
                          </div>
                        </div>
                        <div class="flex no-wrap" v-if="__item.ClassType == 3">
                          <span class="">最小成班人数：</span><span>{{ __item.ScrollMinNum }}</span>
                        </div>
                        <!-- <div class="flex no-wrap" v-if="__item.ClassType == 3">
                        <span class="">最大成班人数：</span
                        ><span>{{ __item.ScrollMaxNum }}</span>
                      </div> -->
                      </div>
                      <div v-if="viewType == 'week'&&__item.ClassType === 3"
                        style="white-space:pre-wrap;font-size:10px">
                        {{__item.CourseGradeName}}<span>({{__item.Ranks||0}})</span> </div>
                    </div>
                    <div style="position:relative">
                      <q-badge rounded color="red" label="未成班" style="position:absolute;top:0;right:0"
                        v-if="isShowTag(__item.GuestList, __item.ScrollMinNum)" />
                      <div class="flex">
                        <span class="detailLabel">老师：</span><span>{{ _item.TeacherName }}</span>
                      </div>
                      <div class="flex">
                        <span class="detailLabel">教室：</span>{{ __item.RoomName }}
                      </div>
                      <div class="flex no-wrap">
                        <span class="detailLabel">课程：</span><span>{{ __item.CourseName }}</span>
                      </div>
                      <div class="flex no-wrap">
                        <span class="detailLabel">班级：</span>
                        <span>{{ __item.ClassName }}
                          <span v-if="__item.ClassType === 2">
                            <span v-if="__item.ReserveType === 0">(正常试听)</span>
                            <span v-if="__item.ReserveType === 1">(跟班试听)</span>
                          </span>
                        </span>
                      </div>
                      <div class="flex no-wrap">
                        <span class="detailLabel">时间：</span><span>{{ __item.StartTime }}-{{ __item.EndTime }}</span>
                      </div>
                      <div class="flex no-wrap" v-if="__item.ClassType == 1">
                        <span class="detailLabel">进度：</span><span>{{ __item.Ranks }}/{{ __item.TotalPlanNum }}</span>
                      </div>
                      <div class="flex no-wrap" v-if="__item.ClassType == 3">
                        <span class="detailLabel">进度：</span><span>第{{ __item.Ranks||0 }}次课</span>
                        <span class="q-ml-sm" v-if="__item.CourseGradeName">({{__item.CourseGradeName}})</span>
                      </div>
                      <div class="flex no-wrap">
                        <span class="detailLabel"> 类型：</span><span v-if="__item.ClassType == 1">跟班</span><span
                          v-if="__item.ClassType == 2">试听课</span><span v-if="__item.ClassType == 3">约课</span>
                      </div>

                      <div class="flex no-wrap" v-if="__item.ClassType !== 2">
                        <span class="detailLabel">学员：</span>
                        <div>
                          <div v-for="(x, y) in __item.GuestList" :key="y"
                            style="white-space:nowrap;display:inline-block" class="q-mr-sm">
                            {{ x.GuestName }}
                            <span v-if="x.AppointType == 2">(补)</span>
                            <span v-if="x.AppointType == 3">(重)</span>
                          </div>
                        </div>
                      </div>
                      <div class="flex no-wrap" v-if="__item.ClassType == 3">
                        <span class="detailLabel">状态：</span>
                        <div>
                          <span v-if="__item.AppointState == 1" style="color:#ef5350">待确认</span>
                          <span v-if="__item.AppointState == 2" style="color:#21ba45">已确认</span>
                          <q-btn color="accent" size="xs" label="确认" v-if="
                              __item.AppointState == 1 &&
                                __item.GuestList.length >=
                                  __item.ScrollMinNum &&
                                auth.IsEdit
                            " @click="
                              confirmSub(
                                item.ClassDate,
                                _item.TeacherId,
                                __item
                              )
                            " />
                        </div>
                      </div>
                      <div class="flex no-wrap" v-if="__item.ClassType == 3">
                        <span class="">最小成班人数：</span><span>{{ __item.ScrollMinNum }}</span>
                      </div>
                      <!-- <div class="flex no-wrap" v-if="__item.ClassType == 3">
                      <span class="">最大成班人数：</span><span>{{ __item.ScrollMaxNum }}</span>
                    </div> -->
                    </div>
                  </el-popover>
                </div>
              </div>
            </div>
          </div>
        </template>
      </q-calendar>
    </div>
    <SubscribeForm v-model="showForm" :editType="editType" :dateObj="dateObj" :saveObj="saveObj" :auth="auth"
      :teacherList="TeacherList2" @success="successHandle" />
  </div>
</template>

<script>
  import {
    GetAppointmentPlanStat,
    SetSureAppointment,
    GetAppointmentConfig
  } from "../../api/studyabroad/subscribe.js";
  import {
    date
  } from "quasar";
  import {
    getTeacherDropDownList,
    queryClassRoomList
  } from "../../api/school/index";
  import SubscribeForm from "../../components/stuMan/subscribe/subscribeForm";
  import QCalendar from "@quasar/quasar-ui-qcalendar";

  export default {
    meta: {
      title: "约课中心",
    },
    data() {
      return {
        config: {
          AdvanceDay: 0,
          AppointDay: 7
        },
        pickerOptions: {
          disabledDate: time => {
            let timeRange = this.config.AppointDay * 24 * 60 * 60 * 1000;
            let _maxTime = Date.now() - 8.64e7 + timeRange; // 最大时间
            return (
              time.getTime() < Date.now() - 8.64e7 || time.getTime() > _maxTime
            );
          }
        },
        viewType: "week",
        viewTypeList: [{
            name: "天视图",
            value: "day"
          },
          {
            name: "周视图",
            value: "week"
          }
        ],
        showForm: false,
        editType: 1,
        selectedDate: "",
        msg: {
          StartDate: "",
          EndDate: "",
          TeacherId: 0,
          ClassRoomId: 0,
          ClassType: 0,
          AppointState: 0
        },
        TeacherList: [],
        classroomList: [],
        ClassTypeList: [{
            label: "全部",
            Id: 0
          },
          {
            label: "跟班课",
            Id: 1
          },
          {
            label: "试听课",
            Id: 2
          },
          {
            label: "预约课",
            Id: 3
          }
        ],
        AppointStateList: [{
            label: "全部",
            Id: 0
          },
          {
            label: "待确认",
            Id: 1
          },
          {
            label: "已确认",
            Id: 2
          }
        ],
        colorList: [
          "blue-grey",
          "purple",
          "orange",
          "pink",
          "green",
          "teal",
          "secondary",
          "info",
          "pink",
          "deep-purple",
          "blue",
          "cyan",
          "cyan-8",
          "brown",
          "blue-grey"
        ],
        legendList: [],
        TeacherList2: [],
        events: [],
        dateObj: {},
        saveObj: {},
        auth: {
          IsEdit: false
        }
      };
    },
    components: {
      SubscribeForm
    },
    mounted() {
      this.selectedDate = QCalendar.today();
      this.getTeacherList();
      this.getclassroom();
      this.msg.StartDate = this.$refs.calendar.lastStart;
      this.msg.EndDate = this.$refs.calendar.lastEnd;
      this.getData();
      this.getAppointmentConfig();
      const ActionMenuList = JSON.parse(localStorage.getItem("loginUserInfo"))
        .data.ActionMenuList;
      const res = ActionMenuList.find(e => {
        return e.FunctionCode == "subscribe_edit";
      });
      if (res) {
        this.auth.IsEdit = true;
      } else {
        this.auth.IsEdit = false;
      }
    },
    methods: {
      badgeClasses(event, type, TeacherId) {
        const bg = this.getColor(TeacherId);
        return {
          [`text-white bg-${bg}`]: true
        };
      },
      badgeStyles(event, type, timeStartPos, timeDurationHeight, index, total) {
        const s = {};
        if (timeStartPos) {
          s.top = timeStartPos(event.StartTime) + "px";
        }
        if (timeDurationHeight) {
          let gap = this.calcGap(event.StartTime, event.EndTime);
          s.height = timeDurationHeight(gap) + "px";
        }
        s["align-items"] = "flex-start";
        s.left = 0;
        s.width = "100%";
        const singleW = (1 / total) * 100;
        s.width = singleW + "%";
        if (index == 0) {
          s.left = 0;
        } else {
          s.left = singleW * index + "%";
        }
        return s;
      },
      getHeight(event, timeDurationHeight) {
        let gap = this.calcGap(event.StartTime, event.EndTime);
        let height = timeDurationHeight(gap) + "px";
        return {
          height: height + "px"
        };
      },
      calendarNext() {
        this.$refs.calendar.next();
        setTimeout(() => {
          this.msg.StartDate = this.$refs.calendar.lastStart;
          this.msg.EndDate = this.$refs.calendar.lastEnd;
          this.getData();
        }, 100);
      },
      calendarPrev() {
        this.$refs.calendar.prev();
        setTimeout(() => {
          this.msg.StartDate = this.$refs.calendar.lastStart;
          this.msg.EndDate = this.$refs.calendar.lastEnd;
          this.getData();
        }, 100);
      },
      getTeacherList() {
        getTeacherDropDownList({
          LeaveStatus: 1,
          IsShow: 1
        }).then(res => {
          if (res.Code == 1) {
            this.TeacherList = JSON.parse(JSON.stringify(res.Data));
            var obj = {
              TeacherName: "不限",
              TId: 0
            };
            this.TeacherList.unshift(obj);
            this.TeacherList2 = JSON.parse(JSON.stringify(res.Data));
            this.TeacherList2.unshift({
              TeacherName: "请选择",
              TId: 0
            });
            this.legendList = JSON.parse(JSON.stringify(res.Data));

            this.legendList.forEach((item, index) => {
              item.bg = this.colorList[index];
            });
          }
        });
      },
      getclassroom() {
        queryClassRoomList({}).then(res => {
          if (res.Code == 1) {
            this.classroomList = res.Data;
            var obj = {
              RoomName: "不限",
              RoomId: 0
            };
            this.classroomList.unshift(obj);
          }
        });
      },
      getData() {
        GetAppointmentPlanStat(this.msg).then(res => {
          // this.events = res.Data;
          let data = JSON.parse(JSON.stringify(res.Data));
          res.Data.map((e, i) => {
            data[i].RList = [];
            e.RList.map(x => {
              this.legendList.map(y => {
                if (y.TId == x.TeacherId) {
                  data[i].RList.push(x);
                }
              });
            });
          });
          this.events = data;
        });
      },
      changeDate() {
        setTimeout(() => {
          this.msg.StartDate = this.$refs.calendar.lastStart;
          this.msg.EndDate = this.$refs.calendar.lastEnd;
          this.getData();
        }, 500);
      },
      calcGap(s, e) {
        let timeStamp = Date.now();
        let formatStr = date.formatDate(timeStamp, "YYYY-MM-DD");
        let start = new Date(formatStr + " " + s).getTime();
        let end = new Date(formatStr + " " + e).getTime();
        let res = (end - start) / 60000;
        return res;
      },
      getColor(TeacherId) {
        let bg = "";
        this.legendList.filter(item => {
          if (item.TId == TeacherId) {
            bg = item.bg;
          }
        });
        return bg;
      },
      onModelChanged(date) {},
      onClickDate2(data) {},
      onClickDayHeader2(data) {},
      onClickInterval2(data) {},
      onClickTime2(data) {
        //小于今天，不显示弹窗
        if (this.showAddStu(data.scope.timestamp.date) && this.auth.IsEdit) {
          this.showForm = true;
          this.editType = 1;
          this.saveObj = {};
          this.dateObj = data.scope.timestamp;
        }
      },
      onClickIntervalHeader2(data) {},
      showDetail(data, date, tid) {
        this.showForm = true;
        this.editType = 2;
        this.dateObj.date = date;
        this.saveObj = data;
        this.saveObj.Tid = tid;
      },
      confirmSub(date, id, item) {
        if (item.EnrollNum < item.ScrollMinNum) {
          this.$q.notify({
            message: `最小开班人数为${item.ScrollMinNum}`,
            position: "top",
            type: "negative"
          });
          return;
        }
        const msg = {
          Date: date,
          TeacherId: id,
          ShiftSort: item.ShiftSort
        };
        SetSureAppointment(msg).then(res => {
          if (res.Code == 1) {
            this.$q.notify({
              message: "操作成功",
              position: "top",
              type: "positive"
            });
            this.getData();
          }
        });
      },
      successHandle() {
        this.getData();
      },
      isShowTag(arr, min) {
        let n = 0;
        arr.map(e => {
          if (e.AppointType !== 3) {
            n += 1;
          }
        });
        if (n < min) {
          return true;
        } else {
          return false;
        }
      },
      getAppointmentConfig() {
        GetAppointmentConfig({}).then(res => {
          this.config = res.Data;
        });
      },
      showAddStu(date) {
        if (new Date(date).getTime() < new Date(QCalendar.today()).getTime()) {
          return false;
        } else {
          return true;
        }
      }
    }
  };
</script>

<style lang="scss">
  .viewbox {
    overflow-x: auto;
    box-sizing: border-box;
  }

  .calendar-container {
    position: relative;
    overflow: auto;
  }

  .my-event {
    position: absolute;
    font-size: 12px;
  }

  .searchBox .el-input__inner {
    border: none;
    background-color: transparent;
  }

  .searchBox .el-input .el-input__inner,
  .el-select .el-input {
    border-radius: 0;
    height: 25px;
  }

  .courseItem {
    height: 100%;
  }

  .detailLabel {
    width: 35px;
    white-space: nowrap;
  }

  .detailValue {
    width: 100%;
    display: inline-block;
  }
</style>