<template>
  <div class="prohibit" :style="{ background: listData.length == 0 ? '#fff ' : '#f2f4f5' }">
    <van-nav-bar title="上课禁止时段" left-arrow :border="true" @click-left="onNavBack">
      <van-icon name="plus" slot="right" id="plus-icon" @click="onAddClick" />
    </van-nav-bar>
    <div class="prohibit-list-container" v-show="isShowPage">
      <div class="con" v-show="listData.length > 0">
        <!-- 内容 -->
        <van-cell v-for="(item, index) in listData" :key="`prohibit_${index}`">
          <van-swipe-cell>
            <div class="area">
              <div :class="[{ active: item.Active }, 'left']" @click="listClick(item)">
                <div class="title">{{ item.StartTime }}-{{ item.EndTime }}</div>
                <div class="date">
                  <span v-for="(data, index) in formatWeekdays(item.Weekdays)" :key="`date_${index}`">{{ data }}</span>
                  <span>
                    <van-icon
                      name="lock"
                      v-if="!item.Editable && item.RecordType === prohibitModel.recordType.manufactor"
                    />
                  </span>
                </div>
              </div>
              <van-switch :value="item.Active == 1" @input="onInput($event, item.Id)" :active-color="$green" />
            </div>
            <template slot="right">
              <van-button square type="danger" text="删除" @click="onClose(item)" />
            </template>
          </van-swipe-cell>
        </van-cell>
        <div class="watchTips" v-show="deviceType == '2'">
          <p>课堂免打扰时段不能使用设备，也不能呼入电话及无响铃</p>
        </div>
      </div>

      <div class="noData_img" v-show="listData.length == 0">
        <div v-if="deviceType == '1'" class="watchTips">您还没有给定位卡设置禁用时段，快去添加吧~</div>
        <div v-else class="watchTips">
          <p>请点击右上角“+”号添加课堂免打扰时段。</p>
          <p>课堂免打扰时段不能使用设备，也不能呼入电话及无响铃</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
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 {
  data() {
    return {
      switchShow: false,
      listData: [],
      serialNo: '',
      prohibitModel: ProhibitModel,
      deviceType: this.$store.getters.deviceType,
      isShowPage: false
    };
  },
  methods: {
    // 返回
    onNavBack() {
      this.$router.push({ name: 'Myself' });
    },
    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();
          console.log(res.data);
          let item = res.data;
          let listData = [];
          let cmdData = item.items.filter(val => val.cmdCode == DeviceCommandModel.prohibition);
          let parseValue = JSON.parse(cmdData[0].cmdValue);
          parseValue.Items.forEach(val => {
            listData.push(val);
          });
          this.listData = listData;
          this.isShowPage = true;
        })
        .catch(() => {
          ToastService.clear();
          this.isShowPage = true;
        })
        .finally(() => {
          ToastService.clear();
        });
    },
    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 => {
          let item = res.data;
          let status = item.stateCode == 1 ? '操作成功' : '保存失败，请重新设置';
          ToastService.clear();
          if (item.stateCode == 1) {
            ToastService.success({ message: status });
          } else {
            DialogService.confirm({ title: '操作失败，请重新设置' });
          }
        })
        .catch(() => {
          ToastService.clear();
        })
        .finally(() => this.getCommandList());
    },
    onAddClick() {
      this.$router.push({
        name: 'setupProhibitPeriod',
        query: { title: '添加上课禁用时段', code: this.$route.query.code }
      });
    },
    switchClick() {
      this.switchShow = !this.switchShow;
    },
    onInput(checked, id) {
      this.listData.map(val => {
        if (val.Id == id) {
          val.Active = checked ? 1 : 0;
        }
        return val;
      });
      console.log(this.listData);
      let cmdCode = DeviceCommandModel.prohibition;
      let cmdValue = {
        Items: this.listData
      };
      this.sendCommand(cmdCode, JSON.stringify(cmdValue));
    },
    listClick(item) {
      if (item.RecordType !== ProhibitModel.recordType.manufactor) {
        this.$router.push({
          name: 'setupProhibitPeriod',
          query: { title: '设置时段', code: this.$route.query.code, id: item.Id, show: false }
        });
      } else {
        this.tipsOnEditable();
      }
    },
    tipsOnEditable() {
      DialogService.confirm({
        title: '抱歉，该记录不可操作',
        message: '该记录为教师端所设，家长端不可以操作'
      });
    },
    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;
    },
    //滑动单元格
    onClose(item) {
      if (item.RecordType !== ProhibitModel.recordType.manufactor) {
        const req = this.listData.filter(val => val.Id !== item.Id);
        let cmdCode = DeviceCommandModel.prohibition;
        let cmdValue = {
          Items: req
        };
        this.sendCommand(cmdCode, JSON.stringify(cmdValue));
        ToastService.success({ message: '操作成功' });
      } else {
        this.tipsOnEditable();
      }
    }
  },
  computed: {},
  created() {
    this.getCommandList();
  }
};
</script>
<style lang="scss" scoped>
.prohibit {
  height: 100vh;
  .prohibit-list-container {
    /*  padding: 30px; */
    height: calc(100vh - 160px);
    overflow: scroll;
    .con {
      width: 100%;
      background: #fff;
      margin-bottom: 50px;
      .area {
        padding: 0 30px;
        height: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
    .noData_img,
    .watchTips {
      font-size: 32px;
      min-height: 200px;
      padding: 30px;
      @include flexbox(center, center, column, nowrap);
    }
  }
}
</style>
