<template>
  <div class="addFamilyNumber familyNumber replace">
    <div class="management">
      <div class="oh_100vh">
        <div class="top-con">
          <van-nav-bar title="修改亲情号" left-arrow :border="true" @click-left="onNavBack">
            <div class="save" slot="right" @click="onSubmit">保存</div>
          </van-nav-bar>
          <!-- <van-cell>
            <div class="con">
              <span class="cell mbnone">昵称</span>
            </div>
            <input type="text" maxlength="6" placeholder="如爸爸，妈妈，必须少于6个汉字" v-model.trim="nickName" />
          </van-cell> -->
          <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="true">
            <div class="inside-tips">
              <p>注：</p>
              <p>1）由于网络因素影响，亲情号码设置后，最长需要等待10分钟后才可拨打。</p>
              <p>
                2）设备最多可设置{{
                  setPhoneNumber
                }}个亲情号码，添加首月无法删除，次月起每月最多允许删除1个亲情号，请慎重操作。
              </p>
            </div>
          </div>
        </div>

        <!--<div class="submit">
          <a href="javascript: void(0)"
             :class="{next: theNextClass}"
             @click="submit">保存</a>
                </div>-->
      </div>
    </div>
  </div>
</template>

<script>
import { DeviceCommandModel } from '../../config/models';
import ToastService from '../../services/toast-service';
import DialogService from '../../services/dialog-service';
import NotifyService from '../../services/notify-service';
import APICommand from '@/api/command';
export default {
  data() {
    return {
      nickName: '',
      phone: '',
      checked: false,
      shortcutKey: '',
      listData: [],
      sos: false,
      mbnoneDisabled: false,
      sureFalg: true,
      familyId: 0, //路由跳转过来的ID // radio 联系方式类型
      /* contactType: ""  */ value1: '',
      shortKeylist: [], //当前可设置的快捷键
      newShortKeyList: ['1', '2', '3', '4', '5'], //对比的快捷键
      familyNameList: [], //亲情号码名字
      familyShortKeyList: [] //亲情号码快捷键
    };
  },
  methods: {
    // 返回
    onNavBack() {
      this.$router.push({ name: 'familyNumber' });
    },
    // 点击其他按钮，号码清空
    onClearCornet() {
      this.phone = '';
    },
    onClearMobile() {
      this.phone = '';
    },
    onClearPhone() {
      this.phone = '';
    },
    initContactType() {
      if (/* /^(0[0-9]{2,3})([2-9][0-9]{6,7})+([0-9]{1,4})?$/ */ /^1[3456789]\d{9}$/.test(this.phone)) {
        this.contactType = '0';
      } else if (/* /^[1-9][0-9][0-9]$/ */ /^(0[0-9]{2,3})([2-9][0-9]{6,7})+([0-9]{1,4})?$/.test(this.phone)) {
        this.contactType = '1';
      } else if (this.phone.length <= 5 || this.phone.length >= 2) {
        this.contactType = '2';
      }
    },
    // 校验联系方式
    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: '请输入正确的号码' });
            return false;
          }
        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;
      }
    },
    checkedClick() {
      if (!this.checked) {
        this.mbnoneDisabled = true;
        this.shortcutKey = '5';
        this.sos = true;
        let _this = this;
        //TODO:轮询号码列表是否有sos号码(除了自身)
        let over = this.listData.find(val => {
          return val.PressKey == 5 && val.Id != _this.familyId;
        });
        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;
      }
    },
    onSubmit() {
      if (!this.sureFalg) {
        ToastService.loading();
        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 (this.phone == '') {
        DialogService.confirm({ title: '号码不能为空' });
        return;
      }
      /* if (!this.checkedContact()) {
        return;
      } */
      // 找出重复的用户名
      let repetition = this.listData.filter(val => {
        return val.relationship != this.nickName;
      });
      let exists = this.listData.filter(val => {
        return val.phone == this.phone;
      });
      // 判断重复的用户名
      if (repetition !== undefined && repetition.length > 0 && !this.sos) {
        if (repetition.length == 1 || repetition.length >= 2) {
          let nickName = this.nickName;
          let queryName = this.$route.query.relationship;
          let familyNameList = this.$store.getters.familyNameList || [];
          let notQuery = familyNameList.filter(function (item) {
            return item != queryName;
          });
          if (notQuery.includes(queryName) == true) {
            DialogService.confirm({ title: '用户名已存在' });
            return;
          } else if (notQuery.includes(nickName) == true) {
            DialogService.confirm({ title: '用户名已存在' });
            return;
          }
        }
      }
      //    根据是否是sos并且进行了取消sos按键的快捷操作
      if (this.$route.query.sos === 1 && this.shortcutKey !== 5) {
        let nickName = this.nickName;
        let familyNameList = this.$store.getters.familyNameList || [];
        let onlyName = familyNameList.filter(function (item) {
          return item;
        });
        if (this.shortcutKey != 5 && onlyName.includes(nickName) == true) {
          DialogService.confirm({ title: '用户名已存在' });
          return;
        }
      }
      //TODO:判断重复号码
      if (exists !== undefined && exists.length > 0 && !this.sos) {
        if (exists.length <= 2) {
          let existNum = exists[0];
          //TODO:根据familyId识别是否正在修改的亲情号
          if (existNum.Id !== this.familyId && existNum.PressKey !== '5') {
            DialogService.confirm({ title: '电话号码已存在' });
            return;
          }
        } else {
          DialogService.confirm({ title: '电话号码已存在' });
          return;
        }
      }
      // 成功保存触发
      this.sure();
    },
    sure() {
      //TODO:查询已存在的号码
      let _this = this;
      let exist = this.listData.find(val => {
        return _this.familyId === val.Id;
      });
      if (exist !== undefined) {
        exist.relationship = this.nickName;
        exist.phone = this.phone.replace(/\s+/g, '');
        exist.SOS = this.checked ? 1 : 0;
        exist.PressKey = this.shortcutKey;
      }

      let cmdCode = DeviceCommandModel.familyNum;
      let cmdValue = {
        WhiteList: this.listData
      };

      this.sendCommand(cmdCode, JSON.stringify(cmdValue));
    },
    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);
            let parseValue = JSON.parse(cmdData[0].cmdValue);
            parseValue.WhiteList.forEach(val => {
              if (val.Id == _this.$route.query.id) {
                _this.familyId = val.Id;
                _this.nickName = val.relationship;
                _this.phone = val.phone;
                _this.checked = val.SOS == 1;
                _this.shortcutKey = val.PressKey;
                _this.sos = _this.checked;
                _this.mbnoneDisabled = _this.sos;
                _this.initContactType();
              }
              listData.push(val);
            });
            _this.listData = listData;
            _this.setFamilyNum();
            _this.setFamilyShortKey();
          }
        })
        .catch(() => {})
        .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;
      ToastService.loading();
      /*  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;
          this.sureFalg = true;
          if (item.stateCode == 1) {
            ToastService.success({
              message: item.message,
              onClose: () => this.onNavBack()
            });
          } else {
            DialogService.confirm({
              title: '保存失败',
              message: item.message
            });
          }
        })
        .catch(() => {
          this.sureFalg = true;
          ToastService.clear();
        });
    },
    /* dialog(title) {
      this.$dialog.confirm({
        title,
        className: "device_confirm",
        showCancelButton: false
      });
    }, */
    inputChange() {
      this.shortcutKey = this.shortcutKey.replace(/[^\d]/g, '');
    },
    //初始化快捷键数组
    initShortKey() {
      let familyShortKeyList = this.$store.getters.familyShortKeyList;
      let selfKey = this.$route.query.shortKey;
      if (typeof familyShortKeyList === 'string') {
        familyShortKeyList = Array.from(familyShortKeyList.replace(/,/g, ''));
      }
      let keyOtherList = this.newShortKeyList.filter(f => {
        return f != selfKey;
      });
      let newShorList = this.findDiffShortKey(keyOtherList, 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.$route.query.shortKey;
    },
    // 选择下拉框的值
    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;
      }
    },
    // 找出两个数组中未设置的快捷键
    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) {
      let _this = this;
      /* if (!_this.sos && key > 4) {
                DialogService.confirm({
                    title: "快捷键1-4的数字"
                }).then(() => {
                    _this.shortcutKey = "";
                });
            } */
      if (key) {
        _this.listData.forEach(val => {
          //TODO:根据familyId识别是否正在修改的亲情号
          if (key == val.PressKey && key < 5 && _this.familyId !== val.Id) {
            DialogService.confirm({
              title: '快捷键已经存在,请另外设置其它的快捷健'
            })
              .then(() => {
                _this.shortcutKey = '';
              })
              .catch(() => {
                _this.shortcutKey = '';
              });
          }
        });
      }
    },
    nickName() {
      if (this.nickName.length >= 6 && this.nickName != this.$route.query.relationship) {
        NotifyService.notify({
          type: 'warning',
          message: '昵称最长可设置6位'
        });
      }
    },
    phone() {
      if (this.phone.length > 11) {
        this.phone = this.phone.replace(/\s+/g, '');
      }
    }
  },
  mounted() {
    this.getCommandList();
    setTimeout(() => {
      this.initShortKey();
      ToastService.clear();
    }, 1000);
  }
};
</script>

<style lang="scss" scoped>
.addFamilyNumber {
  .required {
    color: red;
    padding: 0 10px;
  }
  .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>
