<style lang="less" scoped>
.work-scene {
    border-top: 1px solid #c4c4c466;
    // height: 184rpx;
    // padding: 28rpx 40rpx 40rpx 40rpx;
    height: 92px;
    display: flex;
    padding: 0 40rpx;
    justify-content: space-around;
    align-items: center;
}
.off {
    display: flex;
    padding: 26rpx 24rpx;
    text-align: center;
    box-sizing: border-box;
    align-items: center;
    width: 156rpx;
    height: 116rpx;
    background: rgba(159, 183, 205, 0.15);
    border-radius: 32rpx;
    margin-left: 18rpx;
    .text-font {
        padding-left: 16rpx;
        width: 52rpx;
        height: 64rpx;
        height: 64rpx;
        font-family: 'Montserrat';
        font-style: normal;
        font-weight: 500;
        font-size: 26rpx;
        color: #4d5262;
    }
}
.imgSt {
    width: 40rpx;
    height: 40rpx;
}
.book {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 116rpx;
    background: rgba(159, 183, 205, 0.15);
    &.hasWorkTime {
        background:  rgba(61, 203, 204, 0.3);
    }
    border-radius: 16px;
    padding-left: 24rpx;
    .work-box {
        // margin-left: 16rpx;
        display: flex;
        align-items: center;
        // width: 220rpx;
        .fontSi {
            padding-top: 8rpx;
            font-family: 'Montserrat';
            font-style: normal;
            font-weight: 500;
            font-size: 30rpx;
            line-height: 36rpx;
            color: #1f2429;
        }
        .text-font {
            font-family: 'Montserrat';
            font-style: normal;
            font-weight: 500;
            font-size: 24rpx;
            line-height: 30rpx;
            color: #4d5262;
        }
    }

    .book-box {
        margin-right: 8rpx;
        width: 96rpx;
        height: 100rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 9px;
        box-sizing: border-box;
        background: #ffffff;
        box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.1),
            0px 4px 10px rgba(0, 0, 0, 0.07);
        border-radius: 32rpx;
        &.bigWidth {
            width: 196rpx;
        }
        .book-font {
            // width: 52rpx;
            // height: 64rpx;
            font-family: 'PingFang SC';
            font-style: normal;
            font-weight: 400;
            font-size: 26rpx;
            line-height: 32rpx;
            text-align: center;
            color: #000000;
        }
    }
}
</style>
<template>
    <div class="work-scene">
        <div
            class="book"
            :class="{'hasWorkTime': timeText === '工作时间' && hasWorkTime}"
            @click="changeWorkStatus"
        >
            <div
                class="work-box"
                v-if="hasWorkTime"
            >
                <div class="imgSt">
                    <img
                        style="width:100%;height:100%"
                        src="{{h5StaticPath+'icon-work.svg'}}"
                        alt=""
                        lazyload
                    >
                </div>
                <div style="margin-left:20rpx">
                    <div class="text-font">{{timeText}}</div>
                    <div class="fontSi">{{timeRange}}</div>
                </div>
            </div>
            <div
                class="work-box"
                v-else
            >
                <div class="imgSt">
                    <img
                        style="width:100%;height:100%"
                        src="{{h5StaticPath+'icon-work.svg'}}"
                        alt=""
                        lazyload
                    >
                </div>
                <div style="margin-left:20rpx">
                    <div class="text-font">请选择工作时间段</div>
                    <div
                        class="text-font"
                        style="padding-top: 8rpx;"
                    >将自动开启办公服务</div>
                </div>

            </div>
            <div
                class="book-box"
                :class="{'bigWidth':!(isWorkOff &&  !inCusRangeTime)}"
            >
                <div class="book-font">预约时间</div>
            </div>

        </div>

        <div
            class="off"
            v-if="isWorkOff && !inCusRangeTime"
            @click="handleWorkOff"
        >
            <div class="imgSt">
                <img
                    style="width:100%;height:100%"
                    src="{{h5StaticPath+'icon-work-over.svg'}}"
                    alt=""
                    lazyload
                >
            </div>
            <div class="text-font">我要离开</div>
        </div>
    </div>
</template>
<script>

