<template>
  <div class="register-container">
    <h2>用户注册</h2>
    <form @submit.prevent="handleRegister" class="register-form">
      <div class="form-group">
        <label for="email">邮箱:</label>
        <input type="email" id="email" v-model="formData.email" required />
      </div>
      <div class="form-group">
        <label for="phone_number">手机号:</label>
        <input type="tel" id="phone_number" v-model="formData.phone_number" required />
      </div>
      <div class="form-group">
        <label for="nickname">昵称:</label>
        <input type="text" id="nickname" v-model="formData.nickname" required />
      </div>
      <div class="form-group">
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="formData.password" required />
      </div>
      <div class="form-group">
        <label for="password2">确认密码:</label>
        <input type="password" id="password2" v-model="formData.password2" required />
      </div>
      <div class="form-group">
        <label for="school">学校 (可选):</label>
        <input type="text" id="school" v-model="formData.school" />
      </div>
      <div class="form-group">
        <label for="bio">简介 (可选):</label>
        <textarea id="bio" v-model="formData.bio"></textarea>
      </div>
      <div class="form-group">
        <label for="avatar">头像 (可选):</label>
        <input type="file" id="avatar" @change="handleFileChange" accept="image/*" />
      </div>
      <button type="submit" :disabled="isLoading">
        {{ isLoading ? '注册中...' : '注册' }}
      </button>
      <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
      <p v-if="successMessage" class="success-message">{{ successMessage }}</p>
    </form>
    <p class="login-link">
      已有账号？ <router-link to="/login">立即登录</router-link>
    </p>
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
// import apiClient from '../services/api'; // 现在注册逻辑在store中
import { useRouter } from 'vue-router';
import { useAuthStore } from '../store/auth';

const formData = reactive({
  email: '',
  phone_number: '',
  nickname: '',
  password: '',
  password2: '',
  school: '',
  bio: '',
  avatar: null,
});

const errorMessage = ref('');
const successMessage = ref('');
const isLoading = ref(false);
const router = useRouter();
const authStore = useAuthStore();

const handleFileChange = (event) => {
  const file = event.target.files[0];
  formData.avatar = file || null;
};

const handleRegister = async () => {
  isLoading.value = true;
  errorMessage.value = '';
  successMessage.value = '';
  authStore.loginError = null; // 清除 store 中的错误

  const submissionData = new FormData();
  Object.keys(formData).forEach(key => {
    if (formData[key] !== null && formData[key] !== '') { // 只添加有值的字段
      submissionData.append(key, formData[key]);
    }
  });
  // 如果密码为空，后端会验证，这里确保至少传了
  if (!formData.password) submissionData.append('password', '');
  if (!formData.password2) submissionData.append('password2', '');


  try {
    await authStore.register(submissionData); // 调用store的register action

    successMessage.value = '注册成功！已自动登录，即将跳转到首页...';
    setTimeout(() => {
      router.push('/');
    }, 2000);

  } catch (error) {
    errorMessage.value = error.message || '注册失败，发生了未知错误。';
    console.error('Register component error:', error);
  } finally {
    isLoading.value = false;
  }
};
</script>
<style scoped>
/* 样式与LoginView类似，你可以复用或自定义 */
.register-container { max-width: 450px; margin: 30px auto; padding: 25px; border: 1px solid #ddd; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
.register-form .form-group { margin-bottom: 12px; text-align: left; }
.register-form label { display: block; margin-bottom: 4px; font-weight: bold; font-size: 0.9em; }
.register-form input[type="email"],
.register-form input[type="tel"],
.register-form input[type="text"],
.register-form input[type="password"],
.register-form textarea { width: calc(100% - 22px); padding: 9px; border: 1px solid #ccc; border-radius: 4px; font-size: 0.95em; }
.register-form input[type="file"] { font-size: 0.9em; }
.register-form textarea { resize: vertical; min-height: 60px; }
.register-form button { width: 100%; padding: 10px; background-color: #5cb85c; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 1em; transition: background-color 0.3s; margin-top: 10px; }
.register-form button:disabled { background-color: #aaa; cursor: not-allowed; }
.register-form button:hover:not(:disabled) { background-color: #4cae4c; }
.error-message { color: red; margin-top: 10px; font-size: 0.9em; }
.success-message { color: green; margin-top: 10px; font-size: 0.9em; }
.login-link { margin-top: 15px; font-size: 0.9em; }
.login-link a { color: #42b983; text-decoration: none; }
.login-link a:hover { text-decoration: underline; }
</style>