<style lang="less" scoped>
.workOvertime {
    .space-title {
        font-weight: 500;
        font-size: 52rpx;
        line-height: 72rpx;
        color: #000000;
        margin-bottom: 4rpx;
        word-break: break-all;
    }
    .space-text {
        color: #c4c4c4;
        font-size: 26rpx;
        line-height: 36rpx;
    }
    .period-selector {
        padding-top: 40rpx;
    }
    .btn-box {
        display: flex;
        justify-content: space-around;
        padding-top: 90rpx;
        .btn {
            height: 100rpx;
            width: 240rpx;
            border-radius: 50rpx;
            border: 1px solid #c3c7cb;
            text-align: center;
            line-height: 100rpx;
            &.sub {
                border-color: white;
                background: rgba(61, 203, 204, 1);
                color: #FFFFFF;
                width: 390rpx;
            }
            &.dis-sub {
                background: #c3c7cb;
            }
        }
    }
    .min {
        color: #c3c7cb;
        font-size: 12px;
    }
}
</style>
<template>
    <div class="workOvertime">
        <div class="space-title">{{localName}} 申请延时 </div>
        <div class="space-text">延时期间，空间相关设备会开启</div>
        <div class="fliter-area">
            <div class="date-selector">
                <date-selector
                    @component-date-selector-select="changeSelectedData"
                    :selectValue="date"
                ></date-selector>
            </div>
            <div class="period-selector">
                <period-time-slider
                    v-if="showAndHidden"
                    disabledPast="{{disabledPast}}"
                    :showPastDisabled="true"
                    :disabledUnopened="true"
                    @component-period-time-slider-select="selectedPeriod"
                    @component-bookList-delete="bookListDelete"
                    :selectValue="period"
                    :bookedList="roomData.bookedList[date]"
                    @component-period-time-slider-judgecanselectedend="judgeCanSelectedEnd"
                    :hiddenBookedUserName="roomData.classification==1"
                    :openStartTime="openStartTime"
                    :openEndTime="openEndTime"
                ></period-time-slider>
            </div>
        </div>
        <div class="btn-box">
            <span
                class="btn"
                @click="handleCancel"
            >取消</span>
            <span
                class="{{'btn'+' sub'+(canBooked ? '':' dis-sub')}}"
                @click="handleSubmit"
                :disabled="!canBooked"
            >提交申请
                <span class="min">{{sstext}}</span>
            </span>
        </div>
    </div>
</template>
<script>
import wepy from '@wepy/core'
import store from '@/store'
import { saveBatchCustomScene } from '@/packagesEnv/api/officehome.js'

