<template>
  <div class="verificationCode-wrap">
    <div class="title">
      <i class="icon icon-jiantou-zuo" @click="goBack"></i>
    </div>
    <div class="tab">
      <p>请您输入验证码</p>
    </div>
    <p class="info">
      验证码已发送至您的{{registerType}}
      <br>
      {{countryCode ? countryCode + ' ' + $route.query.value : $route.query.value }}
    </p>
    <div class="code">
      <p>6位数字验证码</p>
      <div class="input" @click="showKeyboard = true">
        <i
          v-for="(item, index) in 6"
          :class="{active: index+1 == value.length}"
          :key="index">
          {{value.substr(index, 1)}}
        </i>
      </div>
      <p class="sendAgain">没收到验证码？
        <span @click="againGetAreaCode" v-if="number == 0">重新获取</span>
        <i v-else>{{number}}s</i>
      </p>
    </div>
    <van-number-keyboard
      :show="showKeyboard"
      @input="onInput"
      @delete="onDelete"
      @blur="showKeyboard = false"
    />
  </div>
</template>

<script>
export default {
  name: "VerificationCode",
  data() {
    return {
      value: "",
      showKeyboard: false,
      registerType: null,
      number: 60,
      countryCode: null,
      lang: this.$store.state.langStr,
      disabled: false
    };
  },
  created: function() {
    window.scrollTo({
      top: 0,
      behavior: "instant"
    });
    this.time();
    let item = this.$util.sessionStorage.fetch("registerItem");
    if (item && item.key === "mail") {
      this.registerType = "邮箱";
    } else {
      this.countryCode = this.$util.storage.fetch("areaCodeItem").code;
      this.registerType = "手机";
    }
  },
  watch: {
    value(val) {
      if (val.length === 6) {
        this.validateAreaCode();
      }
    }
  },
  mounted: function() {},
  methods: {
    onInput(key) {
      this.value = (this.value + key).slice(0, 6);
    },
    onDelete() {
      this.value = this.value.slice(0, this.value.length - 1);
    },
    // 重新获取验证码
    againGetAreaCode() {
      if (this.number === 0 && this.disabled === false) {
        this.disabled = true;
        let params = {};
        params.url = this.$apis.api_user_verification;
        params.data = {
          status: this.$util.sessionStorage.fetch("sendType")
        };
        let item = this.$util.sessionStorage.fetch("registerItem");
        if (item && item.key === "mail") {
          params.data.email = item.value;
        } else {
          params.data.mobile = this.$route.query.value;
          params.data.countryId =
            this.$store.state.areaCodeObj.id ||
            this.$util.storage.fetch("areaCodeItem").id;
        }
        this.$net.req(params, this).then(
          res => {
            if (Number(res.code) === 0) {
              this.time();
            }
          },
          e => {
            this.$Toast(e.msg);
          }
        );
      }
    },
    // 验证验证码
    validateAreaCode() {
      let item = this.$util.sessionStorage.fetch("registerItem");
      let params = {};
      switch (this.$util.sessionStorage.fetch("sendType")) {
        case 1:
          // 注册
          params.url = this.$apis.api_user_verification_code;
          params.data = {
            code: this.value
          };
          if (item && item.key === "mail") {
            params.data.email = item.value;
          } else {
            params.data.mobile = this.$route.query.value;
            params.data.countryId =
              this.$store.state.areaCodeObj.id ||
              this.$util.storage.fetch("areaCodeItem").id;
          }
          this.$net.req(params, this).then(
            res => {
              if (Number(res.code) === 0) {
                this.$router.push({
                  path: "/" + this.lang + "/setNickname"
                });
              }
            },
            e => {
              this.$Toast(e.msg);
            }
          );
          break;
        case 2:
          // 找回密码、修改密码
          params.url = this.$apis.api_user_pwd_find;
          params.data = {
            code: this.value,
            pwd: this.$util.aesDecrypt(
              this.$util.sessionStorage.fetch("password")
            )
          };
          if (item && item.key === "mail") {
            params.data.email = item.value;
          } else {
            params.data.mobile = this.$route.query.value;
            params.data.countryId =
              this.$store.state.areaCodeObj.id ||
              this.$util.storage.fetch("areaCodeItem").id;
          }
          this.$net.req(params, this).then(
            res => {
              if (Number(res.code) === 0) {
                this.$Toast("密码找回成功");
                this.$store.commit("setUserObj", res.data);
                let userInfo = encodeURIComponent(JSON.stringify(res.data));
                this.$util.storage.save("loginUserInfo", userInfo);
                this.$util.storage.save("userToken", res.data.token);
                setTimeout(() => {
                  // 客源表单
                  if (this.$util.sessionStorage.fetch("guide")) {
                    window.location.replace("/" + this.lang + "/form");
                  } else {
                    window.location.replace("/");
                  }
                }, 1500);
              }
            },
            e => {
              this.$Toast(e.msg);
            }
          );
          break;
        case 3:
          // 绑定手机号、邮箱
          params.url = this.$apis.api_user_binding;
          params.data = {
            code: this.value
          };
          if (item && item.key === "mail") {
            params.data.email = item.value;
          } else {
            params.data.mobile = this.$route.query.value;
            params.data.countryId =
              this.$store.state.areaCodeObj.id ||
              this.$util.storage.fetch("areaCodeItem").id;
          }
          this.$net.req(params, this).then(
            res => {
              if (Number(res.code) === 0) {
                this.$Toast("绑定成功");
                this.$store.commit("setUserObj", res.data);
                let userInfo = encodeURIComponent(JSON.stringify(res.data));
                this.$util.storage.save("loginUserInfo", userInfo);
                this.$util.storage.save("userToken", res.data.token);
                setTimeout(() => {
                  window.location.replace("/");
                }, 300);
              }
            },
            e => {
              this.$Toast(e.msg);
            }
          );
          break;
        case 5:
          // 验证码登录
          params.url = this.$apis.api_user_mobile_code;
          params.data = {
            code: this.value,
            mobile: this.$route.query.value,
            registerSource: "nature_mobile",
            countryId:
              this.$store.state.areaCodeObj.id ||
              this.$util.storage.fetch("areaCodeItem").id
          };
          this.$net.req(params, this).then(
            res => {
              if (Number(res.code) === 0) {
                this.$store.commit("setUserObj", res.data);
                let userInfo = encodeURIComponent(JSON.stringify(res.data));
                this.$util.storage.save("loginUserInfo", userInfo);
                this.$util.storage.save("userToken", res.data.token);
                setTimeout(() => {
                  // 客源表单
                  if (this.$util.sessionStorage.fetch("guide")) {
                    this.$router.push({
                      path: "/" + this.lang + "/form"
                    });
                  } else {
                    if (this.$route.query.next) {
                      window.location.replace(this.$route.query.next);
                    } else {
                      window.location.replace("/");
                    }
                  }
                }, 1500);
              }
            },
            e => {
              this.$Toast(e.msg);
            }
          );
          break;
        default:
          break;
      }
    },
    // 倒计时
    time() {
      var num = 60;
      let name = setInterval(() => {
        num--;
        this.number = num;
        if (num === 0) {
          this.disabled = false;
          clearInterval(name);
        }
      }, 1000);
    },
    // 返回
    goBack() {
      window.history.length > 1 ? this.$router.go(-1) : this.$router.push("/");
    }
  }
};
</script>

