<template>
  <div class="period oh_100vh_bgColor">
    <van-nav-bar :title="$route.query.title" left-text="返回" @click-left="onCancel">
      <div class="setupProhibitPeriod_save" @click="onSubmit" slot="right">保存</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"
        :item-height="itemHeight"
        :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"
        :item-height="itemHeight"
        :visible-item-count="3"
      />
    </div>
    <van-cell
      center
      title="重复周期"
      value-class="week-value"
      is-link
      @click="popupShowClick"
      v-show="!$route.query.show"
    >
      <span
        v-show="checkData.length != 0"
        class="text"
        v-for="(item, index) in checkData"
        :key="`check_data_${index}`"
        >{{ item.value.slice(1, 3) }}</span
      >
      <span v-show="checkData.length == 0" class="text">至少选一个周期</span>
    </van-cell>

    <week :popupShow="popupShow" :checkValue="checkData" @emitCheckboxValue="handleCheckboxValue" />
  </div>
</template>

<script>
import week from './week';
import { DeviceCommandModel, ProhibitModel } from '../../config/models';
import DialogService from '../../services/dialog-service';
import ToastService from '../../services/toast-service';
import APICommand from '@/api/command';
export default {
  components: { week },
  data() {
    return {
      itemHeight: Number(((document.body.clientWidth / 750) * 98).toFixed()),
      startTime: '08:30',
      endTime: '09:10',
      startShow: false,
      endShow: false,
      popupShow: false,
      pickerValue: '',
      checkData: [],
      listData: [],
      repeatStr: '', //重复的数据
      isSaving: false
    };
  },
  methods: {
    //返回
    onNavBack() {
      this.$router.go(-1);
    },
    getCommandList() {
      /* let url = `/api/Command/CommandList`;
        let jsonData = { deviceId: this.$store.getters.deviceId }; */
      /* 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.prohibition);
          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)) {
              this.checkData = [];
              listData.forEach(val => {
                if (val.Id == this.$route.query.id) {
                  this.startTime = val.StartTime;
                  this.endTime = val.EndTime;
                  this.checkData = this.formatObj(val.Weekdays);
                }
              });
            }
            this.listData = listData;
          }
        })
        .catch(err => {
          DialogService.confirm({
            message: err.message ? err.message : '系统繁忙，请稍后再试'
          });
        });
    },
    //post
    sendCommand(cmdCode, cmdValue) {
      ToastService.loading();
      /* let that = this; */
      this.isSaving = true;
      /* 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.clear();
            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;
    },
    //重复周期的是否显示
    popupShowClick() {
      this.popupShow = !this.popupShow;
    },
    //处理周期组件转过来的数据
    handleCheckboxValue(val) {
      this.checkData = val.data;
      this.popupShow = val.flag;
    },
    // 真保存
    onSubmit() {
      if (this.isSaving) return;
      if (this.checkData.length == 0) {
        DialogService.confirm({ title: '设置失败', message: '至少选择一个周期' });
        return;
      }
      // 开始时间不能大于结束时间
      let startConflict = this.startTime.replace(':', '');
      let endConflict = this.endTime.replace(':', '');
      if (Number(startConflict) > Number(endConflict)) {
        DialogService.confirm({ title: '设置失败', message: '开始时间不能大于结束时间' });
        return;
      } else {
        let confirmFlag = true; //是否给予提交flag
        let queryId = this.$route.query.id;
        // 提交值的判断
        if (this.listData.length != 0) {
          for (let i = 0; i < this.listData.length; i++) {
            let val = this.listData[i];
            if (val.Id != queryId) {
              let flag = false; //周期是否有重复flag
              let repeatStr = ''; //重复项
              let checkDataFormat = Array.from(this.checkDataFormat);
              let Weekdays = Array.from(val.Weekdays);
              Weekdays.forEach(wValue => {
                checkDataFormat.forEach(cValue => {
                  if (cValue == wValue) {
                    //证明数组里有相同的周期的
                    flag = true; //有相同周期
                    confirmFlag = false; //不给提交
                    repeatStr += cValue;
                  }
                });
              });
              this.repeatStr = repeatStr; //赋值给this.repeatStr
              if (flag) {
                let start1 = val.StartTime;
                let end1 = val.EndTime;
                let start2 = this.startTime;
                let end2 = this.endTime;
                //判断时间是否有交叉
                if ((start1 >= start2 && start1 < end2) || (start1 < start2 && end1 > start2)) {
                  let message = `${this.formatWeekdays(this.repeatStr)}的时间有交叉，请重新选择`;
                  DialogService.confirm({
                    title: message
                  });
                  confirmFlag = false;
                  return false;
                } else {
                  confirmFlag = true;
                }
              } else {
                confirmFlag = true;
              }
            }
          }
        } else {
          confirmFlag = true;
        }

        console.log(confirmFlag);

        if (confirmFlag) {
          let queryId = this.$route.query.id;
          if (queryId) {
            this.listData.forEach(val => {
              if (val.Id == queryId) {
                (val.StartTime = this.startTime), (val.EndTime = this.endTime), (val.Weekdays = this.checkDataFormat);
              }
            });
          } else {
            this.listData.push({
              StartTime: this.startTime,
              EndTime: this.endTime,
              Active: 1,
              Weekdays: this.checkDataFormat,
              RecordType: ProhibitModel.recordType.parentWeb,
              Editable: ProhibitModel.editable.parentWeb
            });
          }
          let cmdCode = DeviceCommandModel.prohibition; //上课禁用
          let cmdValue = {
            Items: this.listData
          };
          this.sendCommand(cmdCode, JSON.stringify(cmdValue));
        }
      }
    },
    //保存
    // todo Deprecated 弃用
    confirm() {
      if (this.isSaving) return;
      if (this.checkData.length == 0) {
        DialogService.confirm({ title: '至少选一个周期' });
        return;
      } else {
        let confirmFlag = true; //是否给予提交flag
        let queryId = this.$route.query.id;

        // 提交值的判断
        if (this.listData.length != 0) {
          this.listData.forEach(val => {
            if (val.Id != queryId) {
              let flag = false; //周期是否有重复flag
              let repeatStr = ''; //重复项
              let checkDataFormat = Array.from(this.checkDataFormat);
              let Weekdays = Array.from(val.Weekdays);
              Weekdays.forEach(wValue => {
                checkDataFormat.forEach(cValue => {
                  if (cValue == wValue) {
                    //证明数组里有相同的周期的
                    flag = true; //有相同周期
                    confirmFlag = false; //不给提交
                    repeatStr += cValue;
                  }
                });
              });
              this.repeatStr = repeatStr; //赋值给this.repeatStr

              if (flag) {
                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 = `${this.formatWeekdays(this.repeatStr)}的时间有交叉，请重新选择`;
                  DialogService.confirm({ title: message });
                  confirmFlag = false;
                  return false;
                } else {
                  confirmFlag = true;
                }
              } else {
                confirmFlag = true;
              }
            }
          });
        } else {
          confirmFlag = true;
        }
        console.log(confirmFlag);
        if (confirmFlag) {
          let queryId = this.$route.query.id;
          if (queryId) {
            this.listData.forEach(val => {
              if (val.Id == queryId) {
                (val.StartTime = this.startTime), (val.EndTime = this.endTime), (val.Weekdays = this.checkDataFormat);
              }
            });
          } else {
            this.listData.push({
              StartTime: this.startTime,
              EndTime: this.endTime,
              Active: 1,
              Weekdays: this.checkDataFormat
            });
          }

          let cmdCode = DeviceCommandModel.prohibition; //上课禁用
          let cmdValue = {
            Items: this.listData
          };
          this.sendCommand(cmdCode, JSON.stringify(cmdValue));
        }
      }
    },
    removalTime(arr1, arr2) {
      let Weekdays = Array.from(arr1);
      let checkDataFormat = Array.from(arr2);
      Weekdays.forEach(wValue => {
        checkDataFormat.forEach((cValue, cIndex) => {
          if (cValue == wValue) {
            checkDataFormat.splice(cIndex, 1);
          }
        });
      });
      return checkDataFormat;
    },
    //1234567转周几
    formatWeekdays(str) {
      let arr = Array.from(str);
      let newArr = [];
      arr.forEach(val => {
        switch (Number(val)) {
          case 1:
            newArr.push('周一');
            break;
          case 2:
            newArr.push('周二');
            break;
          case 3:
            newArr.push('周三');
            break;
          case 4:
            newArr.push('周四');
            break;
          case 5:
            newArr.push('周五');
            break;
          case 6:
            newArr.push('周六');
            break;
          case 7:
            newArr.push('周日');
            break;
          default:
            newArr = [];
        }
      });
      return newArr;
    },
    formatObj(str) {
      if (str != '' && str != null) {
        let arr = Array.from(str);
        let newArr = [];
        arr.forEach(val => {
          newArr.push({
            value: `每${this.formatWeekdays(val)}`,
            className: 'active',
            id: Number(val)
          });
        });
        return newArr;
      }
    },
    onCancel() {
      this.$router.go(-1);
    }
    //dialog弹窗
    /* dialog(message) {
        this.$dialog.confirm({
          title: message,
          className: "device_confirm",
          showCancelButton: false
        });
      } */
  },
  computed: {
    checkDataFormat() {
      let data = '';
      if (this.checkData.length > 0) {
        this.checkData.forEach(val => {
          data += val.id;
        });
      }
      return data;
    }
  },
  created() {
    this.getCommandList();
    this.formatObj();
  }
};
</script>
<style lang="scss" scoped>
.van-nav-bar__right {
  .setupProhibitPeriod_save {
    width: 80px;
    line-height: 40px;
    background: #1989fa;
    color: #fff;
  }
}
.week-value {
  display: flex;
  justify-content: flex-end;
  flex: 2;
}
</style>