import config from '@/config'
import moment from 'moment'
import {
    getNowDate,
    getNowTime,
    SliderUnit
} from '@/service/meetingTimes'
import {
    formateBookedList,
    formateTimeValue,
    formateDateValue,
    formateTimeToColon,
    formateTimeToValue,
    dateToDate,
    endtimeToUnitTime,
    startimeToUnitTime
} from '@/packagesEnv/pages/common.js'
function timeRangeLowLastTime(val) {
  let newVal = val + SliderUnit * 4
  if (newVal > 24) {
    return 24
  }
  return newVal
}
let resData = {}
let timer = null
wepy.component({
  props: {
    localName: String,
    workDayTime: Object,
    objectId: Object,
    countDownTwoMin: Number
  },
  store,
  data: {
    date: getNowDate(),
    currentCheckedItem: [], // 当前选中项
    disabledPast: true,
    roomId: '',
    hasCus: false, // 是否有服务定制
    openStartTime: null, // 服务定制开始时间
    openEndTime: null, //  服务定制结束时间
    customTime: { // 记录服务定制初始值
      start: '',
      end: ''
    },
    canBooked: false, // 标记是否可以预定
    period: null,
    roomData: {
      bookedList: []
    },
    deleteBookedListIdx: null,
    showAndHidden: true,
    sstext: '' // 倒计时展示

  },
  watch: {
    workDayTime(newVal) {
      if (newVal) {
        resData = newVal
        this.cusTime()
      }
    },
    countDownTwoMin(ss) {
      this.text = ''
      if (ss < 60 && ss !== 0) {
        this.sstext = `( ${ss} s )`
      } else {
        this.sstext = ''
      }
    }
  },
  ready() {
    this.setDefaultPeriod()
  },
  detached() {
  },
  methods: {
    cusTime() { // 服务定制时间及预约时段
      let copyResData = JSON.parse(JSON.stringify(resData));
      (copyResData.data || []).forEach(item => {
        item.date = dateToDate(item.date)
        if (item.date === this.date) {
          this.hasCus = true
          item.cusStartTime = item.cusStartTime ? item.cusStartTime : '000000'
          item.cusEndTime = item.cusEndTime ? item.cusEndTime : '000000'
          this.customTime = {
            start: item.cusStartTime,
            end: item.cusEndTime
          }
          const start = startimeToUnitTime(item.cusStartTime)
          const end = endtimeToUnitTime(item.cusEndTime)
          this.openStartTime = formateTimeToValue(start)
          this.openEndTime = formateTimeToValue(end) - 0.5

          item.customSceneList && item.customSceneList.find(item => {
                        // console.log(item, 'yuyue');
            item.startDate = dateToDate(item.startDate)
            item.endDate = dateToDate(item.endDate)
          })
          this.currentCheckedItem = item.customSceneList || []
        }
      })
      if (!this.hasCus) {
        this.openStartTime = ''
        this.openEndTime = ''
      }
      setTimeout(() => {
        this.roomData.bookedList = formateBookedList(this.currentCheckedItem)
      }, 200)
    },
    handleCancel() { // 取消
      this.$emit('component-close-visible', false)
    },
    deleteOrAdd(type) { // 删除或者增加
      const bookListDayArr = this.roomData.bookedList[this.date] || []
      let workType = 0  // 0 预约加班，1 取消，2 加班(我来了)， 3 最后一个走
      if (type === 'cancel') {
        workType = 1
      } else {
        const nowTime = getNowTime().juggeValue
        if ((this.period.start <= nowTime) && nowTime <= this.period.end) {
          workType = 2
        } else {
          workType = 0
        }
      }
      let historyBookList = [] // 历史选择的时段
      bookListDayArr && bookListDayArr.forEach((item, idx) => {
        if (
                    (this.period.start <= item.start && item.start <= this.period.end) ||
                    (this.period.start <= item.end && item.end <= this.period.end) ||
                    (item.start <= this.period.start && this.period.end <= item.end)
                ) {  // 跟选择的时段有交集
          item.type = 1
          historyBookList.push(item)
        }
      })
      const date = formateDateValue(this.date)
      let newBooklist = {
        startDate: date,
        endDate: date,
        startTime: formateTimeValue(this.period.start),
        endTime: formateTimeValue(this.period.end),
        type: workType,
        objectId: this.objectId,
        customSceneEqType: 'ALL'  // 来源 AC 空调入口, SE 灯入口 ALL 加班入口
      }
      return { historyBookList, newBooklist }
    },
    bookAndPried(newBooklist, historyBookList) {
      const newBookStart = newBooklist.startTime
      const newBookEnd = newBooklist.endTime
      let bookedrange = []; // 已选择的区间
      (historyBookList || []).forEach((item, idx) => {
        bookedrange.push(item.startTime)
        bookedrange.push(item.endTime)
      })
      bookedrange = [...new Set(bookedrange)]
      bookedrange.sort()
      const bookedrangeStart = bookedrange[0]
      const bookedrangeEnd = bookedrange[bookedrange.length - 1]
      return { newBookStart, newBookEnd, bookedrangeStart, bookedrangeEnd }
    },
    bookListDelete() { // 删除一条加班记录
      let { historyBookList, newBooklist } = this.deleteOrAdd('cancel')
      let { newBookStart, newBookEnd, bookedrangeStart, bookedrangeEnd } = this.bookAndPried(newBooklist, historyBookList)
      let saveBookList = []
      if (bookedrangeStart === newBookStart && bookedrangeEnd === newBookEnd) {
                // 选区全部包括
      } else {
        if (bookedrangeStart === newBookStart) { // 选区的开始重合
          newBooklist.startTime = newBookEnd
          newBooklist.endTime = bookedrangeEnd
          saveBookList.push(newBooklist)
          console.log('选区的开始重合')
        } else if (bookedrangeEnd === newBookEnd) { // 选区的结束重合
          newBooklist.startTime = bookedrangeStart
          newBooklist.endTime = newBookStart
          saveBookList.push(newBooklist)
          console.log('选区的结束重合')
        } else { // 选区中间
          newBooklist.startTime = bookedrangeStart
          newBooklist.endTime = newBookStart
          saveBookList.push(newBooklist)
          const newBooklistTwo = JSON.parse(JSON.stringify(newBooklist))
          newBooklistTwo.startTime = newBookEnd
          newBooklistTwo.endTime = bookedrangeEnd
          saveBookList.push(newBooklistTwo)
          console.log('选区的中间')
        }
      }
      const nowTime = moment().format('HHmmss')
      saveBookList.find(item => {
        if (nowTime >= item.startTime && nowTime <= item.endTime) {
          item.type = 2
        } else {
          item.type = 0
        }
      })

      let arr = [...historyBookList, ...saveBookList]
      let paramsArr = []
      arr.map(item => {
        if (item.startTime < item.endTime) {
          paramsArr.push(item)
        }
      })
      let deleStart = newBookStart
      let deleEnd = newBookEnd
      if (deleStart < this.customTime.end && deleStart > this.customTime.start) {
        deleStart = this.customTime.end
      }
      if (deleEnd > this.customTime.start && deleEnd < this.customTime.end) {
        deleEnd = this.customTime.start
      }

      let _this = this
      wx.showModal({
        title: '',
        content: `删除 ${formateTimeToColon(deleStart)}-${formateTimeToColon(deleEnd)} 预约时间？`,
        success: function (sm) {
          if (sm.confirm) {
            saveBatchCustomScene({ 'historyBookList': paramsArr, type: 'delete' }).then(res => {
              _this.$emit('component-set-countDown')
              _this.$emit('component-close-visible', false)
            })
          } else {
                        // console.log('取消');
          }
        }
      })

            // this.roomData.bookedList.splice(deleteBookedListIdx, 1)
            /*   let arr = this.roomData.bookedList[this.date];
              arr.splice(deleteBookedListIdx, 1);
              this.roomData.bookedList[this.date] = arr */
    },
    handleSubmit() { // 提交申T请
      if (!this.canBooked) return
      if (timer) return
      timer = setTimeout(() => { }, 1000 * 2)
      this.canBooked = false
      let { historyBookList, newBooklist } = this.deleteOrAdd('save')
      let { newBookStart, newBookEnd, bookedrangeStart, bookedrangeEnd } = this.bookAndPried(newBooklist, historyBookList)
      if (bookedrangeStart <= newBookStart && newBookEnd <= bookedrangeEnd) {
        if (this.period.hasUuBooked) {
          newBooklist.startTime = bookedrangeStart
          newBooklist.endTime = bookedrangeEnd
        }
      } else {
        if (((bookedrangeStart < newBookEnd) && (newBookEnd < bookedrangeEnd)) || newBookEnd === bookedrangeStart) {
                    //    开始时间早于 已经预约的时间
          newBooklist.endTime = bookedrangeEnd
        }
        if (((bookedrangeStart < newBookStart) && (newBookStart < bookedrangeEnd)) || newBookStart === bookedrangeEnd) {
                    // 结束时间时间晚于 已经预约的时间
          newBooklist.startTime = bookedrangeStart
        }
      }
      if (newBooklist.startTime > this.customTime.start &&
                newBooklist.startTime < this.customTime.end) {
        newBooklist.startTime = this.customTime.end
      }
      if (newBooklist.endTime > this.customTime.start &&
                newBooklist.endTime < this.customTime.end) {
        newBooklist.endTime = this.customTime.start
      }

      saveBatchCustomScene({ historyBookList, newBooklist })
      .then(res => {
        clearTimeout(timer)
        timer = null
        this.$emit('component-set-countDown')
        this.$emit('component-close-visible', false)
        // this.canBooked = true;
      })
      .catch(() => {
        clearTimeout(timer)
        timer = null
        this.$emit('component-set-countDown')
        this.$emit('component-close-visible', false)
      })
    },
    setDefaultPeriod() {    // 默认选中时间
      let nowHour = getNowTime().juggeValue
      if (this.openStartTime !== this.openEndTime) { // 有服务定制  服务定制向后两个小时
        const realOpenEndTime = this.openEndTime + 0.5
        if (nowHour > this.openStartTime && nowHour < realOpenEndTime) { // 服务定制中
          this.period = {
            start: realOpenEndTime,
            end: timeRangeLowLastTime(realOpenEndTime),
            from: 'outer'
          }
        }
        if (nowHour >= realOpenEndTime || nowHour === this.openStartTime) { // 服务定制后
          this.period = {
            start: nowHour,
            end: timeRangeLowLastTime(nowHour),
            from: 'outer'
          }
          return
        }
        if (nowHour < this.openStartTime) { // 服务定制前
          if ((this.openStartTime - nowHour) >= 2) {
            this.period = {
              start: nowHour,
              end: timeRangeLowLastTime(nowHour),
              from: 'outer'
            }
          } else {
            this.period = {
              start: nowHour,
              end: nowHour + (this.openStartTime - nowHour),
              from: 'outer'
            }
          }
        }
      } else { // 没有服务定制
        this.period = {
          start: nowHour,
          end: timeRangeLowLastTime(nowHour),
          from: 'outer'
        }
      }
    },
    selectedPeriod({ start, end, hasUuBooked }) {
      this.period = { start, end, hasUuBooked }
    },
    judgeCanSelectedEnd(canBooked) {
      this.canBooked = canBooked
    },
    changeSelectedData(date) {  // 选择日期
      this.selectedDate(date)
            //   this.getServeTime(date);
      this.cusTime()
    },
    selectedDate(date) {
      this.date = date
      this.disabledPast = date == getNowDate()
    },
    getServeTime(date) {
            /*  if (!this.roomId) {
               return;
             } */
            //   this.openStartTime = formateTimeToValue('24:00');
            //   this.openEndTime = formateTimeToValue('24:00');
      this.canBooked = false
            /*  getMeetingRoomServerTime({
               id: this.roomId,
               day: date
             }).then(res => {
               let result = res.data || {};
               if (result.businessFlag) {
                  // 如果营业
                 this.openStartTime = formateTimeToValue(result.startTime);
                 this.openEndTime = formateTimeToValue(result.endTime);
               } else {
                 // 不营业, 全天标红,利用这种方式去标红
                 this.openStartTime = formateTimeToValue('24:00');
                 this.openEndTime = formateTimeToValue('24:00');
                 this.canBooked = false;
               }
             }); */
    }
  }
})
</script>




<config>
{
    "backgroundColor": "#fff",
    "usingComponents": {
      "period-time-slider": "./components/period-time-slider",
      "date-selector":"./components/date-selector",
    }
}
</config>
