<template>
  <div class="addFamilyNumber familyNumber replace">
    <div class="management">
      <div class="oh_100vh">
        <div class="top-con">
          <van-nav-bar title="新增亲情号" left-text="返回" :border="true" @click-left="onNavBack">
            <div class="family_save" slot="right" @click="submit">保存</div>
          </van-nav-bar>

          <van-cell-group>
            <van-field
              v-model.trim="nickName"
              maxlength="6"
              label="昵称"
              required
              placeholder="如爸爸，妈妈，必须少于6个汉字"
              input-align="right"
            />
            <van-field
              v-model.trim="phone"
              maxlength="12"
              label="号码"
              required
              oninput="value=value.replace(/\s+/g,'')"
              placeholder="可输入手机，固话，短号"
              input-align="right"
            />
            <van-cell center required>
              <template #title>
                <span class="custom-title">快捷键</span>
              </template>
              <template #extra>
                <div>
                  <van-dropdown-menu>
                    <van-dropdown-item v-model="value1" @change="onDrodownClick" :options="shortKeylist" />
                  </van-dropdown-menu>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
          <div class="tips-container" v-show="isUnicom">
            <div class="inside-tips">
              <p>注：</p>
              <p>1）由于网络因素影响，亲情号码设置后，最长需要等待10分钟后才可拨打。</p>
              <p>
                2）设备最多可设置{{
                  setPhoneNumber
                }}个亲情号码，添加首月无法删除，次月起每月最多允许删除1个亲情号，请慎重操作。
              </p>
            </div>
          </div>
        </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 NotifyService from '../../services/notify-service';
