<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;
    }
    .box {
        position: fixed;
        bottom: 0;
        height: 110px;
        z-index: 999;
        display: flex;
        align-items: center;
        background: linear-gradient(
            0deg,
            #ffffff 78.17%,
            rgba(255, 255, 255, 0) 100%
        );
    }
    .btn-box {
        display: flex;
        justify-content: space-around;
        .btn {
            height: 100rpx;
            width: 240rpx;
            border-radius: 50rpx;
            border: 1px solid #c3c7cb;
            text-align: center;
            line-height: 100rpx;
            &.sub {
                border-color: white;
                color:#FFFFFF;
                background: rgba(61, 203, 204, 1);
                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-hand
                    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"
                    :customList="customList"
                ></period-time-slider-hand>
            </div>
        </div>
        <div v-show="spaceEquipList.length">
            <book-equipments
                :spaceEquipList="spaceEquipList"
                :bookEquipList="bookEquipList"
                ref="refBookEquip"
            ></book-equipments>
        </div>
        <div class="box">
            <div class="btn-box">
                <span
                    class="btn"
                    @click="handleCancel"
                >取消</span>
                <span
                    class="{{'btn'+' sub'+(canBooked ? '':' dis-sub')}}"
                    style="margin-left:20rpx"
                    @click="handleSubmit"
                    :disabled="!canBooked"
                >提交申请
                    <span class="min">{{sstext}}</span>
                </span>
            </div>
        </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'

let resData = {}
let timer = null
wepy.component({
  props: {
    equipConfig: Array, // 设备配置是否可控
    localName: String,
    workDayTime: Object,
    objectId: Object,
    countDownTwoMin: Number,
    bookEquipList: String
  },
  store,
  data: {
    date: getNowDate(),
    currentCheckedItem: [], // 当前选中项
    disabledPast: true,
    roomId: '',
    hasCus: false, // 是否有服务定制
    customList: [],  // 服务定制
    customTimeInit: [], // 记录服务定制初始值
    canBooked: false, // 标记是否可以预定
    period: null,
    roomData: {
      bookedList: []
    },
    deleteBookedListIdx: null,
    showAndHidden: true,
    sstext: '', // 倒计时展示
    spaceEquipList: [] // 单空间设备
  },
  watch: {
    workDayTime(newVal) {
      if (newVal) {
        resData = newVal
        this.spaceEquipList = resData.data[0].equipmentList
        this.cusTime()
      }
    },
    countDownTwoMin(ss) {
      this.text = ''
      if (ss < 60 && ss !== 0) {
        this.sstext = `( ${ss} s )`
      } else {
        this.sstext = ''
      }
    }
  },
  ready() {
    this.setDefaultPeriod()
  },
  detached() {
  },
  methods: {
    timeRangeLowLastTime(val, type) {
      let newVal
            // 服务定制中，判断之后的一个服务定制开始时间
      if (type === '中') {
        let arrTimes = []
        this.customList.map(item => {
          arrTimes.push(item.openStartTime)
          arrTimes.push(item.openEndTime)
        })
        arrTimes = Array.from(new Set(arrTimes))
        for (let i = 0; i < arrTimes.length; i++) {
          const item = arrTimes[i]
          if (item > val && (item - val <= 2)) {
            newVal = item
            return newVal
          } else {
            newVal = val + SliderUnit * 4
            if (newVal > 24) {
              return 24
            }
          }
        }
      }

      newVal = val + SliderUnit * 4
      if (newVal > 24) {
        return 24
      }
      return newVal
    },
    cusTime() { // 服务定制时间及预约时段
      let copyResData = JSON.parse(JSON.stringify(resData));
      (copyResData.data || []).forEach(item => {
        item.date = dateToDate(item.date)
        this.customList = []
        if (item.date === this.date) {
          const spaceCustomContentList = item.spaceCustomContentList || [] // 服务定制
          spaceCustomContentList.map(cusItem => {
            this.hasCus = true
            cusItem.startTime = cusItem.startTime ? cusItem.startTime : '000000'
            cusItem.endTime = cusItem.endTime ? cusItem.endTime : '000000'

            const obj = {
              start: cusItem.startTime,
              end: cusItem.endTime
            }
            this.customTimeInit.push(obj)

            const start = startimeToUnitTime(cusItem.startTime)
            const end = endtimeToUnitTime(cusItem.endTime)

            const cusObj = {
              openStartTime: formateTimeToValue(start),
              openEndTime: formateTimeToValue(end) - 0.5
            }
            this.customList.push(cusObj) // 服务定制时间组
          })

          item.customSceneList && item.customSceneList.find(item => {
            item.startDate = dateToDate(item.startDate)
            item.endDate = dateToDate(item.endDate)
          })
          this.currentCheckedItem = item.customSceneList || []
        }
      })
      if (!this.hasCus) { // 没有服务定制  当前值保持数组不为空
        const cusObj = {
          openStartTime: '',
          openEndTime: ''
        }
        this.customList.push(cusObj) // 服务定制时间组
      }
      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 && this.date === getNowDate()) {
          workType = 2
        } else {
          workType = 0
        }
      }
      let historyBookList = [] // 历史选择的时段
      let equipArr = []
      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 sceneEquipList = item.sceneEquipList || []
          equipArr = [...equipArr, ...sceneEquipList]
        }
      })
      const date = formateDateValue(this.date)
      let newBooklist = {
        startDate: date,
        endDate: date,
        startTime: formateTimeValue(this.period.start),
        endTime: formateTimeValue(this.period.end),
        sceneEquipList: equipArr,
        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 }
    },
        // 删除的时间 于服务定制的关系
    checkeDeleteCustom(newBookStart, newBookEnd, paramsArr) {
      let deleStart = newBookStart
      let deleEnd = newBookEnd
      this.customTimeInit.map(item => {
        if (deleStart < item.end && deleStart > item.start) {
          deleStart = item.end
        }
        if (deleEnd > item.start && deleEnd < item.end) {
          deleEnd = item.start
        }
      })
      let nowTime = moment().format('HHmmss')
            // 当日 当前时间 删除数据 表示 我要离开
      paramsArr.map(item => {
         // 0 为预约 2为我来了，设备参数不能传id
        if (item.type === 0 || item.type === 2) {
          console.log(item, item.sceneEquipList)
          let arr = item.sceneEquipList || []
          for (let i = 0; i < arr.length; i++) {
            const eq = arr[i]
            if (eq.id) {
              delete eq.id
            }
          }
        }
        if (nowTime >= deleStart && nowTime <= deleEnd) {
          if (item.endDate != getNowDate()) return
          if (item.startTime >= deleStart && item.startTime <= deleEnd) {
            item.type = 3
            item.endTimeReal = nowTime
          }
          if (item.endTime >= deleStart && item.endTime <= deleEnd) {
            item.type = 3
            item.endTimeReal = nowTime
          }
        }
      })

      return { deleStart, deleEnd, paramsArr }
    },
    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 params = []
      arr.map(item => {
        if (item.startTime < item.endTime) {
          params.push(item)
        }
      })
      let { deleStart, deleEnd, paramsArr } = this.checkeDeleteCustom(newBookStart, newBookEnd, params)
      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 */
    },
    setParamsEquiplist(historyEquips) {
      const arr = this.$refs.refBookEquip.equipData
      let res = []
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        item.eqlist.map(eq => {
          for (let j = 0; j < this.equipConfig.length; j++) {
            const cf = this.equipConfig[j]
                        // 设备需要开启 且是受控状态
            if (eq.status && eq.id === cf.equipmentId && cf.isExeSpaceTime) {
              res.push({
                type: eq.equipmentCategory,
                objectId: eq.id,
                projectId: eq.projectId
              })
            }
          }
        })
      }
      let copyRes = JSON.parse(JSON.stringify(res))
            // 历史数据设备 推入到当前需要的
      for (let i = 0; i < historyEquips.length; i++) {
        const ele = historyEquips[i]
        let searchFlag = false
        for (let j = 0; j < copyRes.length; j++) {
          const jele = copyRes[j]
          if (ele.objectId !== jele.objectId) {
            searchFlag = true
          } else {
            searchFlag = false
          }
        }
        if (searchFlag) {
          delete ele.id
          delete ele.sceneId
          res.push(ele)
        }
      }
      return res
    },
        // 提交的使用时间和服务定制的关系
    checkNowCustomTime(newBooklist) {
      const serNewBookList = JSON.parse(JSON.stringify(newBooklist))
      this.customTimeInit.map(item => {
        if (newBooklist.startTime > item.start && newBooklist.startTime < item.end) {
          serNewBookList.startTime = item.end
        }
        if (newBooklist.endTime > item.start && newBooklist.endTime < item.end) {
          serNewBookList.endTime = item.start
        }
      })
      return serNewBookList
    },
    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
        }
      }
      newBooklist = this.checkNowCustomTime(newBooklist)
      newBooklist.sceneEquipList = this.setParamsEquiplist(newBooklist.sceneEquipList)
      saveBatchCustomScene({ historyBookList, newBooklist })
                .then(res => {
                  clearTimeout(timer)
                  timer = null
                  this.$emit('component-set-countDown')
                  this.$emit('component-close-visible', false)
                })
                .catch(() => {
                  clearTimeout(timer)
                  timer = null
                  this.$emit('component-set-countDown')
                  this.$emit('component-close-visible', false)
                })
    },
    setDefaultPeriod() {    // 默认选中时间
      let nowHour = getNowTime().juggeValue
      if (this.customList.length) { // 有服务定制  服务定制向后两个小时
        for (let i = 0; i < this.customList.length; i++) {
          const item = this.customList[i]

          const start = item.openStartTime
          const end = item.openEndTime
          const realOpenEndTime = end + 0.5
          if (nowHour >= start && nowHour < realOpenEndTime) { // 服务定制中
            this.period = {
              start: realOpenEndTime,
              end: this.timeRangeLowLastTime(realOpenEndTime, '中'),
              from: 'outer'
            }
            break
          }
          if (nowHour >= realOpenEndTime || nowHour === start) { // 服务定制后
            this.period = {
              start: nowHour,
              end: this.timeRangeLowLastTime(nowHour),
              from: 'outer'
            }
          }
          if (nowHour < start) { // 服务定制前
            if ((start - nowHour) >= 2) {
              this.period = {
                start: nowHour,
                end: this.timeRangeLowLastTime(nowHour),
                from: 'outer'
              }
            } else {
              this.period = {
                start: nowHour,
                end: nowHour + (start - nowHour),
                from: 'outer'
              }
            }
            break
          }
        }
      } else { // 没有服务定制
        this.period = {
          start: nowHour,
          end: this.timeRangeLowLastTime(nowHour),
          from: 'outer'
        }
      }
    },
    selectedPeriod({ start, end, hasUuBooked }) {
      this.period = { start, end, hasUuBooked }
    },
    judgeCanSelectedEnd(canBooked) {
      this.canBooked = canBooked
    },
    changeSelectedData(date) {  // 选择日期
      this.selectedDate(date)
      this.hasCus = false
      this.cusTime()
    },
    selectedDate(date) {
      this.date = date
      this.disabledPast = date == getNowDate()
    },
    getServeTime(date) {
      this.canBooked = false
    }
  }
})
</script>




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