<template>
  <div class="scheduling">
    <div class="search">
      <el-date-picker
        v-model="monthValue"
        value-format="yyyy-MM-dd"
        type="month"
        placeholder="选择时间"
        :clearable="false"
      ></el-date-picker>
      <div class="search-icon">
        <el-tooltip
          effect="light"
          placement="bottom"
          content="批量排班"
        >
          <i
            class="zoniot_font zoniot-icon-piliangshenhe"
            @click="add()"
          ></i>
        </el-tooltip>
        <el-tooltip
          effect="light"
          placement="bottom"
          content="返回"
        >
          <i
            class="zoniot_font zoniot-icon-fanhui"
            @click="goback()"
          ></i>
        </el-tooltip>
      </div>
    </div>
    <el-calendar
      first-day-of-week="7"
      v-model="monthValue"
    >
      <template
        slot="dateCell"
        slot-scope="{ date, data }"
        v-if="data.type === 'current-month'"
      >
        <div class="showDateDay">{{ date | dateNewType }}</div>
        <div class="schedulingUser">
          <template v-for="(item, index) in calendarData">
            <div
              :key="index"
              v-if="data.day == item.partrolDate"
            >
              <template v-for="(itx, inxs) in item.rosterUserDtos">
                <div
                  :key="inxs"
                  class="listTime"
                  v-if="thisDayOfStaDay(data)"
                >
                  <span>{{ itx.partrolTime }}</span>
                  <span>{{ itx.partolName }}</span>
                </div>
              </template>
              <template v-if="
                                    date.getTime() <= $moment(zeroTetracosa(thisObj.endDate)).valueOf() &&
                                    thisTimeFF(data, item.rosterUserDtos)
                                ">
                <!-- 每周那几天 -->
                <span v-if="thisObj.periodType == 1">
                  <template v-if="periodValueType(thisObj.periodValue).includes(date.getDay() + '') && thisDayOfStaDay(data)">
                    <div
                      class="pointSet"
                      @click="addItem(date, data, item,1)"
                    >点击设置</div>
                  </template>
                </span>
                <!-- 每隔N天 -->
                <span v-else>
                  <template v-if="timeAddDay(thisObj, thisObj.periodValue, data)">
                    <div
                      class="pointSet"
                      @click="addItem(date, data, item,2)"
                    >点击设置</div>
                  </template>
                </span>
              </template>
            </div>
          </template>
          <!-- 时间范围内且没有排班 -->
          <template v-if="
                            date.getTime() <= $moment(zeroTetracosa(thisObj.endDate)).valueOf() &&
                            thisTimeNull(data, thisObj.timePeriod) &&
                            !trueArr.includes(data.day)
                        ">
            <!-- 每周那几天 -->
            <span v-if="thisObj.periodType == 1">
              <template v-if="periodValueType(thisObj.periodValue).includes(date.getDay() + '') && thisDayOfStaDay(data)">
                <div
                  class="pointSet"
                  @click="add(data)"
                >点击设置</div>
              </template>
            </span>
            <!-- 每隔N天 -->
            <span v-else>
              <template v-if="timeAddDay(thisObj, thisObj.periodValue, data)">
                <div
                  class="pointSet"
                  @click="add(data)"
                >点击设置</div>
              </template>
            </span>
          </template>
        </div>
      </template>
    </el-calendar>
  </div>
