<style lang="less">
.work-overtime.disabled .tip-text {
  color: rgba(6, 6, 61, 0.3);
}

.work-overtime .btn-off-work {
  width: 128rpx;
  height: 40rpx;
  background: rgba(13, 13, 61, 0.86);
  border-radius: 4rpx;
  font-size: 24rpx;
  line-height: 40rpx;
  text-align: center;
  color: #ffffff;
  margin-right: 18rpx;
}

.work-overtime .main-tip {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.work-overtime .icon-clock {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
  display: block;
}

.work-overtime .tip-text {
  font-size: 28rpx;
  line-height: 28rpx;
  color: rgba(13, 13, 61, 0.86);
  margin-right: 8rpx;
}

.work-overtime .icon-arrow {
  width: 32rpx;
  height: 32rpx;
  display: block;
}

.work-overtime .choose-work-overtime-panel {
  position: fixed;
  bottom: 0;
  height: 820rpx;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 2;
}

.work-overtime .choose-work-overtime-panel .top {
  height: 200rpx;
  padding-left: 46rpx;
  padding-top: 46rpx;
  text-align: left;
  box-sizing: border-box;
  background-color: #f7f7fa;
}

.work-overtime .choose-work-overtime-panel .tip-text {
  font-size: 28rpx;
  line-height: 28rpx;
  color: rgba(9, 9, 61, 0.45);
  margin-bottom: 38rpx;
}

.work-overtime .choose-work-overtime-panel .time-text {
  font-size: 40rpx;
  line-height: 40rpx;
  color: rgba(13, 13, 61, 0.86);
}

.work-overtime .choose-work-overtime-panel .picker {
  height: 432rpx;
  width: 100%;
  overflow: hidden;
  .picker-contanier {
    height: 100%;
  }
}

.work-overtime .choose-work-overtime-panel .bottom {
  height: 188rpx;
  position: relative;
}

.work-overtime .choose-work-overtime-panel .cancle-btn {
  font-size: 32rpx;
  line-height: 44rpx;
  color: #c4c4c4;
  position: absolute;
  top: 38rpx;
  left: 48rpx;
}

.work-overtime .choose-work-overtime-panel .confirm-btn {
  width: 264rpx;
  height: 100rpx;
  background: #ffda1a;
  box-shadow: 0px 8rpx 12rpx rgba(0, 0, 0, 0.07);
  border-radius: 60rpx;
  font-weight: 500;
  font-size: 28rpx;
  line-height: 100rpx;
  text-align: center;
  color: #000000;
  margin: 10rpx auto 0;
}

.work-overtime .picker-row-item {
  font-size: 46rpx;
  line-height: 56rpx;
  text-align: center;
  color: #232326;
}
</style>

<template>
  <div class="work-overtime" v-if="canset">
    <div class="main-tip" v-on:click="showPanel">
      <div class="btn-off-work" v-if="showWorkOff" v-on:click.stop="workOff">提前关闭</div>
      <div class="tip-text">{{tipText}}</div>
      <image
        mode="scaleToFill"
        class="icon-arrow"
        src="{{h5StaticPath}}icon_arrow-right-weight-gray.svg"
      />
    </div>
    <div class="choose-work-overtime-panel" v-if="show" v-on:touchmove.stop="stopPragtion">
      <div class="top">
        <div class="tip-text">空间设备运行时间</div>
        <div class="time-text">{{pickerTipText}}</div>
      </div>
      <div class="picker">
        <picker-view :value="value" bindchange="changeServerTime" class="picker-contanier">
          <picker-view-column>
            <div
              class="picker-row-item"
              v-for="(item,index) in startList"
              :key="index"
            >{{item.label}}</div>
          </picker-view-column>
          <picker-view-column>
            <div
              class="picker-row-item"
              v-for="(itemName,index) in endList"
              :key="index"
            >{{itemName.label}}</div>
          </picker-view-column>
        </picker-view>
      </div>
      <div class="bottom">
        <div class="cancle-btn" v-on:click="doCancel">取消</div>
        <div class="confirm-btn" v-on:click="doConfirm">确定</div>
      </div>
    </div>
  </div>
</template>

<script>
import wepy from '@wepy/core';
import config from '@/config';
import {
  getCustomServerTimeHttp,
  saveCustomServerTimeHttp
} from '@/packagesEnv/api/intelligentControl';
import utils from '@/common/utils';
let h5StaticPath = config.h5StaticPath + '/page-intelligent-control/';

const LimitTime = 8;

wepy.component({
  data: {
    h5StaticPath: h5StaticPath,
    hasNocus: false,
    canset: true,
    showWorkOff: false,
    value: [0, 0],
    show: false,
    startList: [],
    endList: [],
    record: {},
    tipText: '',
    pickerTipText: ''
  },
  props: {
    spaceId: String
  },
  // created() {
  //   this.getTimeInfo();
  // },
  watch: {
    spaceId: function(newValue, oldValue) {
      if (newValue !== oldValue && newValue) {
        this.reset();
        this.getTimeInfo();
      }
    }
  },
  didUpdate() {},
  didUnmount() {},
  methods: {
    reset() {
      this.hasNocus = false;
      this.canset = true;
      this.showWorkOff = false;
      this.show = false;
    },
    getTimeInfo() {
      getCustomServerTimeHttp(this.spaceId).then(res => {
        let result = res.content || {};
        this.record = result;
        this.canset = result.isOpen;
        let nowTimeValue = getNowTimeValue();
        if (nowTimeValue < LimitTime) {
          // 8点前的逻辑
          this.showBeforeLimit(result);
        } else {
          // 8点后的多级
          this.judgeShowWorkOff(result.cusEndTime, result.endTime);

          if (!result.cusStartTime && !result.cusEndTime) {
            // 没有服务时间且没有加班时间
            if (!result.startTime && !result.endTime) {
              this.tipConfigCusTime();
            } else {
              // 没有有服务时间有加班时间
              this.showNoCusWithOverwork(result.endTime);
            }
          } else {
            // 有定制时间的时候
            this.showWithCus(result);
          }
        }
      });
    },
    showPanel() {
      this.show = true;
    },
    changeServerTime(e) {
      let value = e.$wx.detail.value;
      let { startList, endList } = this;
      let pickerTipText = `${startList[value[0]].label}-${
        endList[value[1]].label
      }`;
      if (endList[value[1]].label == '通宵') {
        pickerTipText = '设备将通宵运行';
      }
      this.pickerTipText = pickerTipText;
      this.value = [...value];
    },
    doConfirm() {
      let endIndex = this.value[1] == -1 ? 0 : this.value[1];
      let start = formatTimeStrToParamstr(this.startList[this.value[0]].value);
      let end = formatTimeStrToParamstr(this.endList[endIndex].value);

      let data = {
        objectId: this.spaceId // 空间ID
      };
      if (!this.record.cusEndTime && !this.record.cusStartTime) {
        data = {
          ...data,
          startTime: start, // 加班的开始时间
          endTime: end
        };
      } else {
        if (this.record.cusEndTime == end) {
          data = {
            ...data,
            cusEndTime: this.record.cusEndTime,
            cusStartTime: this.record.cusStartTime,
            startTime: null
          };
        } else {
          data = {
            ...data,
            cusEndTime: this.record.cusEndTime,
            cusStartTime: this.record.cusStartTime,
            startTime: this.record.cusEndTime, // 加班的开始时间，时分秒
            endTime: end // 加班的结束时间
          };
        }
      }

      saveCustomServerTimeHttp(data).then(
        res => {
          this.closePanel();
          this.getTimeInfo();
        },
        res => {
          wx.showToast({
            title: res.message,
            duration: 1000,
            icon: 'none'
          });
        }
      );
    },
    workOff() {
      saveCustomServerTimeHttp({
        objectId: this.spaceId, // 空间ID
        type: 3
      }).then(
        reuslt => {
          if (reuslt.result === 'success') {
            this.getTimeInfo();
            wx.showToast({
              title: '操作成功，将为您关闭空间内的设备',
              duration: 3000,
              icon: 'none'
            });
          } else {
            wx.showToast({
              title: reuslt.message,
              duration: 3000,
              icon: 'none'
            });
          }
          this.showWorkOff = false;
        },
        res => {
          wx.showToast({
            title: reuslt.message,
            duration: 3000,
            icon: 'none'
          });
        }
      );
    },
    doCancel() {
      // todo 重新拉取数据设置为更改前的数据
      this.getTimeInfo();
      this.closePanel();
    },
    closePanel() {
      this.show = false;
    },
    stopPragtion() {},
    tipConfigCusTime() {
      let { startList, endList } = this.generatListByNow();
      this.tipText = '配置设备运行时间';
      this.pickerTipText = startList[0].label + '-' + endList[0].label;
      this.startList = [...startList];
      this.endList = [...endList];
      this.value = [0, 0];
    },
    generateListByTime(start) {
      let endList = [];
      for (var i = start; i < 24; i++) {
        let time = parseInt(i) + 1;
        time = time < 10 ? '0' + time : time;
        endList.push({
          label: time + ':00',
          value: time
        });
      }
      endList.push({
        label: '通宵',
        value: '通宵'
      });
      return endList;
    },
    generatListByNow() {
      let now = new Date();
      let hour = now.getHours();
      let startList = [
        {
          label: utils.getTwoNum(hour) + ':00',
          value: hour
        }
      ];
      let endList = this.generateListByTime(hour);
      return {
        startList,
        endList
      };
    },
    showNoCusWithOverwork(endTime) {
      let { startList, endList } = this.generatListByNow();
      let tipText = '';
      let endIndex = 0;
      if (endTime === '通宵') {
        tipText = '设备将通宵运行';
        endIndex = endList.length - 1;
      } else {
        let endTimeValue = formatTimeStr(endTime);
        let endTimeValues = endTimeValue.split(':');
        let now = getNowTimeValue();
        let endjuddgeTime = getStrTimeValue(endTimeValue);
        if (now > endjuddgeTime) {
          tipText = `配置设备运行时间`;
          this.showWorkOff = false;
        } else {
          tipText = `设备将于${endTimeValue}关闭`;
          endIndex = endList.findIndex(item => item.value == endTimeValues[0]);
        }
      }

      this.tipText = tipText;
      this.pickerTipTextst = startList[0].label + '-' + endList[endIndex].label;
      this.startList = [...startList];
      this.endList = [...endList];
      this.value = [0, endIndex];
    },
    judgeShowWorkOff(cusendTime, endTime) {
      // 如果没有加班时间，就不展示
      if (!endTime) {
        this.showWorkOff = false;
        return;
      }
      // 如果没有定制时间，有加班时间
      if (!cusendTime && endTime) {
        this.showWorkOff = true;
        return;
      }

      // 如有有加班时间，有定制时间，当前时间在定制结束时间以后，在加班时间以内都可以提前下班
      let showWorkOff = false;
      let nowHour = new Date().getHours();
      let nowMinuts = new Date().getMinutes();
      let nowValue = nowHour + nowMinuts / 60;

      let cusendTimeValues = formatTimeStr(cusendTime).split(':');
      let cusendTimeValue =
        parseInt(cusendTimeValues[0]) + parseInt(cusendTimeValues[1]) / 60;

      // 当前时间大于服务定制时间，小于加班时间
      if (nowValue > cusendTimeValue) {
        if (endTime.indexOf('通宵') !== -1) {
          showWorkOff = true;
        } else {
          let endtimeValues = formatTimeStr(endTime).split(':');
          let endtimeValue =
            parseInt(endtimeValues[0]) + parseInt(endtimeValues[1]) / 60;
          if (nowValue < endtimeValue) {
            showWorkOff = true;
          }
        }
      }
      this.showWorkOff = showWorkOff;
    },

    showBeforeLimit(result) {
      // 如果没有加班时间
      let tipText = '';
      let pickerTipText = '通宵运行';
      let showWorkOff = false;
      // 如果没有加班时间
      if (!result.endTime || !result.startTime) {
        tipText = '设备已关闭';
      } else {
        tipText = '设备将通宵运行';
        showWorkOff = true;
      }
      let nowHour = new Date().getHours();

      this.tipText = tipText;
      this.pickerTipText = pickerTipText;
      this.showWorkOff = showWorkOff;
      this.startList = [
        {
          label: utils.getTwoNum(nowHour) + ':00',
          value: nowHour
        }
      ];
      this.endList = [
        {
          label: '通宵',
          value: 8
        }
      ];
    },
    showWithCus(result) {
      let end = result.endTime || result.cusEndTime;
      let start = result.cusStartTime;
      let now = getNowTimeValue();
      let cusEndTimeStr = formatTimeStr(result.cusEndTime);
      let cusEndTime = getStrTimeValue(cusEndTimeStr);
      let endTimeStr = formatTimeStr(end);
      let startTimeStr = formatTimeStr(start);
      let startTime = getStrTimeValue(startTimeStr);
      let endTime = getStrTimeValue(endTimeStr);
      let startList = [
        {
          label: startTimeStr,
          value: startTime
        }
      ];
      let endList = [];
      let tipText = '';
      let pickerTipText = '';
      let showWorkOff = false;
      endTime =
        endTime == '通宵'
          ? '通宵'
          : endTime > cusEndTime
          ? endTime
          : cusEndTime;
      endTimeStr = getTimeValueStr(endTime);
      let endJuddgeValue = endTime == '通宵' ? 25 : endTime;
      pickerTipText = `${startTimeStr} - ${endTimeStr}`;
      if (now < startTime) {
        // before - 再服务时间开启之前
        tipText = `设备将于${startTimeStr}开启`;
        endList = this.generateListByTime(parseInt(cusEndTime - 1));
      } else if (now < endJuddgeValue) {
        // in-在服务开启到加班或服务结束以前
        if (endTime == '通宵') {
          tipText = `设备将通宵运行`;
          pickerTipText = '通宵运行';
          if (now < cusEndTime) {
            endList = this.generateListByTime(parseInt(cusEndTime - 1));
          } else {
            let list = this.generatListByNow();
            endList = list.endList;
          }
        } else {
          tipText = `设备将于${endTimeStr}关闭`;
          if (now > cusEndTime) {
            let list = this.generatListByNow();
            endList = list.endList;
          } else {
            endList = this.generateListByTime(parseInt(cusEndTime - 1));
          }
        }
      } else {
        // after-服务｜加班结束范围之后
        let list = this.generatListByNow();
        endList = list.endList;
        if (endTime == '通宵') {
          tipText = `设备将通宵运行`;
          pickerTipText = '通宵运行';
        } else {
          tipText = '设备已关闭';
          pickerTipText = `${startTimeStr} - ${endList[0].label}`;
        }
      }

      let endIndex = endList.findIndex(item => item.label == endTimeStr);
      this.endIndex = endIndex == -1 ? 0 : endIndex;
      this.tipText = tipText;
      this.pickerTipText = pickerTipText;
      this.endList = endList;
      this.startList = startList;
      this.value = [0, endIndex];
    }
  }
});

function formatTimeStr(str) {
  if (!str) {
    return '';
  }
  if (str.indexOf('通宵') !== -1) {
    return '通宵';
  }
  let hour = str.substr(0, 2);
  let minute = str.substr(2, 2);
  return hour + ':' + minute;
}

function formatTimeStrToParamstr(str) {
  str = str + '';
  if (!str) {
    return '';
  }
  if (str == '通宵') {
    return '通宵';
  }
  let value = str.split('.');
  let hour = utils.getTwoNum(parseInt(value[0]));
  let minutes = '00';
  if (value[1]) {
    minutes = utils.getTwoNum(parseInt(value[1] * 60));
  }
  return [hour, minutes].join('') + '00';
}

function getStrTimeValue(str) {
  if (!str) {
    return '';
  }
  if (str == '通宵') {
    return '通宵';
  }
  let values = str.split(':');
  return parseInt(values[0]) + parseInt(values[1]) / 60;
}

function getNowTimeValue() {
  let now = new Date();
  let hour = parseInt(now.getHours());
  let minuts = parseInt(now.getMinutes());
  return hour + minuts / 60;
}

function getTimeValueStr(time) {
  if (time == '通宵') {
    return '通宵';
  }
  let values = (time + '').split('.');
  let hour = parseInt(values[0]);
  let minuts = 0;
  if (values[1]) {
    minuts = parseFloat('0.' + values[1]) * 60;
  }
  return utils.getTwoNum(hour) + ':' + utils.getTwoNum(minuts);
}
</script>
