<template>
  <div class="period oh_100vh_bgColor">
    <van-nav-bar title="休眠设置" left-text="返回" @click-left="onNavBack">
      <div class="setupsleep_save" slot="right" @click="onSubmit">保存</div>
    </van-nav-bar>
    <van-cell class title="从" :value="startTime" is-link @click="onStartClick" />
    <div class="top" v-show="startShow">
      <van-datetime-picker
        v-model="startTime"
        type="time"
        :min-hour="0"
        :max-hour="23"
        :show-toolbar="false"
        :visible-item-count="3"
      />
    </div>
    <van-cell title="至" :value="endTime" is-link @click="onEndClick" />
    <div class="top" v-show="endShow">
      <van-datetime-picker
        v-model="endTime"
        type="time"
        :min-hour="0"
        :max-hour="23"
        :show-toolbar="false"
        :visible-item-count="3"
      />
    </div>
  </div>
</template>

<script>
import { DeviceCommandModel } from '../../config/models';
import DialogService from '@/services/dialog-service';
import ToastService from '@/services/toast-service';
import APICommand from '@/api/command';
export default {
  data() {
    return {
      startTime: '08:30',
      endTime: '09:10',
      startShow: false,
      endShow: false,
      checkData: [],
      listData: [],
      repeatStr: '', //重复的数据
      isSaving: false
    };
  },
  methods: {
    //返回
    onNavBack() {
      this.$router.go(-1);
    },
    getCommandList() {
      /* let url = `/api/Command/CommandList`;
        let jsonData = { deviceId: this.$store.getters.deviceId }; */
      ToastService.loading();
      /* this.$axios
          .post(url, jsonData) */
      APICommand.commandList({
        deviceId: this.$store.getters.deviceId
      })
        .then(res => {
          ToastService.clear();
          let item = res.data;
          let listData = [];
          let cmdData = item.items.filter(val => val.cmdCode == DeviceCommandModel.sleep);
          if (this.$own.isNull(cmdData)) {
            this.listData = [];
          } else {
            let parseValue = JSON.parse(cmdData[0].cmdValue);
            parseValue.Items.forEach(val => {
              listData.push(val);
            });
            if (this.$own.isNotNull(this.$route.query.id)) {
              listData.forEach(val => {
                if (val.Id == this.$route.query.id) {
                  this.startTime = val.StartTime;
                  this.endTime = val.EndTime;
                }
              });
            }
            this.listData = listData;
          }
        })
        .catch(err => {
          DialogService.confirm({
            message: err.message ? err.message : '系统繁忙，请稍后再试'
          });
        });
    },
    //post
    sendCommand(cmdCode, cmdValue) {
      ToastService.loading();
      /* let url = `/api/Command/SendCommand`;
        let jsonData = {
          deviceId: this.$store.getters.deviceId,
          userId: this.$store.getters.userId,
          serialNo: this.$store.getters.serialNo,
          cmdCode,
          cmdValue
        }; */
      ToastService.loading();
      /* this.$axios
          .post(url, jsonData) */
      APICommand.sendCommand({
        deviceId: this.$store.getters.deviceId,
        userId: this.$store.getters.userId,
        serialNo: this.$store.getters.serialNo,
        cmdCode,
        cmdValue
      })
        .then(res => {
          ToastService.clear();
          let item = res.data;
          let status = item.stateCode == 1 ? '保存成功' : '保存失败，请重新设置';
          if (item.stateCode == 1) {
            ToastService.success({ message: status, onClose: () => this.onNavBack() });
          } else {
            DialogService.confirm({ title: status });
          }
        })
        .catch(() => {})
        .finally(() => (this.isSaving = false));
    },

    onStartClick() {
      this.startShow = !this.startShow;
      this.endShow = false;
    },

    onEndClick() {
      this.startShow = false;
      this.endShow = !this.endShow;
    },
    //保存
    onSubmit() {
      if (this.isSaving) {
        return;
      }
      let startTimes = this.startTime.replace(':', '');
      let endTimes = this.endTime.replace(':', '');
      if (Number(startTimes) == Number(endTimes)) {
        DialogService.confirm({ title: '设置失败', message: '开始时间不能等于结束时间' });
        return false;
      }

      this.isSaving = true;
      let queryId = this.$route.query.id;
      let confirmFlag = true;

      try {
        this.listData.forEach(val => {
          if (queryId != val.Id) {
            let start1 = '1900/01/01 ' + val.StartTime;
            let end1 = '1900/01/01 ' + val.EndTime;
            let start2 = '1900/01/01 ' + this.startTime;
            let end2 = '1900/01/01 ' + this.endTime;
            //判断时间是否有交叉
            if ((start1 >= start2 && start1 < end2) || (start1 < start2 && end1 > start2)) {
              let message = `时间有交叉，请重新选择`;
              DialogService.confirm({
                title: message
              });
              confirmFlag = false;
              this.isSaving = false;
              throw new Error('抛异常来终止forEach::休眠时间有交叉！');
            }
          }
        });
      } catch (e) {
        console.log(e);
      }

      if (!confirmFlag) {
        return false;
      }

      if (queryId) {
        this.listData.forEach(val => {
          if (val.Id == queryId) {
            val.StartTime = this.startTime;
            val.EndTime = this.endTime;
            val.Weekdays = '1234567';
          }
        });
      } else {
        this.listData.push({
          StartTime: this.startTime,
          EndTime: this.endTime,
          Active: 1,
          Weekdays: '1234567'
        });
      }

      let cmdCode = DeviceCommandModel.sleep; //上课禁用
      let cmdValue = {
        Items: this.listData
      };

      this.sendCommand(cmdCode, JSON.stringify(cmdValue));
    }
    /* cancel() {
        let name = "sleep";
        this.$router.go(-1);
      }, */
    //dialog弹窗
    /* dialog(message) {
        this.$dialog.confirm({
          title: message,
          className: "device_confirm",
          showCancelButton: false
        });
      } */
  },
  computed: {
    contrastTime() {
      let startTime = '1997/06/11 ' + this.startTime;
      let endTime = '1997/06/11 ' + this.endTime;
      return startTime >= endTime;
    }
  },
  created() {
    this.getCommandList();
  }
};
</script>
<style lang="scss">
.van-nav-bar__right {
  .setupsleep_save {
    width: 80px;
    line-height: 40px;
    background: #1989fa;
    color: #fff;
  }
}
</style>
