<template>
  <div class="register-page">
    <van-nav-bar
      title="注册账号"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <div class="content">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="form.username"
            name="username"
            label="用户名"
            placeholder="3-50个字符"
            :rules="[{ required: true, message: '请输入用户名' }]"
          />
          <van-field
            v-model="form.password"
            type="password"
            name="password"
            label="密码"
            placeholder="6-20个字符"
            :rules="[{ required: true, message: '请输入密码' }]"
          />
          <van-field
            v-model="form.name"
            name="name"
            label="姓名"
            placeholder="请输入真实姓名"
            :rules="[{ required: true, message: '请输入姓名' }]"
          />
          <van-field
            v-model="form.studentId"
            name="studentId"
            label="学号"
            placeholder="非在校生可不填"
          />
          <van-field
            v-model="form.email"
            name="email"
            label="邮箱"
            placeholder="选填"
          />
          <van-field
            v-model="form.phone"
            name="phone"
            label="手机号"
            placeholder="选填"
          />
        </van-cell-group>

        <div style="margin: 32px 16px;">
          <van-button round block type="primary" native-type="submit" :loading="loading">
            注册
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { register } from '@/services/auth';
import { showToast } from 'vant';

const router = useRouter();

const form = reactive({
  username: '',
  password: '',
  name: '',
  studentId: '',
  email: '',
  phone: ''
});

const loading = ref(false);

const onClickLeft = () => history.back();

const onSubmit = async () => {
  loading.value = true;
  try {
    await register(form);
    showToast('注册成功');
    router.replace('/login');
  } catch (error) {
    // Error handled by interceptor
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="scss">
.register-page {
  min-height: 100vh;
  background-color: #f7f8fa;

  .content {
    padding-top: 20px;
  }
}
</style>
