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

const user = userStore()
const ruleFormRef = ref<FormInstance>()

const form = reactive({
  username: '',
  password: '',
});
const buttonLoading = ref(false);

const debouncedSubmitForm = debounce(submitForm, 500);

/**
 * 提交表单并进行验证
 * @param formEl 表单实例
 * @param callBack 验证通过后的回调函数
 */
async function submitForm(formEl: FormInstance | undefined, callBack: () => void) {
  // 检查表单实例是否存在
  if (!formEl) {
    return;
  }
  // 表单验证
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const {username, password} = form;
      try {
        // 调用用户登录方法
        await user.login({username, password});
      } catch (error) {
        console.error('Login failed:', error);
      }
      // 如果有回调函数，执行回调
      callBack && callBack();
    } else {
      console.error('Form validation failed:', 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 v-model:phone="form.username"/> -->
        <AccountFormItem prop-name="username" v-model:phone="form.username"/>
        <!-- <PasswordFormItem v-model:password="form.password"/> -->
        <PasswordFormItem v-model:button-loading="buttonLoading"  @submit-click="debouncedSubmitForm(ruleFormRef, $event)" prop-name="password" v-model:password="form.password"/>
        <SubmitFormBtn v-model:button-loading="buttonLoading"  @submit-click="debouncedSubmitForm(ruleFormRef, $event)"/>
      </el-form>
      <div class="bf-login-footer-btn">
        <!-- <a class="forget-pwd" @click="user.loginType = LoginType.RESET_PASSWORD">忘记密码</a> -->
        <a class="sign-up" @click="user.loginType = LoginType.REGISTER">立即注册</a>
      </div>
      <!-- <div class="bf-login-process">
        <a class="wx-login" @click="user.loginType = LoginType.WECHAT_LOGIN"><img
            src="@/assets/components/common/login/wx-icon.png" style="background: rgba(107, 182, 87, 1);">微信登录</a>
        <a class="SMS-login" @click="user.loginType = LoginType.SMS_LOGIN"><img
            src="@/assets/components/common/login/SMS-icon.png">短信登录</a>
      </div> -->
    </div>
  </div>
</template>


<style scoped lang="scss">
</style>
