<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <span>创建您的账户</span>
        </div>
      </template>
      <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" label-position="top" hide-required-asterisk autocomplete="off">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="registerForm.name" placeholder="您的真实姓名" size="large" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="registerForm.phone" placeholder="您的手机号" size="large" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="您的邮箱" size="large" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="verificationCode">
          <el-row :gutter="10" style="width: 100%;">
            <el-col :span="15" class="verification-code-input">
              <el-input v-model="registerForm.verificationCode" placeholder="请输入6位验证码" size="large"></el-input>
            </el-col>
            <el-col :span="9">
              <el-button @click="sendVerificationCode" :disabled="isSendingCode || countdown > 0" :loading="isSendingCode" class="send-code-button" size="large">
                {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registerForm.password" placeholder="设置您的密码" show-password size="large" autocomplete="new-password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请再次输入您的密码" show-password size="large" autocomplete="new-password"></el-input>
        </el-form-item>
        <el-form-item label="注册身份" prop="role">
          <el-select v-model="registerForm.role" placeholder="请选择您的身份" style="width: 100%;" size="large">
            <el-option label="公众监督员" value="PUBLIC_SUPERVISOR"></el-option>
            <el-option label="网格员" value="GRID_WORKER"></el-option>
            <el-option label="业务主管" value="SUPERVISOR"></el-option>
            <el-option label="系统管理员" value="ADMIN"></el-option>
            <el-option label="决策者" value="DECISION_MAKER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" :loading="isRegistering" class="register-button">立即注册</el-button>
        </el-form-item>
        <div class="extra-links">
          <el-link type="info" @click="$router.push('/login')">已有账户？返回登录</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { signup, sendVerificationCode as apiSendCode } from '@/api/auth';

const router = useRouter();
const registerFormRef = ref<FormInstance>();
const isRegistering = ref(false);

const registerForm = reactive({
  name: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
  role: '',
  verificationCode: '',
});

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.password) {
    callback(new Error("两次输入的密码不一致!"));
  } else {
    callback();
  }
};

const validatePhone = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机号'));
  } else if (!/^1\d{10}$/.test(value)) {
    callback(new Error('手机号必须是以1开头的11位数字'));
  } else {
    callback();
  }
};

const registerRules = reactive<FormRules>({
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }],
  phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [{ validator: validatePass2, trigger: 'blur' }],
  role: [{ required: true, message: '请选择注册身份', trigger: 'change' }],
  verificationCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
});

const isSendingCode = ref(false);
const countdown = ref(0);
let timer: number | null = null;

const sendVerificationCode = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请输入您的邮箱地址');
    return;
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(registerForm.email)) {
    ElMessage.warning('请输入有效的邮箱地址');
    return;
  }

  isSendingCode.value = true;
  try {
    await apiSendCode(registerForm.email);
    ElMessage.success('验证码已发送，请注意查收');

    countdown.value = 60;
    if(timer) clearInterval(timer);
    timer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        if(timer) clearInterval(timer);
        timer = null;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error('验证码发送失败，请稍后重试');
    console.error(error);
  } finally {
    isSendingCode.value = false;
  }
};

const handleRegister = async () => {
  if (!registerFormRef.value) return;
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      isRegistering.value = true;
      try {
        const { confirmPassword, ...signupData } = registerForm;
        await signup(signupData);
        ElMessage.success('注册成功！正在跳转到登录页面...');
        setTimeout(() => {
          router.push('/login');
        }, 1500);
      } catch (error) {
        ElMessage.error('注册失败，请检查您填写的信息。');
        console.error(error);
      } finally {
        isRegistering.value = false;
      }
    }
  });
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100vw;
  overflow-y: auto; /* Allow scrolling only if card is too tall */
  padding: 40px 0;
  background-image: url('/register-bg.avif');
  background-size: cover;
  background-position: center;
}

.register-card {
  width: 550px; /* Wider card for more fields */
  border-radius: 25px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  background: rgba(245, 245, 245, 0.85);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.5);
}

.card-header {
  text-align: center;
  font-size: 26px;
  font-weight: 600;
  color: #004d40;
  padding: 25px 0 15px 0;
  border-bottom: 1px solid rgba(0,77,64,0.2);
}

.register-button {
  width: 100%;
  border: none;
  background: #004d40;
  color: white;
  letter-spacing: 5px;
  padding-left: 10px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 77, 64, 0.4);
  border-radius: 10px;
  font-size: 16px;
  height: 45px;
}

.register-button:hover {
  background: #00695c;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 77, 64, 0.5);
}

.extra-links {
  text-align: center;
  margin-top: 15px;
}

.extra-links .el-link {
  color: #555;
  font-size: 15px;
}
.extra-links .el-link:hover {
  color: #004d40;
}

/* Add scoped styles for the verification code input and button */
:deep(.verification-code-input .el-input__wrapper) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.send-code-button {
    width: 100%;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    background-color: #004d40;
    color: white;
    border-color: #004d40;
}

.send-code-button:hover {
    background-color: #00695c;
    border-color: #00695c;
}
</style>
<style>
/* Global overrides to match login page style */
:deep(.register-container .el-input__wrapper),
:deep(.register-container .el-select .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.9) !important;
  border-radius: 10px !important;
  height: 45px;
  box-shadow: none !important;
  border: 1px solid transparent !important;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

:deep(.register-container .el-input__wrapper:hover),
:deep(.register-container .el-select .el-input__wrapper:hover) {
  border-color: #ccc !important;
}

:deep(.register-container .el-input__wrapper.is-focus),
:deep(.register-container .el-select .el-input__wrapper.is-focused) {
   border-color: #004d40 !important;
   box-shadow: 0 0 0 1px rgba(0, 77, 64, 0.2) !important;
}

.register-container .el-form-item__label {
  color: #555 !important;
  font-weight: 500 !important;
  letter-spacing: 0.5px !important;
  font-size: 15px !important;
}

.register-container .el-input__inner {
  color: #333 !important;
  font-size: 16px !important;
}

.register-container .el-button {
  height: 45px;
  border-radius: 10px;
}
</style> 
