<template>
  <div class="m-container">
    <h2>
      <el-page-header @back="onCancel" :content="title"></el-page-header>
      <!-- <div class="squrt" /> -->
    </h2>
    <el-date-picker
      v-model="week"
      type="week"
      format="yyyy-MM 第 WW 周"
      value-format="yyyy-MM-dd"
      placeholder="选择周"
      @change="changeWeek"
      :picker-options="{
        firstDayOfWeek: 1,
      }"
    >
    </el-date-picker>
    <div class="taskList">
      <div class="teamDot dotBtn" draggable="true" @click="drop" @dragstart="dragstart($event)">下校巡查</div>
      <p>任务数量:<span :style="times>activeTotal?'color:red':''">{{activeTotal}}</span>/<span>{{times}}</span></p>
    </div>
    <div class="timeWrap">
      <div class="weekDotList">
        <!-- @click="setWeekDotList(item, index)" -->
        <div class="weekDot" v-for="(item, index) in weekList" :key="index">
          <p class="week">{{ item.week }}</p>
          <p class="date">{{ item.dateStr }}</p>
        </div>
      </div>
      <div class="timer" @drop="drop" @dragover="dragOver($event)">
        <div class="imgWrap" v-drag>
          <img :src="timerImg" />
          <div v-for="(item, index) in taskList" :key="index + 'new'">
            <el-popover placement="top" trigger="hover">
              <p>巡查日期:{{ item.planStart | dayjsFormat }}</p>
              <p>
                巡查时间:{{ item.planStart | dayjsFormatMinute }}~{{
                  item.planEnd | dayjsFormatMinute
                }}
              </p>
              <p>巡查乐团:{{ item.musicGroupName }}</p>
              <div
                slot="reference"
                :style="item.style"
                class="teamDot dot"
                @click="resetSchedule(item)"
              >
                下校巡查
              </div>
            </el-popover>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :title="isNew ? '新增下校巡查' : '修改下校巡查'"
      width="600px"
      :visible.sync="taskStatus"
      v-if="taskStatus"
    >
      <taskinfo
        :taskInfo="activeTask"
        ref="taskinfo"
        :rangeStart="rangeStart"
        :rangeEnd="rangeEnd"
        :MusicGroupList="MusicGroupList"
        :itemId="itemId"
        @refreshList="refreshList"
      />
      <div slot="footer" style="margin-top: 20px" class="dialog-footer">
        <el-button @click="taskStatus = false">取 消</el-button>
        <el-button type="primary" v-if="isNew" @click="submitInfo(0)"
          >确 定</el-button
        >
        <el-button type="primary" v-else @click="submitInfo(1)"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <taskList style="margin-top: 15px;" ref="taskList" @resetSchedule="resetSchedule" @getTotal='getTotal'/>
  </div>
