<script setup lang="ts">
import { loginData, userinfo } from "@/store/store.js";
import YlLoginData from "@/pages/login/login-data.vue";
import { CaretLeft } from "@element-plus/icons-vue";
import { ref } from "vue";
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { ElMessage } from "element-plus";
import jsEncrypt from "jsencrypt";
import { formatError } from "@/utils/utils.ts";
const loading = ref(false);
const { runAsync: getPubKey } = useRequest(
  () => myRequest(`/api/user/login?username=${loginData.username}`),
  { manual: true },
);
const { runAsync: runRegister } = useRequest(
  (enPass: string) =>
    myRequest(
      `/api/user?username=${loginData.username}&password=${encodeURIComponent(enPass)}`,
      "",
      {},
      "post",
    ),
  { manual: true },
);
const toRegister = () => {
  if (!loginData.username) {
    ElMessage.error("请输入用户名");
    return;
  }
  loading.value = true;
  getPubKey()
    .then((res) => {
      if (res.code === 200) {
        const encrypt = new jsEncrypt();
        encrypt.setPublicKey(res.data as string);
        const enPwd = encrypt.encrypt(loginData.password);
        runRegister(enPwd as string)
          .then((r) => {
            loading.value = false;
            if (r.code === 200) {
              userinfo.login = true;
              userinfo.username = loginData.username;
              userinfo.token = r.data;
            }
          })
          .catch((r) => {
            loading.value = false;
            ElMessage.error(`登录失败：${formatError(r)}`);
          });
      }
    })
    .catch((res) => {
      loading.value = false;
      ElMessage.error(`获取公钥失败：${formatError(res)}`);
    });
};
</script>

<template>
  <div style="position: absolute; width: 100%; height: 100%">
    <div class="title">用户注册</div>
    <yl-login-data show-re-input />
    <div class="action-div">
      <el-button link size="large" @click="loginData.login = true"
        ><el-icon><CaretLeft /></el-icon>返回登录</el-button
      >
      <el-button
        type="primary"
        size="large"
        :disabled="
          !loginData.username ||
          !loginData.password ||
          loginData.password !== loginData.repeatPass ||
          loading
        "
        @click="toRegister"
      >
        {{ loading ? "注册中。。。" : "注册" }}</el-button
      >
    </div>
  </div>
</template>

<style scoped>
.title {
  position: relative;
  width: 100%;
  margin: 2rem auto;
  text-align: center;
  font-size: 2rem;
  background: linear-gradient(180deg, #ff69b4, #ff69b450);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.action-div {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 80%;
  margin: 0 auto;
  height: calc(100% - 27rem);
}
</style>
