<template>
  <div class="container">
    <div class="block">
      <van-field v-model="phone" label="手机号" placeholder="请输入" required/>
      <van-field v-model="smsCode" label="验证码" placeholder="请输入" required>
        <template #button>
          <van-button v-if="time === 60" round size="mini" type="info" @click="getCode">获取验证码</van-button>
          <van-button v-else disabled round size="mini" type="info">{{ time }}s后重试</van-button>
        </template>
      </van-field>
    </div>
    <van-button block color="linear-gradient(to right, #81B5FB, #3E92FF)" round @click="submit">注册</van-button>
  </div>
</template>

<script>
import {register, sendsmscode} from '@/api/user'

var leftTime
export default {
  name: 'userInfo',
  data() {
    return {
      form: {},
      time: 60,
      userInfo: {},
      phone: '',
      smsCode: '',
      surName: '',
      gender: '',
      userId: ''
    }
  },

  mounted() {
    this.init()
  },
  destroyed() {
    clearInterval(leftTime)
  },
  methods: {
    init() {
      this.type = this.$route.params.type ? this.$route.params.type : ''
      this.userInfo = this.$store.state.app.userInfo
      this.gender = this.userInfo.gender
      this.surName = this.userInfo.realName || this.userInfo.nickname
    },
    submit() {
      let params = {
        phone: this.phone,
        smsCode: this.smsCode,
        surName: this.surName,
        appid: this.$store.state.app.appId
      }
      if (!params.phone) {
        this.$toast.fail('请输入手机号')
        return
      }
      if (!params.smsCode) {
        this.$toast.fail('请输入验证码')
        return
      }
      register(params).then(res => {
        localStorage.setItem('token', res.token)
        this.$toast.success('注册成功')
        let query = this.$route.query
        this.$router.replace({ path: query.redirect, query: query.params ? JSON.parse(query.params) : {} })
      })
    },
    getCode() {
      if (!this.phone) {
        this.$toast.fail('请输入手机号')
        return false
      }
      if (!/1[3456789]\d{9}/.test(this.phone)) {
        this.$toast.fail('手机号格式错误')
        return false
      }
      sendsmscode({
        phone: this.phone
      }).then(() => {
        leftTime = setInterval(() => {
          if (this.time > 0) {
            this.time--
          } else {
            this.time = 60
            clearInterval(leftTime)
          }
        }, 1000)
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import './index';
</style>
