<template>
    <div class="register">
      <van-nav-bar
        left-arrow
        @click-left="onClickLeft"
      />
      <van-tabs class="register-tabs" type="card" v-model="active" animated @change="_change">
        <van-tab title="手机注册">
          <van-form class="register-form" @submit="onSubmit">
            <van-field
              v-model="phone"
              placeholder="手机号码"
              :rules="[{ required: true, message: '请填写手机号码' }]"
            />
            <van-field
              v-model="password"
              type="password"
              placeholder="密码"
              :rules="[{ required: true, message: '请填写密码' }]"
            />
            <van-field
              v-model="invite"
              placeholder="邀请码(选填)"
            />
            <div style="margin: 16px;">
              <van-button round block type="info" native-type="submit">注册</van-button>
            </div>
          </van-form>
        </van-tab>
        <van-tab title="邮箱注册">
          <van-form class="register-form" @submit="onSubmit">
            <van-field
              v-model="email"
              placeholder="邮箱账号"
              :rules="[{ required: true, message: '请填写邮箱账号' }]"
            />
            <van-field
              v-model="password"
              type="password"
              placeholder="密码"
              :rules="[{ required: true, message: '请填写密码' }]"
            />
            <van-field
              v-model="invite"
              placeholder="邀请码(选填)"
            />
            <div style="margin: 16px;">
              <van-button round block type="info" native-type="submit">注册</van-button>
            </div>
          </van-form>
        </van-tab>
      </van-tabs>
    </div>
</template>

<script>
export default {
  name: 'register',
  data () {
    return {
      phone: '',
      email: '',
      password: '',
      invite: '',
      active: 0
    }
  },
  created () {
    if (this.$route.query) {
      this.invite = this.$route.query.code
    }
  },
  methods: {
    onClickLeft () {
      this.$router.go(-1)
    },
    onSubmit () {
      this.$http.user.register({
        phone: this.active === 0 && this.phone,
        email: this.active === 1 && this.email,
        password: this.password,
        refcode: this.invite
      }).then(({ code, msg }) => {
        if (code === 200) {
          this.$toast.success(msg)
          this.$router.push('/login')
        }
      })
    },
    _change () {
      this.password = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.register {
  &-tabs {
    margin-top: 20px;
  }
  &-form {
    margin-top: 20px;
  }
}
</style>
