<template>
  <div class="binding-phone">
    <div class="relative-wrap">
      <div class="title-wrap">
        <p class="title">- 手机号绑定 -</p>
        <span>成功绑定可得<i>100</i>书币</span>
      </div>
      <div class="form-wrap">
        <div class="form-item">
          <input type="phone"
                 v-model="info.phone"
                 placeholder="请输入手机号"
                 @focus="showBg = false"
                 @blur="showBg = true">
        </div>
        <div class="form-item">
          <input type="text"
                 v-model="info.code"
                 placeholder="请输入手机验证码"
                 @focus="showBg = false"
                 @blur="showBg = true">
          <span class="get-code"
                @click="getCode">{{code_text}}</span>
        </div>
      </div>
      <div class="to-binding"
           @click="bindNow">立即绑定</div>
    </div>
    <transition name="fade">
      <img src="../assets/bg.jpg"
           alt=""
           class="bg"
           v-show="showBg">
    </transition>
  </div>
</template>

<script>
import { PhoneBinding } from "../components/prompt";

import { getPhoneCode, phoneBind } from "../api";

export default {
  data() {
    return {
      showBg: true,
      code_getting: false,
      code_text: "获取验证码",
      info: {
        phone: "",
        code: "",
        from: "person"
      }
    };
  },
  methods: {
    getCode() {
      const { info, code_getting } = this;
      const codeNumber = 60;
      if (!this.validatePhone(info.phone)) return;
      if (!code_getting) {
        this.code_getting = true;
        getPhoneCode(info.phone)
          .then(_ => {
            this.countDown(codeNumber);
          })
          .catch(e => {
            this.$Toast(e.data.msg);
          });
      }
    },
    validatePhone(phone) {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57]|19[0-9])[0-9]{8}$/;
      let flag = true;
      if (!phone) {
        this.$Toast("请输入手机号！");
        flag = false;
      } else if (!reg.test(phone)) {
        this.$Toast("请输入正确的手机号！");
        flag = false;
      }
      return flag;
    },
    countDown(time) {
      let timer = null;
      this.code_text = time + "s";
      timer = setInterval(() => {
        time--;
        if (time === 0) {
          this.code_text = "获取验证码";
          this.code_getting = false;
          clearInterval(timer);
        } else this.code_text = time + "s";
      }, 1000);
    },
    bindNow() {
      const { info } = this;
      if (!this.validatePhone(info.phone)) return;
      if (!info.code) {
        this.$Toast("请输入验证码");
        return;
      }
      // request
      phoneBind(info)
        .then(r => {
          return PhoneBinding();
        })
        .then(_ => {
          this.$router.replace("/person");
        })
        .catch(e => {
          this.$Toast(e.data.msg);
        });
    }
  }
};
</script>
