<script setup lang="ts">
import {reactive, ref} from 'vue'
import {debounce} from "@/utils/common.ts";
import {register, sendCode} from "@/api/user.ts";
import {AuthCodeType} from "@/enums/verification.ts";
import {ElMessage, type FormInstance} from "element-plus";
import {LoginType, userStore} from "@/stores/user.ts";
import AccountFormItem from "@/components/common/login/component/AccountFormItem.vue";
import CodeFormItem from "@/components/common/login/component/CodeFormItem.vue";
import PasswordFormItem from "@/components/common/login/component/PasswordFormItem.vue";
import SubmitFormBtn from "@/components/common/login/component/SubmitFormBtn.vue";

const form = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: ''
});
const user = userStore();
const ruleFormRef = ref<FormInstance>();

const debouncedSendAuthCode = debounce(sendAuthCode, 500);

async function sendAuthCode(sendAuthCodeCallBack: () => void) {
  if (!ruleFormRef.value?.validateField) return;
  await ruleFormRef.value.validateField('phone', async (valid) => {
    if (valid) {
      const {phone} = form;
      await sendCode({phone, type: AuthCodeType.REGISTER});
      if (sendAuthCodeCallBack) {
        sendAuthCodeCallBack()
      }
    } else {
      ElMessage.error('请输入正确的手机号码');
    }
  });
}

const debouncedSubmitForm = debounce(submitForm, 500);
function submitForm(formEl: FormInstance | undefined, callBack: () => void) {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const {phone, password, code} = form;
        await register({phone, password, code})
        ElMessage.success('注册成功')
        user.loginType = LoginType.ACCOUNT_LOGIN;
      } catch (e) {
        console.log(e);
      }
      callBack && callBack()
    } else {
      callBack && callBack()
      // ElMessage.error('注册失败，请稍后重试')
      console.log('error submit!', fields);
    }
  });
}


</script>
<template>
  <div class="bf-login-dialog-box">
    <h1 class="title">注册</h1>
    <div class="bf-login-form">
      <el-form :model="form" ref="ruleFormRef">
        <AccountFormItem prop-name="phone" v-model:phone="form.phone"/>
        <CodeFormItem v-model:code="form.code" @sendAuthCode="debouncedSendAuthCode"/>
        <PasswordFormItem prop-name="password" v-model:password="form.password"></PasswordFormItem>
        <PasswordFormItem prop-name="confirmPassword" v-model:password="form.confirmPassword" v-model:confirm-password="form.password" placeholder="请确认登陆密码"></PasswordFormItem>
        <SubmitFormBtn @submit-click="debouncedSubmitForm(ruleFormRef, $event)">立即注册</SubmitFormBtn>
      </el-form>
      <div class="bf-register-account">
        <span>已有账户？</span>
        <a @click="user.loginType = LoginType.ACCOUNT_LOGIN">立即登录</a>
      </div>
    </div>
  </div>
</template>


<style scoped lang="scss">
.bf-register-account {
  margin-top: -30px;

  a {
    color: #409EFF;
  }
}
</style>
