<script setup lang="ts">
import {reactive, ref} from 'vue'
import AccountFormItem from "@/components/common/login/component/AccountFormItem.vue";
import PasswordFormItem from "@/components/common/login/component/PasswordFormItem.vue";
import CodeFormItem from "@/components/common/login/component/CodeFormItem.vue";
import {LoginType, userStore} from "@/stores/user.ts";
import {ElMessage, FormInstance} from "element-plus";
import {debounce} from "@/utils/common.ts";
import { resetPassword, sendCode} from "@/api/user.ts";
import {AuthCodeType} from "@/enums/verification.ts";
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.FORGOTTEN_PASSWORD});
      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 resetPassword({phone, password, code})
        ElMessage.success('修改成功')
        user.loginType = LoginType.ACCOUNT_LOGIN;
      }catch (e) {
      }
      callBack && callBack()
    } else {
      // ElMessage.error('修改失败，请稍后重试')
      console.log('error submit!', fields);
      callBack && callBack()
    }
  });
}


</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>