import wepy from '@wepy/core';
import moment from 'moment';
import store from '@/store';
import config from '@/config';
import { mapActions } from '@wepy/x';
import { saveBatchCustomScene } from '@/packagesEnv/api/officehome.js'
import { checkSpaceControl } from '@/packagesEnv/pages/common.js'
function HHmm(time, num) {
  const HH = time.slice(num, num + 2);
  const mm = time.slice(num + 2, num + 4);
  return `${HH}:${mm}`
}
let timer = null;
let isClickTimer = null;
wepy.component({

  props: {
    workDayTime: Object,
    isControl: Boolean // 是否可控
  },
  store,
  data: {
    h5StaticPath: config.h5StaticPath + '/page-officehome/',
    isWorkOff: false, // 到下班时间
    hasWorkTime: true, // 有工作时间
    workTimeList: [], // 工作时间列表
    currentTimeRange: [], // 当前工作区间
    timeRange: '', // 工作时间区间
    timeText: '--', // 工作时间文案
    inCusRangeTime: false // 在服务时间内
  },
  computed: {

  },
  watch: {
    workDayTime(newVal) {
      if (newVal.data) {
        clearInterval(timer);
        timer = null;
        this.getData()
        timer = setInterval(() => {
          this.getData();
        }, 1000 * 10);
      }
    }
  },
  detached() {
    clearInterval(timer);
    timer = null;
  },
  methods: {
    ...mapActions([
      'setCusTime',
      'setIsNowTime'
    ]),

    isHasWorkTime() { // 有工作时间
      let flag = false;
      this.workTimeList.forEach((item, idx) => {
        if (item.length !== 0) {
          flag = true
        }
      })
      if (this.timeRange) { // 有时间段
        flag = true
      }
      return flag
    },
    concatText(today, val) {
      let text = '';
      if (today === val) {
        text = '今日'
      }
      if (Number(val) === (Number(today) + 1)) {
        text = '次日'
      }
      if (Number(val) > (Number(today) + 1)) {
        const weekDay = moment(val).weekday();
        const weekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六' ];
        text = weekArr[weekDay];
      }
      return text
    },
    bookDayText(val, cusFlag) { // 预约显示日期
      if (cusFlag || (this.isWorkOff && !this.inCusRangeTime)) {
        return '工作时间'
      }
      if (!val.length) return ''
      const startDate = val[0].slice(0, 8);
      const endDate = val[1].slice(0, 8);
      const today = moment().format('YYYYMMDD');
      let startText = this.concatText(today, startDate);
      let endText = this.concatText(today, endDate);
      if (startText === endText) {
        return `已预约-${endText}`
      } else {
        return `已预约(${startText}-${endText})`
      }
    },
    showTimeText(val, cusFlag) {  // 显示时间文案
      const nowTime = moment().format('YYYYMMDDHHmmss');
      let nowtimeFlag = false;
      val.forEach((item, idx) => {
        const start = item[0];
        const end = item[1];
        if (nowTime >= end) {
          this.workTimeList.splice(idx, 1, []);  // 已经过去的从列表删除
        }
        if (start <= nowTime && nowTime <= end) { // 当前在这个区间内
          this.timeText = '工作时间'
          this.setIsNowTime(true)
          this.isWorkOff = true; // 过服务定制时间
          this.currentTimeRange = item;
          nowtimeFlag = true;
        }
      })
      if (!this.hasWorkTime) return;
      if (!nowtimeFlag) {
        this.currentTimeRange = this.workTimeList.find(item => item.length !== 0);
      }
      const startTime = HHmm(this.currentTimeRange[0], 8);
      const endTime = HHmm(this.currentTimeRange[1], 8);
      this.timeRange = `${startTime} ~ ${endTime}`
      this.setCusTime({ startTime: startTime, endTime: endTime })
      this.timeText = this.bookDayText(this.currentTimeRange, cusFlag); // 预约显示日期
    },
    arrTrans(num, arr) { // 一维数组转换为二维数组
      const iconsArr = []; // 声明数组
      arr.forEach((item, index) => {
        const page = Math.floor(index / num); // 计算该元素为第几个素组内
        if (!iconsArr[page]) { // 判断是否存在
          iconsArr[page] = [];
        }
        iconsArr[page].push(item);
      });
      const nowDayTime = moment().format('YYYYMMDDHHmmss');
      let resultArr = [];
      iconsArr.find((item, idx) => {
        let itemEnd = item[1];
        if (nowDayTime > itemEnd) {
        } else {
          resultArr.push(item)
        }
      })
      return resultArr;
    },
    getData() {
      this.setIsNowTime(false)
      this.isWorkOff = false;
      let resData = this.workDayTime.data || []
      let timeArr = []; // 时间组
      let cusFlag = false; // 服务定制内
      let cusEle = {};
      this.setCusTime({
        startTime: '',
        endTime: ''
      })
      resData.forEach((ele, eleIdx) => {
        const nowDay = moment().format('YYYYMMDD');
        const nowTime = moment().format('HHmmss');
        this.inCusRangeTime = false;
        if (ele.date === nowDay) { // 是当天且有服务定制
          const list = ele.spaceCustomContentList || [];
          for (let i = 0; i < list.length; i++) {
            const spaceItem = list[i]
            if (spaceItem.startTime && nowTime >= spaceItem.startTime && nowTime < spaceItem.endTime) {
              cusFlag = true;
              cusEle = spaceItem;
              timeArr.push(`${ele.date}${spaceItem.startTime}`);
              timeArr.push(`${ele.date}${spaceItem.endTime}`);
            }
          }
        }
        if (ele.customSceneList) {
          let bookItemArr = ele.customSceneList;
          bookItemArr.forEach((item, idx) => {
            // 审批通过 或者 没有审批条件 时间存入展示列表中
            if (item.approvalStatus === 1 || !item.hasOwnProperty('approvalStatus')) {
              timeArr.push(`${item.startDate}${item.startTime}`);
              timeArr.push(`${item.startDate}${item.endTime}`);
            }
          })
        }
      })
      if (cusFlag) { // 服务定制时间
        this.isWorkOff = false;
        this.inCusRangeTime = true;
        this.hasWorkTime = true;
        this.setIsNowTime(true)
      }

      if (timeArr.length === 0) {  // 没有预约时间
        this.workTimeList = [];
        this.hasWorkTime = false;
        return
      }

      timeArr.sort(); //  排序
      let timeArrCopy = JSON.parse(JSON.stringify(timeArr));
      timeArrCopy.forEach((item, idx) => {
        let date = Number(item.slice(0, 8));
        let time = item.slice(8, 16);
        let nextItem = timeArrCopy[idx + 1] || '';
        let nextDate = Number(nextItem.slice(0, 8));
        let nextTime = nextItem.slice(8, 16);
        if (time === nextTime && nextDate === date) { // 去重
          timeArr.splice(timeArr.findIndex(jtem => jtem === item), 1);
          timeArr.splice(timeArr.findIndex(jtem => jtem === nextItem), 1);
        }
        if (time === '240000' && nextTime === '000000' && (nextDate - 1 === date)) { // 时间段跨天相邻
          timeArr.splice(timeArr.findIndex(jtem => jtem === item), 1);
          timeArr.splice(timeArr.findIndex(jtem => jtem === nextItem), 1);
        }
      })
      let timeArrResult = this.arrTrans(2, timeArr) // 一维数组转换为二维数组
      if (timeArrResult.length === 0) {
        this.hasWorkTime = false;
        return
      }
      this.workTimeList = JSON.parse(JSON.stringify(timeArrResult));
      this.hasWorkTime = this.isHasWorkTime();
      this.showTimeText(timeArrResult, cusFlag);// 显示时间文案
    },
    handleWorkOff() { // 我要离开
      if (!checkSpaceControl(this.isControl)) return;
      if (wx.canIUse('vibrateShort')) {
        wx.vibrateShort();
      } else {
        wx.vibrateLong();
      }
      this.$emit('component-open-sceneShowpop', 'showWorkOff')
      const currentStart = this.currentTimeRange[0];
      const currenEnd = this.currentTimeRange[1];
      let paramsArr = [];
      this.workDayTime.data.forEach((ele, eleIdx) => {
        let bookItemArr = ele.customSceneList || [];
        if (bookItemArr.length > 0) {
          bookItemArr.find(item => {
            const itemStart = `${item.startDate}${item.startTime}`
            const itemEnd = `${item.startDate}${item.endTime}`
            if (currentStart <= itemStart && itemEnd <= currenEnd) {
              item.type = 3
              item.endTimeReal = moment().format('HHmmss');
              paramsArr.push(item);
            }
          })
        }
      })
      saveBatchCustomScene({ 'historyBookList': paramsArr, 'type': 'workOff' }).then(res => {
        this.$emit('component-get-workTimeData');
        clearTimeout(isClickTimer);
      })
    },

    changeWorkStatus() {
      if (!checkSpaceControl(this.isControl)) return;
      this.$emit('component-open-workTimePop', true)
      this.$emit('component-EquipType-workTimePop', 'all');
    }
  }

})
</script>