</template>
<script>
import dayjs from "dayjs";
import { getInspectionItemPlan, getMusicGroup } from "../api";
import taskinfo from "./compontent/taskInfo";
import taskList from "./compontent/taskList";
import { permission } from "@/utils/directivePage";
import {
  setDate,
  getNowDateAndSunday,
  getNowDateAndMonday,
  getWeekDay,
} from "@/utils/date";
export default {
  name:'scheduleDetail',
  components: {
    taskinfo,
    taskList,
  },
  data() {
    return {
      timerImg: require("@/views/main/teamSchedule/compontent/weekTimer.png"),
      active: -1,
      week: new Date(),
      weekList: [],
      startTime: "",
      endTime: "",
      taskList: [],
      weekDay: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      tableTime: "",
      title: "",
      userId: "",
      taskStatus: false,
      activeTask: null,
      isNew: false,
      rangeStart: "",
      rangeEnd: "",
      organId: "",
      MusicGroupList: [],
      times:'',
      activeTotal:''
    };
  },
  async mounted() {
    console.log('加载页面')
    this.init();
    // 获取乐团
    try {
      const ruselt = await getMusicGroup({ organId: this.organId });
      this.MusicGroupList = ruselt.data;
    } catch (e) {}
  },
  methods: {
    init() {
      this.times = this.$route.query.times
      this.itemId = this.$route.query.itemId;
      this.organId = this.$route.query.organId;
      this.rangeStart = this.$route.query.startTime;
      this.rangeEnd = this.$route.query.endTime;
      this.week = this.$route.query.startTime;
      this.userId = this.$route.query.teacher;
      this.startTime = this.$route.query.startTime;
      let titleMoth = dayjs(this.startTime).format("MM");
      this.title = `${this.$route.query.name}${titleMoth}月下校巡查安排`;
      this.getCalendatList();
      this.setWeekList();
    },
    setStartTimeAndEndTime(date) {
      this.startTime = getNowDateAndMonday(date);
      if (this.active === -1) {
        this.active = 0;
        this.tableTime = this.startTime;
      }
      this.endTime = getNowDateAndSunday(date);
    },
    async getCalendatList() {
      // console.log(this.$route.query.startTIme)
      // 获取本周的周一和周日 以及这一周得课
      this.setStartTimeAndEndTime(this.week);
      try {
        const result = await getInspectionItemPlan({
          startTime: this.startTime,
          endTime: this.endTime,
          userId: this.userId,
          page: 1,
          rows: 9999,
        });
        this.dataList = result.data.rows;
         this.taskList = [];
        for (let i in this.dataList) {
          this.setCourseTime(this.dataList[i]);
          this.taskList.push(this.dataList[i]);
        }
      } catch (e) {
        console.log(e);
      }
    },
    setCourseTime(row) {
      let startMinutes = this.getMinutes(row.planStart.split(" ")[1]);
      let endMinutes = this.getMinutes(row.planEnd.split(" ")[1]);
      let width = (endMinutes - startMinutes) * 1.8;
      //7点开始  7*60= 420 分钟 每分钟1.8像素 17像素是图片的时间的起始点
      let left = startMinutes - 420 > 0 ? (startMinutes - 420) * 1.8 + 17 : 17;
      let top =
        getWeekDay(row.planStart) === 1
          ? 40
          : getWeekDay(row.planStart) * 60 - 16;
      row.style = {
        width: width + "px",
        top: top + "px",
        left: left + "px",
      };
    },
    getMinutes(str) {
      return parseInt(str.split(":")[0]) * 60 + parseInt(str.split(":")[1]);
    },
    setWeekList() {
      this.weekList = [];
      let startTime = new Date(this.startTime.replace(/-/g, "/"));
      startTime.setTime(startTime.getTime() - 1000 * 60 * 60 * 24);
      for (let i = 0; i < 7; i++) {
        startTime.setTime(startTime.getTime() + 1000 * 60 * 60 * 24);
        // startTime.setTime(startTime.getTime() - 1000 * 60 * 60 * 24)
        this.weekList.push({
          week: this.weekDay[i],
          dateStr: startTime.getMonth() + 1 + "月" + startTime.getDate() + "日",
          date: setDate(startTime),
        });
      }
    },
    setWeekDotList(item, index) {
      this.active = index;
      this.tableTime = item.date;
    },
    changeWeek(val) {
      this.week = val;
      this.active = -1;
      this.getCalendatList();
      this.setWeekList();
      this.$refs.taskList.getList();
    },
    onCancel() {
        this.$store.dispatch('delVisitedViews', this.$route)
      this.$router.push({
        path: "/main/main",
        query: { tabrouter: "teamSchedule" },
      });
    },

    drop(e) {
      console.log(e)
      this.isNew = true;
      this.activeTask = null;
      this.taskStatus = true;
    },
    dragOver(event) {
      event.preventDefault();
    },
    dragstart(e){
      console.log(e)
    },
    submitInfo(val) {
      // 新增修改提交
      this.$refs.taskinfo.submitInfo(val);
    },
    refreshList(date) {
      // 根据这个时间刷新

      this.taskStatus = false;
      this.changeWeek(date);
    },
    resetSchedule(row) {
      // 判断是否有权限
      if (permission("inspectionItemPlan/update")) {
        this.isNew = false;
        this.activeTask = row;
        this.taskStatus = true;
      }
    },
    getTotal(val){
      this.activeTotal = val
    }
  },

  directives: {
    drag(el) {
      // 拖拽大图片移动
      let oDiv = el; //当前元素
      let self = this; //上下文
      oDiv.onmousedown = function (e) {
        //鼠标按下，计算当前元素距离可视区的距离
        let disX = e.clientX - oDiv.offsetLeft;
        let disY = e.clientY - oDiv.offsetTop;
        let wrapW = document.querySelector(".timer").offsetWidth;
        let imgW = document.querySelector(".imgWrap").offsetWidth;
        document.onmousemove = function (e) {
          //通过事件委托，计算移动的距离
          let l = e.clientX - disX;
          let t = e.clientY - disY;
          //移动当前元素

          if (l > 0) {
            l = 0;
          } else if (l < -(imgW - wrapW) + 2) {
            l = -(imgW - wrapW) + 2;
          }

          oDiv.style.left = l + "px";
          // oDiv.style.top = t + "px";
        };
        document.onmouseup = function (e) {
          document.onmousemove = null;
          document.onmouseup = null;
        };
        return false;
      };
    },
  },
};
</script>
<style lang="scss" scoped>
.taskList {
  margin-top: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  .dotBtn {
    cursor: pointer;
    padding: 0 10px;
    color: #fff;
    font-size: 14px;
    line-height: 25px;
    border-radius: 3px;
    margin-right: 20px;
  }
}
.teamDot {
  background: linear-gradient(
    to left,
    rgba(90, 121, 246, 0.75),
    rgba(90, 121, 246, 1)
  );
}