<style scoped lang="less">
.verificationCode-wrap {
  padding: 0 20px;
  background: #fff;
  min-height: 100vh;
  .title {
    display: flex;
    margin: 5px 0 30px -5px;
    i {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 34px;
      height: 34px;
      font-size: 18px;
      color: #ccc;
    }
  }
  .tab {
    display: flex;
    p {
      font-size: 24px;
      color: #222;
      font-weight: 500;
      line-height: 34px;
      margin: 0 20px 0 0;
    }
  }
  .info {
    font-size: 13px;
    font-weight: 400;
    color: rgba(204, 204, 204, 1);
    line-height: 22px;
    margin: 10px 0 0;
  }
  .code {
    > p {
      font-size: 13px;
      font-weight: 400;
      color: rgba(238, 238, 238, 1);
      line-height: 18px;
      margin: 50px 0 10px;
    }
    .input {
      position: relative;
      display: flex;
      input {
        border: 0;
        height: 45px;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        font-size: 24px;
        background: transparent;
      }
      i {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 45px;
        height: 45px;
        border-radius: 4px;
        flex-shrink: 0;
        margin-right: 12px;
        font-size: 24px;
        color: #222;
        border: 1px solid #ccc;
      }
      i.active {
        border-color: #ff523d;
      }
      i:last-child {
        margin: 0;
      }
    }
    .sendAgain {
      margin: 20px 0 0;
      color: #999;
      span {
        color: #ff523d;
      }
    }
  }
}
</style>
