<template>
  <div class="familyNumber">
    <van-nav-bar title="亲情号码" left-arrow :borvan-tabbarder="true" @click-left="onNavBack">
      <van-icon name="plus" slot="right" @click="onAddNumber" />
    </van-nav-bar>
    <div class="management" v-show="isPageShow">
      <div v-if="listData.length > 0">
        <van-cell v-for="(item, index) in listData" :key="index">
          <van-swipe-cell>
            <div class="conArea">
              <div class="con" @click="conClick(item)">
                <span class="cell">{{ item.relationship }}</span>
                <span>
                  {{ item.phone }}
                  <i>（快捷键 {{ item.PressKey == '' ? '无' : item.PressKey }}）</i>
                  <van-icon name="lock" v-if="!item.Editable && item.AppType == familyNumberModel.appType.manufactor" />
                </span>
              </div>
              <em class="fs30" v-show="!isUnicom"
                ><span>{{ item.SOS == 1 ? 'SOS' : '' }}</span></em
              >
              <!-- 增加物联网卡提示，标识亲情号码是否已经下发同步成功 0,1 同步成功， 2同步中-->
              <em class="fs30" v-show="isUnicom" @click="onClickEm">
                <span>{{ item.SOS == 1 ? 'SOS' : '' }}</span>
                {{ item.status >= 2 ? '同步中' : '' }}
              </em>
            </div>
            <template slot="right">
              <van-button square type="danger" text="删除" @click="onDelete(item)" />
            </template>
          </van-swipe-cell>
        </van-cell>
      </div>
      <div class="newsNotData" v-else>您还没添加亲情号码，赶紧去添加吧~</div>
      <div class="tips-container" v-if="isUnicom">
        <div class="inside-tips">
          <p>注：</p>
          <p>1）由于网络因素影响，亲情号码设置后，最长需要等待10分钟后才可拨打。</p>
          <p>
            2）设备最多可设置{{
              setPhoneNumber
            }}个亲情号码，添加首月无法删除，次月起每月最多允许删除1个亲情号，请慎重操作。
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { DeviceCommandModel, FamilyNumberModel } from '@/config/models';
import DialogService from '@/services/dialog-service';
import ToastService from '@/services/toast-service';
import APICommand from '@/api/command';
export default {
  computed: {
    familyNumberModel() {
      return FamilyNumberModel;
    },
    // 获取物联网卡号码，非空为物联网卡，空则为普通电话卡，不显示提示
    isUnicom() {
      return this.$store.getters.uniPhone !== '';
    },
    // 截取物联网卡前3个数字，148是移动，其它是联通，移动可设5个亲情号码，联通可设10个
    setPhoneNumber() {
      const startNumber = this.$store.getters.uniPhone.slice(0, 3);
      return startNumber === '148' ? 5 : 10;
    }
  },
  data() {
    return {
      listData: [],
      numberMax: 30,
      familyNameList: [], //亲情号码名字
      familyShortKeyList: [], //亲情号码快捷键
      uniWhiteList: [], //第三方物联网卡列表
      // 测试数据，不需要后可删除
      testList: [{ phone: '15111511', status: 2 }],
      isPageShow: false
    };
  },
  methods: {
    // 点击标识
    onClickEm() {
      DialogService.confirm({
        title: '温馨提示',
        message: '请再保存一次号码，进行白名单同步。'
      });
    },
    // 返回
    onNavBack() {
      this.$router.push({ name: 'Myself' });
    },
    onAddNumber() {
      // TODO iot平台
      if (this.listData.length >= this.numberMax) {
        DialogService.confirm({
          title: `亲情号码最多只能设置${this.numberMax}个`
        });
      } else {
        this.$router.push({
          name: 'addFamilyNumber',
          query: { serialNo: this.$store.getters.serialNo }
        });
      }
    },
    conClick(item) {
      if (item.AppType !== FamilyNumberModel.appType.manufactor) {
        this.$router.push({
          name: 'changeFamilyNumber',
          query: {
            id: item.Id,
            serialNo: this.$store.getters.serialNo,
            relationship: item.relationship,
            sos: item.SOS,
            shortKey: item.PressKey
          }
        });
      } else {
        this.tipsOnEditable();
      }
    },
    tipsOnEditable() {
      DialogService.confirm({
        title: '抱歉，该记录不可操作',
        message: '该记录为教师端所设，家长端不可以操作',
        className: 'device_confirm'
      });
    },
    getCommandList() {
      ToastService.loading({ message: '数据加载中...' });
      APICommand.commandList({
        deviceId: this.$store.getters.deviceId
      })
        .then(res => {
          let item = res.data;
          let listData = [];
          if (item.items.length > 0) {
            let cmdData = item.items.filter(val => val.cmdCode == DeviceCommandModel.familyNum);
            if (cmdData.length) {
              let parseValue = JSON.parse(cmdData[0].cmdValue);
              parseValue.WhiteList.forEach(val => {
                listData.push(val);
              });
            }
            console.log('随手精灵亲情号码列表::', listData);
            // 判断是否是小台风物联网卡
            // 1. 是，查询小台风第三方亲情号卡列表，合并相同亲情号码的列表
            if (this.isUnicom) {
              let that = this;
              console.log('小台风白名单列表::', that.uniWhiteList);
              if (that.uniWhiteList.length > 0) {
                // 如果小台风白名单列表有数据，就开始拿一一对应亲情号码的状态赋予到随手精灵亲亲号码的列表
                listData.map(item => {
                  // 先判断小台风白名单列表是否有一一对应的亲亲号码，有那就拿相应的状态，无则同步状态默认给2，即同步中
                  item.status = that.uniWhiteList.find(u => u.phone === item.phone)
                    ? that.uniWhiteList.find(u => u.phone === item.phone).status
                    : 2;
                });
                that.listData = listData;
              } else {
                that.listData = listData;
              }
            } else {
              // 2. 否，照旧
              this.listData = listData;
            }
            ToastService.success({
              message: '加载完成'
            });
            this.isPageShow = true;
          }
        })
        .catch(err => {
          console.log(err);
          this.isPageShow = true;
        })
        .finally(() => ToastService.clear());
    },
    // 如果是小台风物联网卡，获取第三方物联网卡同步的亲情号码列表
    getIotCardWiteList() {
      APICommand.GetIotCardWiteList(this.$store.getters.serialNo).then(res => {
        this.uniWhiteList = res.data.data.items || [];
      });
    },
    onDelete(item) {
      if (item.AppType !== FamilyNumberModel.appType.manufactor) {
        const req = this.listData.filter(val => val.Id !== item.Id);
        let cmdCode = DeviceCommandModel.familyNum;
        let cmdValue = {
          WhiteList: req
        };
        this.sendCommand(cmdCode, JSON.stringify(cmdValue));
        ToastService.success({
          message: '操作成功'
        });
      } else {
        this.tipsOnEditable();
      }
    },
    sendCommand(cmdCode, cmdValue) {
      ToastService.loading({ message: '删除中,请稍后...' });
      /* let url = `/api/Command/SendCommand`;
      let jsonData = {
        deviceId: this.$store.getters.deviceId,
        userId: this.$store.getters.userId,
        serialNo: this.$store.getters.serialNo,
        cmdCode,
        cmdValue
      }; */
      /* this.$axios
        .post(url, jsonData) */
      APICommand.SetIotWhiteList({
        deviceId: this.$store.getters.deviceId,
        userId: this.$store.getters.userId,
        serialNo: this.$store.getters.serialNo,
        cmdCode,
        cmdValue
      })
        .then(res => {
          let item = res.data;
          if (item.stateCode == 1) {
            ToastService.success({
              message: '操作成功'
            });
          } else {
            DialogService.confirm({
              title: '操作失败，请重新设置'
            });
          }
          this.getCommandList();
        })
        .catch(() => {
          ToastService.clear();
        });
    },
    setFamilyNum() {
      let _this = this;
      if (_this.listData == null || this.listData.length == 0) {
        this.$store.commit('familyNameList', '');
      } else {
        _this.listData
          .filter(val => {
            return val.PressKey !== '5';
          })
          .forEach(f => {
            _this.familyNameList.push(f.relationship);
            this.$store.commit('familyNameList', _this.familyNameList);
          });
      }
    },
    // 缓存亲情号码快捷键
    setFamilyShortKey() {
      let _this = this;
      if (_this.listData == null || this.listData.length == 0) {
        this.$store.commit('familyShortKeyList', '');
      } else {
        _this.listData
          .filter(val => {
            return val.PressKey != '';
          })
          .forEach(f => {
            _this.familyShortKeyList.push(f.PressKey);
            this.$store.commit('familyShortKeyList', _this.familyShortKeyList);
          });
      }
    }
  },
  created() {
    let that = this;
    this.getIotCardWiteList();
    setTimeout(() => {
      that.getCommandList();
    }, 300);
  }
};
</script>
<style lang="scss" scoped>
.familyNumber {
  position: relative;
  height: 100vh;
  overflow: hidden;
  font-size: 32px;
  .management {
    position: relative;
    height: calc(100vh - 160px);
    overflow: scroll;
    .newsNotData {
      height: 400px;
      @include flexbox(center, center, column, nowrap);
      font-size: 32px;
    }
    .conArea {
      .con {
        height: 100px;
        @include flexbox(center, flex-start, column, nowrap);
      }
    }
    .tips-container {
      padding: 20px;
      .inside-tips {
        padding: 40px;
        border-radius: 30px;
        border: 1px solid green;
      }
    }
  }
}
</style>
>