import APICommand from '@/api/command';
export default {
  data() {
    return {
      loading: false,
      nickName: '',
      phone: '',
      checked: false,
      shortcutKey: '',
      listData: [],
      sos: false,
      mbnoneDisabled: false,
      sureFalg: true, // radio 联系方式类型
      /* contactType: "0" */ value1: '',
      shortKeylist: [], //当前可设置的快捷键
      newShortKeyList: ['1', '2', '3', '4', '5'], //对比的快捷键
      familyNameList: [], //亲情号码名字
      familyShortKeyList: [], //亲情号码快捷键
      namePhoneList: [] //名字和亲情号码
    };
  },
  methods: {
    // 点击其他按钮，号码清空
    onClearCornet() {
      this.phone = '';
    },
    onClearMobile() {
      this.phone = '';
    },
    onClearPhone() {
      this.phone = '';
    },
    // 返回
    onNavBack() {
      this.$router.push({ name: 'familyNumber' });
    },
    // 校验联系方式
    checkedContact() {
      switch (this.contactType) {
        case '0':
          // eslint-disable-next-line no-case-declarations
          let reg = /^1[3456789]\d{9}$/;
          if (reg.test(this.phone)) {
            return true;
          } else {
            DialogService.confirm({ title: '请输入正确的号码' });
          }
        // eslint-disable-next-line no-fallthrough
        case '1':
          // eslint-disable-next-line no-case-declarations
          let reg1 = /^(0[0-9]{2,3})([2-9][0-9]{6,7})+([0-9]{1,4})?$/;
          if (reg1.test(this.phone)) {
            return true;
          } else {
            DialogService.confirm({ title: '请输入正确的号码' });
            return false;
          }
        case '2':
          if (this.phone.length <= 6 && this.phone.length >= 2) {
            return true;
          } else {
            DialogService.confirm({
              title: '请输入正确的2-6位短号'
            });
            return false;
          }
        default:
          DialogService.confirm({ title: '未知号码' });
          return false;
      }
    },
    // TODO 设置为亲情号码按钮事件
    checkedClick() {
      if (!this.checked) {
        this.mbnoneDisabled = true;
        this.shortcutKey = '5';
        this.sos = true;
        //TODO:轮询号码列表是有sos号码
        let over = this.listData.find(val => {
          return val.PressKey == 5;
        });
        if (over != null) {
          DialogService.confirm({
            title: '已有sos号码，是否覆盖原sos号码？',
            showCancelButton: true
          })
            .then(() => {
              //TODO:删除原有sos号码
              this.listData = this.listData.filter(val => {
                return val.PressKey != 5;
              });
              this.listData.forEach(val => {
                if (val.SOS == 1) {
                  val.SOS = 0;
                }
              });
            })
            .catch(() => {
              this.checked = false;
              this.mbnoneDisabled = false;
              this.shortcutKey = '';
              this.sos = false;
            });
        }
      } else {
        this.mbnoneDisabled = false;
        this.shortcutKey = '';
        this.sos = false;
      }
    },
    submit() {
      if (!this.sureFalg) {
        ToastService.success({
          message: '保存成功',
          onClose: () => this.onNavBack()
        });
        return;
      }
      // 数字正则
      let numberReg = /^-?\d*\.?\d+$/;
      // 2022 . 6 .29 修改手机正则表达式
      // 固话正则
      // 是否存在空格
      let spaceReg = /(^\s+)|(\s+$)|\s+/g;
      if (this.nickName == '') {
        DialogService.confirm({ title: '昵称不能为空' });
        return;
      }
      if (spaceReg.test(this.phone)) {
        DialogService.confirm({ title: '号码不能有空格,请您检查后重新输入' });
        return;
      }
      if (!numberReg.test(this.phone)) {
        DialogService.confirm({ title: '号码只能是数字,请您重新输入' });
        return;
      }
      if (this.phone.length < 3) {
        DialogService.confirm({ title: '请至少输入3位的短号' });
        return;
      }
      // 2022.7.13 取消正则匹配
      /* if(this.phone.length === 11) {
                if(!mobileReg.test(this.phone)) {
                    DialogService.confirm({ title: "请输入正确的手机号码" });
                    return;
                }
            }
            if(this.phone.length > 11) {
                if(!fixMobileReg.test(this.phone)) {
                    DialogService.confirm({ title: "请输入正确的固话" });
                    return;
                }
            } */
      /* if (!mobileReg.test(Number(phoneNumber))) {
                DialogService.confirm({ title: "请输入正确的手机号码" });
                return;
            } */
      if (this.phone == '') {
        DialogService.confirm({ title: '号码不能为空' });
        return;
      }
      /* 取消校验方式 */
      /*  if (!this.checkedContact()) {
                    return;
                } */
      // 找出重复的用户名
      let repetition = this.namePhoneList.filter(val => {
        return val.relationship == this.nickName;
      });
      //  找出重复的号码
      let exists = this.namePhoneList.filter(val => {
        return val.phone == this.phone;
      });

      // 判断重复的用户名
      if (typeof repetition != 'undefined' && repetition.length > 0 && !this.sos) {
        if (repetition.length == 1) {
          let existNum = repetition[0];
          if (existNum.PressKey !== '5') {
            DialogService.confirm({ title: '用户名已存在' });
            return;
          }
        } else {
          DialogService.confirm({ title: '用户名已存在' });
          return;
        }
      }
      //TODO:判断重复号码 允许仅一个号码与sos号码相同
      if (typeof exists != 'undefined' && exists.length > 0 && !this.sos) {
        if (exists.length == 1) {
          let existNum = exists[0];
          if (existNum.PressKey !== '5') {
            DialogService.confirm({ title: '电话号码已存在' });
            return;
          }
        } else {
          DialogService.confirm({ title: '电话号码已存在' });
          return;
        }
      }
      this.sure();
    },
    sure() {
      //  保存中的弹窗
      this.listData.push({
        relationship: this.nickName,
        phone: this.phone.replace(/\s+/g, ''),
        SOS: this.checked ? 1 : 0,
        PressKey: this.shortcutKey,
        AppType: FamilyNumberModel.appType.parentWeb,
        Editable: FamilyNumberModel.editable.parentWeb,
        Level: FamilyNumberModel.level,
        CallOut: FamilyNumberModel.callOut,
        Outtime: FamilyNumberModel.outtime,
        Incoming: FamilyNumberModel.inComing,
        IncomingTime: FamilyNumberModel.incomingTime
      });
      let cmdCode = DeviceCommandModel.familyNum;
      let cmdValue = { WhiteList: this.listData };

      this.sendCommand(cmdCode, JSON.stringify(cmdValue));
    },
    inputChange() {
      this.shortcutKey = this.shortcutKey.replace(/[^\d]/g, '');
    },
    getCommandList() {
      ToastService.loading();
      /* let url = `/api/Command/CommandList`;
                let jsonData = { deviceId: this.$store.getters.deviceId }; */
      let _this = this;
      /* _this.$axios
                    .post(url, jsonData) */
      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);
              });
              // 获取白名单列表相关数据
              _this.listData = listData; // 接口调用的数组
              _this.namePhoneList = listData; //专门来筛选名字和亲情号码的数组
              _this.setFamilyNum();
              _this.setFamilyShortKey();
            }
          }
        })
        .catch(err => console.log(err))
        .finally(() => ToastService.clear());
    },
    setFamilyNum() {
      this.$store.commit('familyNameList', '');
      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() {
      this.$store.commit('familyShortKeyList', '');
      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);
          });
      }
    },
    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.sureFalg = false;
      this.loading = true;
      /* 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 => {
          ToastService.clear();
          let item = res.data;
          if (item.stateCode == 1) {
            ToastService.success({
              message: item.message,
              onClose: () => this.onNavBack()
            });
          } else {
            DialogService.confirm({
              title: '保存失败',
              message: item.message
            });
            // 失败初始化筛选名字和亲情号码的数组,防止在此判断重复
            this.namePhoneList = [];
            ToastService.clear();
          }
        })
        .catch(() => {})
        .finally(() => {
          this.sureFalg = true;
          this.loading = false;
          ToastService.clear();
        });
    },
    // 选择下拉框的值
    onDrodownClick(value) {
      console.log('选择了', value);
      if (value === '5') {
        this.shortcutKey = '5';
        this.sos = true;
        this.checked = true;
      } else {
        this.shortcutKey = value;
        this.sos = false;
        this.checked = false;
      }
    },
    // 初始化快捷键数组
    initShortKey() {
      ToastService.loading();
      let familyShortKeyList = this.familyShortKeyList;
      if (typeof familyShortKeyList === 'string') {
        familyShortKeyList = Array.from(familyShortKeyList.replace(/,/g, ''));
      }
      let newShorList = this.findDiffShortKey(this.newShortKeyList, familyShortKeyList);
      this.shortKeylist = newShorList
        .map(s => {
          let text = s;
          if (s === '5') {
            text = 'sos';
          }
          return {
            text: text,
            value: s
          };
        })
        .filter(s => {
          return s.text != '';
        });
      let defaultObj = {
        text: '无',
        value: ''
      };
      this.shortKeylist.push(defaultObj);
      this.value1 = this.shortKeylist[0].value;
      this.shortcutKey = this.value1;
    },
    // 找出两个数组中未设置的快捷键
    findDiffShortKey(arr1, arr2) {
      return arr1.concat(arr2).filter((v, i, arr) => {
        return arr.indexOf(v) === arr.lastIndexOf(v);
      });
    }
  },
  computed: {
    theNextClass() {
      let reg = /^1[3456789]\d{9}$/;
      let mobileReg = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
      if (this.nickName == '' || this.phone == '') {
        return false;
      }

      if (!reg.test(this.phone)) {
        if (!mobileReg.test(this.phone)) {
          return false;
        }
      }

      return true;
    },
    // 获取物联网卡号码，非空为物联网卡，空则为普通电话卡，不显示提示
    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;
    }
  },
  watch: {
    shortcutKey(key) {
      /* if (!this.sos && key > 4) {
                    DialogService.confirm({
                        title: "快捷键1-4的数字",
                    })
                        .then(() => {
                            this.shortcutKey = "";
                        });
                } */
      // 当快捷键等于0的时候
      if (!this.sos && key === '0') {
        DialogService.confirm({
          title: '快捷键1-4的数字'
        }).then(() => {
          this.shortcutKey = '';
        });
      }
      if (key === '5') {
        this.sos = true;
        this.checked = true;
      }
      if (key) {
        this.listData.forEach(val => {
          if (key == val.PressKey && key < 5) {
            DialogService.confirm({
              title: '快捷键已经存在,请另外设置其它的快捷健'
            }).then(() => {
              this.sos = false;
              this.shortcutKey = '';
            });
          }
        });
      }
    },
    nickName() {
      if (this.nickName.length >= 6) {
        NotifyService.notify({
          type: 'warning',
          message: '昵称最长可设置6位'
        });
      }
    },
    phone() {
      if (this.phone.length > 11) {
        return (this.phone = this.phone.replace(/\s+/g, ''));
      }
    }
  },
  created() {
    this.getCommandList();
    setTimeout(() => {
      this.initShortKey();
      ToastService.clear();
    }, 1000);
  }
};
</script>

<style lang="scss" scoped>
.family_save {
  width: 80px;
  line-height: 40px;
  background: #1989fa;
  color: #fff;
  font-size: 30px;
}
.tips-container {
  padding: 20px;
  .inside-tips {
    padding: 40px;
    border-radius: 30px;
    border: 1px solid green;
    p {
      font-size: 32px;
    }
  }
}
</style>
