<template>
  <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="registerForm.username" placeholder="请输入用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="registerForm.password"
        type="password"
        placeholder="请输入密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="confirmPassword">
      <el-input
        v-model="registerForm.confirmPassword"
        type="password"
        placeholder="请再次输入密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(registerFormRef)"> 重置 </el-button>
    <el-button :icon="Check" round size="large" type="primary" :loading="loading" @click="submit(registerFormRef)">
      注册
    </el-button>
  </div>
  <div class="form-footer">
    已有账号？
    <el-button link type="primary" @click="goLogin"> 返回登录 </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import type { ElForm } from "element-plus";
import { ElNotification } from "element-plus";
import md5 from "md5";
import { LOGIN_URL } from "@/config";
import { Login } from "@/api/interface";
import { registerApi } from "@/api/modules/login";
import { CircleClose, Check } from "@element-plus/icons-vue";

type FormInstance = InstanceType<typeof ElForm>;

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

const registerForm = reactive<Login.ReqRegisterForm & { confirmPassword: string }>({
  username: "",
  password: "",
  confirmPassword: ""
});

const validateConfirmPassword = (_rule: any, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    callback(new Error("请再次输入密码"));
    return;
  }
  if (value !== registerForm.password) {
    callback(new Error("两次输入的密码不一致"));
    return;
  }
  callback();
};

const registerRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: "blur" }]
});

const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      const payload: Login.ReqRegisterForm = {
        username: registerForm.username,
        password: md5(registerForm.password)
      };
      const { data } = (await registerApi(payload)) as { data: Login.ResRegister };
      if (data.result) {
        ElNotification({
          title: "注册成功",
          message: "请使用新账号登录",
          type: "success",
          duration: 6000
        });
        goLogin();
      } else {
        ElNotification({
          title: "注册失败，请稍后重试",
          type: "error",
          duration: 8000
        });
      }
    } finally {
      loading.value = false;
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const goLogin = () => {
  router.push(LOGIN_URL);
};

onMounted(() => {
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      submit(registerFormRef.value);
    }
  };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
</script>

<style scoped lang="scss">
@import "../../login/index";
</style>
