<template>
  <div class="body-view">
    <el-text class="title">注册</el-text>
    <el-form class="form-view" @submit.prevent="handleRegister">
      <el-form-item label="账号:" :error="usernameError">
        <el-input v-model="username" placeholder="请输入账号" class="ipt" @input="validateUsername"></el-input>
      </el-form-item>
      <el-form-item label="密码:" :error="passwordError">
        <el-input type="password" v-model="password" placeholder="请输入密码" class="ipt"
          @input="validatePassword"></el-input>
      </el-form-item>
      <el-form-item label="确认密码:" :error="confirmPasswordError">
        <el-input type="password" v-model="confirmPassword" placeholder="请再次输入密码" class="ipt"
          @input="validateConfirmPassword"></el-input>
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="isAdminRef">
          <span class="checkbox-label">我是快递员</span>
        </el-checkbox>
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="isAgreed">
          <span class="checkbox-label">我已阅读并同意《用户协议》</span>
        </el-checkbox>
      </el-form-item>

      <el-form-item class="btn-view">
        <div class="button-container">
          <el-button class="btn" type="primary" @click="handleRegister"
            :disabled="!isAgreed || !canRegister">注册</el-button>
          <el-button class="btn cancel-btn" type="primary" @click="goToLogin">返回登录</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import req from '../request';


const username = ref('');
const password = ref('');
const confirmPassword = ref('');
const isAgreed = ref(false);

const usernameError = ref('');
const passwordError = ref('');
const confirmPasswordError = ref('');
const isAdminRef = ref(false);

const router = useRouter();

// 检测账号是否已存在
const isUsernameUnique = () => {
  const accounts = JSON.parse(localStorage.getItem('accounts') || '[]');
  return !accounts.some(account => account.username === username.value);
};

// 验证账号（长度至少8，包含字母和数字，且唯一）
const validateUsername = () => {

  if (!isUsernameUnique()) {
    usernameError.value = '该账号已存在，请选择其他账号';
    return false;
  }
  usernameError.value = '';
  return true;
};

// 验证密码（长度至少8，包含字母和数字，满足中级强度）
const validatePassword = () => {
  if (password.value.length < 8) {
    passwordError.value = '密码长度至少为8位';
    return false;
  }
  if (!/[a-zA-Z]/.test(password.value) || !/\d/.test(password.value)) {
    passwordError.value = '密码必须包含字母和数字';
    return false;
  }
  passwordError.value = '';
  return true;
};

// 验证确认密码
const validateConfirmPassword = () => {
  if (confirmPassword.value !== password.value) {
    confirmPasswordError.value = '两次输入的密码不一致';
    return false;
  }
  confirmPasswordError.value = '';
  return true;
};

// 计算属性：注册按钮的可用状态
const canRegister = computed(() => validateUsername() && validatePassword() && validateConfirmPassword());

// 处理注册
const handleRegister = () => {
  if (canRegister.value) {
    // 保存账号和密码到 localStorage
    const data = {
      loginId: username.value,
      loginPwd: password.value
    }
    if (isAdminRef.value) {
      data.isAdmin = true
    }
    req({
      method: "POST",
      url: "/user",
      data
    }).then((res) => {
      ElMessage.success('注册成功！请返回登录');
      router.push('/login'); // 使用 Vue Router 跳转到 /login 路由
    })

  } else {
    ElMessage.error('请确保填写正确的信息');
  }
};


// 返回登录视图
const goToLogin = () => {
  router.push('/login'); // 使用 Vue Router 跳转到 /login 路由
};

</script>

<style>
.body-view {
  background-color: #f7f9fc;
  border-radius: 12px;
  box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
  width: 400px;
  padding: 40px;
  margin: 60px auto;
}

.title {
  font-size: 32px;
  font-weight: bold;
  color: #007bff;
  text-align: center;
  margin-bottom: 25px;
}

.ipt {
  border: 1px solid #ced4da;
  height: 50px;
  border-radius: 8px;
  transition: border-color 0.3s;
}

.ipt:focus {
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}

.button-container {
  display: flex;
  justify-content: center;
  gap: 10px;
  width: 100%;
}

.btn {
  height: 50px;
  width: 100px;
  background-color: #007bff;
  border: none;
  color: white;
  margin: 0 30px;
  font-size: 16px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.btn:hover {
  background-color: #0056b3;
}

.btn-view {
  margin-top: 30px;
  text-align: center;
}

.checkbox-label {
  font-size: 14px;
}

.el-checkbox {
  margin-bottom: 5px;
}
</style>