</template>
<script>
export default {
  data () {
    return {
      monthValue: '',
      findUser: [],
      thisObj: {},
      calendarData: [],
      indexThis: 0,
      trueArr: [] //已有设置时间集合
    };
  },
  filters: {
    dateNewType (val) {
      return val.getDate();
    }
  },
  watch: {
    monthValue (e) {
      try {
        let timeArr = e.split('-');
        let time = new Date(timeArr[0], Number(timeArr[1]), 0);
        this.getShiftInformation({
          patrolRouteId: this.thisObj.id,
          startTime: `${timeArr[0]}-${timeArr[1]}-01 00:00:00`,
          endTime: `${timeArr[0]}-${timeArr[1]}-${time.getDate()} 23:59:59`
        });
      } catch { }
    }
  },
  methods: {
    zeroTetracosa (val) {
      if (!!val) {
        return this.$moment(val).format('YYYY-MM-DD') + ' 23:59:59';
      }
      return val;
    },
    add (dateDe) {
      let title = '排班',
        isSingle = true;
      if (dateDe == undefined) {
        title = '批量排班';
        isSingle = false;
      }

      new Promise((resolve) => {
        this.$store.dispatch('addPopup', {
          url: '/patrolManagement/popups/schedulingAdd.vue',
          width: '450px',
          height: '300px',
          props: {
            callback: resolve,
            findUser: this.findUser,
            dateDe,
            thisObj: this.thisObj,
            isSingle: isSingle
          },
          title: title
        });
      }).then(() => {
        let newTime = this.$moment(this.monthValue).format('YYYY-MM-DD');
        let timeArr = newTime.split('-');
        let time = new Date(timeArr[0], Number(timeArr[1]), 0);
        this.getShiftInformation({
          patrolRouteId: this.thisObj.id,
          startTime: `${timeArr[0]}-${timeArr[1]}-01 00:00:00`,
          endTime: `${timeArr[0]}-${timeArr[1]}-${time.getDate()} 23:59:59`
        });
      });
    },
    addItem (da, dateDe, onj, index) {
      console.log('测试', da, dateDe, onj, index)
      new Promise((resolve) => {
        this.$store.dispatch('addPopup', {
          url: '/patrolManagement/popups/schedulingAdd.vue',
          width: '450px',
          height: '300px',
          props: {
            callback: resolve,
            findUser: this.findUser,
            dateDe,
            onj,
            index,
            thisObj: this.thisObj,
            isSingle: true
          },
          title: '排班'
        });
      }).then(() => {
        let newTime = this.$moment(this.monthValue).format('YYYY-MM-DD');
        let timeArr = newTime.split('-');
        let time = new Date(timeArr[0], Number(timeArr[1]), 0);
        this.getShiftInformation({
          patrolRouteId: this.thisObj.id,
          startTime: `${timeArr[0]}-${timeArr[1]}-01 00:00:00`,
          endTime: `${timeArr[0]}-${timeArr[1]}-${time.getDate()} 23:59:59`
        });
      });
    },
    goback () {
      this.$emit('initPage');
    },
    initDate (type) {
      this.monthValue = this.$moment().format(type);
    },
    getShiftInformation (obj) {
      this.$http.post('/sc-community/patrolRoute/getShiftInformation', obj).then(({ data, status, msg }) => {
        if (!!data) {
          this.calendarData = [];
          let calendarData = [],
            trueArr = [];
          for (let inx in data) {
            let rosterUserDtos = [];
            data[inx].map((item) => {
              rosterUserDtos.push({
                partrolTime: item.patrolTime,
                partolName: item.partolName,
                patrolUserId: item.patrolUserId,
                currentUsers: item.currentUsers,
              });
            });
            trueArr.push(this.$moment(inx).format('YYYY-MM-DD'));
            calendarData.push({
              partrolDate: this.$moment(inx).format('YYYY-MM-DD'),
              rosterUserDtos: rosterUserDtos
            });
          }
          this.calendarData = calendarData;
          this.trueArr = trueArr;
          this.indexThis = 0;
          this.$forceUpdate();
        }
      });
    },
    periodValueType (value) {
      if (!!value) {
        let vra = value.split(',').sort();
        vra.map((item, index) => {
          if (item == 7) {
            vra[index] = '0';
          }
        });
        return vra;
      }
      return [];
    },
    timeAddDay (val, sunDay, d) {
      let sum = sunDay || 0;
      let bb = false;
      if (!!val && !!sunDay) {
        if (this.indexThis <= 30) {
          this.indexThis++;
        }
        let { startDate } = val;
        let thisD = this.$moment(d.day + ' 00:00:00').valueOf();
        if (this.thisTimeTypeShow(this.$moment(startDate).valueOf(), Number(sum)).includes(thisD)) {
          bb = true;
        }
      }
      return bb;
    },
    thisTimeTypeShow (kai, sum) {
      // 零点计算 sum天得+1
      let oneDay = 86400000,
        indU = [];
      for (let x = 0; x <= 16; x++) {
        indU.push(kai + x * (sum + 1) * oneDay);
      }
      return indU;
    },
    thisTimeNull (s, item) {
      let thisDate = this.$moment(new Date());
      let sur = false;
      if (!!item) {
        let timePot = item.split('-');
        timePot.map((its) => {
          if (this.$moment(`${s.day} ${its}:00`).valueOf() > thisDate.valueOf()) {
            sur = true;
            return sur;
          }
        });
      }

      return sur;
    },
    thisDayOfStaDay (data) {
      let startDate = this.$moment(this.thisObj.startDate).valueOf();
      let thisDate = this.$moment(data.day + ' 00:00:00').valueOf();
      return startDate <= thisDate;
    },
    thisTimeFF (s, arr) {
      let thisDate = this.$moment(new Date());
      let sur = false;
      arr.map((item, index) => {
        let timePot = item.partrolTime.split('-');
        timePot.map((its) => {
          if (this.$moment(`${s.day} ${its}:00`).valueOf() > thisDate.valueOf()) {
            sur = true;
            return sur;
          }
        });
        return sur;
      });
      return sur;
    }
  },
  created () {
    this.initDate('YYYY-MM-DD');
  },
  mounted () {
    this.findUser = this.$parent.findUser;
    this.thisObj = this.$parent.thisObj;
    this.thisObj.periodType == 1;
    this.$el.querySelector('div.el-calendar__header').remove();
  }
};
</script>
<style scoped lang='scss'>
.scheduling {
    font-size: 12px;
    .showDateDay {
        font-size: 30px;
        text-align: center;
    }
    .schedulingUser {
        cursor: pointer;
        padding: 0 20px;
        line-height: 25px;
        .listTime {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
    .pointSet {
        cursor: pointer;
        line-height: 35px;
        text-align: center;
        color: #0eaeff;
    }
    /deep/ .el-calendar-table {
        &:not(.is-range) {
            td.next {
                pointer-events: none;
            }
            td.prev {
                pointer-events: none;
            }
        }
        .el-calendar-day {
            height: 110px;
            overflow: auto;
            &::-webkit-scrollbar {
                width: 5px;
            }
            &::-webkit-scrollbar-track {
                border-radius: 5px;
                background: #f4f7f9a8;
            }
            &::-webkit-scrollbar-thumb {
                border-radius: 5px;
                background: #c6c4c4a9;
            }
        }
    }
}
</style>