.timeWrap {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  .timer {
    width: 1478px;
    overflow: auto;
    position: relative;
    .imgWrap {
      width: 1659px;
      position: relative;
      z-index: 1;
      img {
        width: 1659px;
        position: relative;
        z-index: 1;
      }
      .dot {
        -moz-user-select: none; /*火狐*/
        -webkit-user-select: none; /*webkit浏览器*/
        -ms-user-select: none; /*IE10*/
        user-select: none;
        cursor: pointer;
        position: absolute;
        min-width: 75px;
        height: 25px;
        color: #fff;
        font-size: 14px;
        line-height: 25px;
        padding-left: 5px;
        z-index: 10;
        top: 40px;
        right: 0;
        border-radius: 3px;
      }
      .vipDot {
        background: linear-gradient(
          to left,
          rgba(42, 174, 166, 0.75),
          rgba(42, 174, 166, 1)
        );
      }
      .newDot {
        background: linear-gradient(
          to left,
          rgba(52, 177, 246, 0.75),
          rgba(52, 177, 246, 1)
        );
      }
    }
  }
  .weekDotList {
    margin: 24px 10px 0 0;
    width: 70px;
    display: flex;
    flex-direction: column;
    background-color: #fff;

    .weekDot {
      cursor: pointer;
      -moz-user-select: none; /*火狐*/
      -webkit-user-select: none; /*webkit浏览器*/
      -ms-user-select: none; /*IE10*/
      user-select: none;
      width: 70px;
      height: 60px;
      background-color: #fff;
      color: #fff;
      padding: 10px 0 10px 10px;
      border-radius: 5px;
      color: #000;
      p {
        font-size: 12px;
        line-height: 20px;
      }
      .week {
        font-size: 12px;
        color: #999;
      }
      .date {
        font-size: 12px;
        color: #333;
      }
    }
    .weekDot.active {
      background-color: rgba(19, 129, 122, 1);
      color: #fff !important;
      border-radius: 5px;
      .week {
        font-size: 12px;
        color: #fff;
      }
      .date {
        font-size: 14px;
        color: #fff;
      }
    }
  }
}
</style>
