/* * @Author: chenjinxu * @Date: 2021-04-15 10:48:22 * @Last Modified by: chenjinxu * @Last Modified time: 2021-05-06
18:55:52 */
<template>
  <div class="period oh_100vh_bgColor">
    <van-nav-bar title="设置闹钟" left-text="返回" @click-left="onNavBack">
      <template #right>
        <div class="setupClock_save" @click="onSubmit">保存</div>
      </template>
    </van-nav-bar>
    <div class="top">
      <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 value-class="week-value" title="重复周期" is-link @click="popupShowClick">
      <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 } from '../../config/models';
import APICommandList from '../../api/command-list';
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',
      popupShow: false,
      checkData: [],
      listData: [],
      repeatStr: '', //重复的数据
      isSaving: false
    };
  },
  computed: {
    checkDataFormat() {
      let data = '';
      if (this.checkData.length > 0) {
        this.checkData.forEach(val => {
          data += val.id;
        });
      } else {
        return '';
      }
      return data;
    },
    isAdd() {
      return this.$own.isNull(this.$route.query.id);
    }
  },
  created() {
    this.getCommandList();
    this.formatObj();
  },
  mounted() {},
  methods: {
    //返回
    onNavBack() {
      this.$router.go(-1);
    },
    // todo 命名
    async getList() {
      ToastService.loading();
      try {
        let result = await APICommandList.getClocks();
        if (result.data.stateCode === 1) {
          this.listData = APICommandList.getCmdValue(result.data.items, DeviceCommandModel.clock);
          const cmdValue = this.updateList();
          let res = await APICommandList.setClocks(cmdValue);
          let item = res.data;
          console.log(item);
          if (res.data.stateCode === 1) {
            // TODO 执行 getList方法时会再执行这个toast导致再执行一次onClose方法
            /*  ToastService.success({
              message: "编辑成功",
              onClose: ()=>this.onNavBack()
            }); */
            ToastService.clear();
          } else {
            DialogService.confirm({ title: '保存失败，请重新设置' });
          }
        }
      } catch (e) {
        /*   console.log(e);
                    this.$toast.clear(); */
      }
      this.isSaving = false;
    },
    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 => {
          let item = res.data;
          let listData = [];
          let cmdData = item.items.filter(val => val.cmdCode == DeviceCommandModel.clock);
          if (this.$own.isNotNull(cmdData)) {
            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;
          } else {
            this.listData = [];
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    //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.$route.query.code,
        cmdCode,
        cmdValue
      }; */
      /* 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 => {
          let item = res.data;
          let status = item.stateCode == 1 ? '保存成功' : '保存失败';
          if (item.stateCode == 1) {
            /*  this.$dialog.confirm({
                                tittle:status,
                                message:status,
                                className: "device_confirm",
                                showCancelButton: false
                            }).then(() => {

                            }); */
            ToastService.success({
              message: status,
              onClose: () => this.onNavBack()
            });
          } else {
            DialogService.confirm({
              title: status
            });
          }
          this.isSaving = false;
        })
        .catch(() => {
          this.isSaving = false;
        });
    },
    //重复周期的是否显示
    popupShowClick() {
      this.popupShow = !this.popupShow;
    },
    //处理周期组件转过来的数据
    handleCheckboxValue(val) {
      this.checkData = val.data;
      this.popupShow = val.flag;
    },
    //保存
    onSubmit() {
      if (this.isSaving) {
        return;
      } else if (this.isAdd && this.listData.length >= 10) {
        DialogService.confirm({ title: '保存失败', message: '闹钟最多可设置10个' });
        return;
      }
      this.isSaving = true;
      let queryId = this.$route.query.id;
      if (queryId) {
        this.listData.forEach(val => {
          if (val.Id == queryId) {
            (val.StartTime = this.startTime), (val.Weekdays = this.checkDataFormat);
          }
        });
      } else {
        this.listData.push({
          StartTime: this.startTime,
          Active: 1,
          Weekdays: this.checkDataFormat
        });
      }

      let cmdCode = DeviceCommandModel.clock; //上课禁用
      let cmdValue = {
        Items: this.listData
      };
      this.sendCommand(cmdCode, JSON.stringify(cmdValue));
    },
    updateList() {
      if (!this.isAdd) {
        this.listData.forEach(val => {
          if (val.Id == this.$route.query.id) {
            val.StartTime = this.startTime;
            val.Weekdays = this.checkDataFormat;
          }
        });
      } else {
        this.listData.push({
          StartTime: this.startTime,
          Active: 1,
          Weekdays: this.checkDataFormat
        });
      }
      return JSON.stringify({ Items: this.listData });
    },

    //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;
      }
    },
    cancel() {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="scss" scoped>
// 保存按钮样式
.van-nav-bar__right {
  .setupClock_save {
    width: 80px;
    line-height: 40px;
    background: #1989fa;
    color: #fff;
  }
}
.week-value {
  display: flex;
  justify-content: flex-end;
  flex: 2;
}
</style>
