<template>
  <div>
    <h2>Register</h2>
    <form @submit.prevent="register">
      <div>
        <label for="username">Username:</label>
        <input type="text" v-model="username" required>
      </div>
      <div>
        <label for="password">Password:</label>
        <input type="password" v-model="password" required>
      </div>
      <div>
        <label for="email">Email:</label>
        <input type="email" v-model="email" required>
      </div>
      <div>
        <label for="phoneNumber">Phone Number:</label>
        <input type="text" v-model="phoneNumber">
      </div>
      <div>
        <label for="company">Company:</label>
        <input type="text" v-model="company">
      </div>
      <div>
        <label for="role">Role:</label>
        <select v-model="role">
          <option value="USER">User</option>
          <option value="ADMIN">Admin</option>
        </select>
      </div>
      <div>
        <label for="verificationCode">Verification Code:</label>
        <input type="text" v-model="verificationCode" required>
        <button type="button" @click="getVerificationCode">Get Verification Code</button>
      </div>
      <button type="submit">Register</button>
    </form>
    <p v-if="message">{{ message }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import authenticationService from '../../services/authenticationService';

const username = ref('');
const password = ref('');
const email = ref('');
const phoneNumber = ref('');
const company = ref('');
const role = ref('USER');
const verificationCode = ref('');
const message = ref('');
const router = useRouter();

const getVerificationCode = async () => {
  // 模拟获取验证码
  message.value = 'Verification code sent. Please check your phone/email.';
};

const register = async () => {
  if (!verificationCode.value) {
    message.value = 'Please enter the verification code.';
    return;
  }
  try {
    const response = await authenticationService.register({
      username: username.value,
      password: password.value,
      email: email.value,
      phoneNumber: phoneNumber.value,
      company: company.value,
      role: role.value
    });
    message.value = response.data.message;
    router.push('/login');
  } catch (error) {
    console.error("Registration failed:", error.response.data.message);
    message.value = error.response.data.message;
  }
};
</script>