<template>
  <div class="page">
    <h-navbar title="Registar" />
    <div class="page-body" :style="{ height: pageHeight }">
      <h-img src="base/2logo.png" width="6rem" type="local" />
      <div class="bottom">
        <other-login />
        <div class="form">
          <h-input
            v-model="data.mobile"
            type="mobile"
            :maxlength="11"
            background="#141618"
            placeholder="Número de Celular"
          />
          <h-input
            background="#141618"
            v-model="data.pwd"
            type="password"
            placeholder="Senha"
          />

          <van-button
            class="login-button"
            color="#2F6368"
            size="large"
            :disabled="hasLogin"
            @click="onRegister"
          >
            Criar Conta
          </van-button>
          <p>
            Já tem uma conta?
            <span style="color: #55ba57" @click="login">Log in</span>
          </p>
        </div>
      </div>
    </div>
    <van-sticky :offset-bottom="0" position="bottom">
      <bottom-tips />
    </van-sticky>
  </div>
</template>

<script setup lang="ts">
import https from "@/https";
import { reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { showLoading, toast } from "@/utils/toast";
import {
  buryingPointToFaceBook,
  buryingPointToGoogle,
  buryingPointToKwaiq,
  resultMobile,
  getLocationParams,
} from "@/utils";
import useLogin from "@/hooks/useLogin";
import useBase from "@/hooks/useBase";
import { MOBILE_CODE } from "@/common/config";

const { onLogin } = useLogin();
const { pageHeight } = useBase();

const router = useRouter();

const data = reactive({
  code: MOBILE_CODE,
  mobile: "",
  pwd: "",
});

const onRegister = async () => {
  let reg2 = RegExp(/^.{6,18}$/);
  const flag = resultMobile(data.mobile);
  if (!flag) {
    return toast("Por favor, introduza o número de telefone correto");
  }
  if (!reg2.test(data.pwd)) {
    return toast("Por favor, introduz uma senha de 6 a 18 dígitos");
  }
  showLoading();
  let params: any = {
    mobile: data.code + data.mobile,
    pwd: data.pwd,
  };
  let uid = getLocationParams(window.location.href);
  if (uid.u) {
    params.inviteUid = uid.u;
  }
  const { code, txt }: ResultData = await https.register(params);
  if (code !== 0) {
    toast(txt);
    return;
  }
  // 注册埋点
  buryingPointToFaceBook("CompleteRegistration");
  buryingPointToKwaiq("completeRegistration");
  buryingPointToGoogle("sign_up", { method: "Google" });
  onLogin(data, true);
};

const login = () => {
  router.push("/login");
};

const hasLogin = computed(() => {
  return !data.mobile || !data.pwd;
});
</script>

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