<script setup lang="ts">
import {reactive, ref} from 'vue'
import {debounce} from "@/utils/common.ts";
import {bindPhone, 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 SubmitFormBtn from "@/components/common/login/component/SubmitFormBtn.vue";
import {useRoute} from "vue-router";
const route = useRoute();
const props = defineProps(['openId'])
const form = reactive({
  phone: '',
  code: '',
  openId: props.openId
});
console.log(form);
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.WECHAT_LAUNCH});
      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, openId, code} = form;
        const res = await bindPhone({phone, openId: props.openId, code})
        console.log('res=', res.token);
        ElMessage.success('绑定成功');
        localStorage.setItem('TOKEN', `${res.token}`);
        location.href = '/'
      } 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" placeholder="请输入手机号码"/>
        <CodeFormItem v-model:code="form.code" @sendAuthCode="debouncedSendAuthCode"/>
        <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-login-dialog-box{
  padding: 40px;
}
.bf-register-account {
  margin-top: -30px;

  a {
    color: #409EFF;
  }
}
</style>
<!-- 登陆框公共样式 -->
<style src="@/assets/styles/components/common/login/GlobalLoginDialog.scss"></style>
