<template>
  <a-form ref="formRef" :model="formState" name="normal_login" class="login-form" @finish="onFinish"
    @finish-failed="onFinishFailed" style="margin-top: 45px;">
    <a-form-item label="手机号" name="phone" :rules="[{ required: true, message: '请输入手机号！' }]">
      <SmsCodeInput v-model:value="formState.phone" />
    </a-form-item>
    <!-- 手动控制密码字段的错误状态 -->
    <a-form-item label="验证码" name="code" :rules="[{ required: true, message: '请输入验证码！' }]">
      <a-input v-model:value="formState.code" placeholder="请输入验证码" />
    </a-form-item>
    <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入8~16位，且包含字母和数字！'},{validator: validatePassword }]">
      <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
    </a-form-item>
    <a-form-item>
      <a-button type="primary" html-type="submit" block class="login-form-button">
        注 册
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { reactive, ref, shallowRef, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import apis from '@/apis';
import { message, type FormInstance } from 'ant-design-vue';
import SmsCodeInput from '@/components/SmsCodeInput.vue';
import { validatePassword } from '@/utils/validotors'; // 根据实际路径调整
const router = useRouter();
const formRef = ref<FormInstance>();

const codeValidateStatus = shallowRef<'success' | 'warning' | 'error' | ''>('');
const codeHelp = shallowRef('');

interface FormState {
  phone: string;
  code: string;
  password: string;
}

const formState = reactive<FormState>({
  phone: '',
  code: '',
  password: '',
});

const clearCodeError = () => {
  codeValidateStatus.value = '';
  codeHelp.value = '';
};

const onFinish = async (values: FormState) => {
  clearCodeError();
  const loginData = {
    ...values,
  };
  formRef.value?.validateFields().then(async () => {
    try {
      const res: any = await apis.login.register(loginData);
      console.log('注册请求成功:', res);
      message.success('注册成功，请登录');
    } catch (error: any) {
      console.error('注册请求失败:', error);
      message.error(error);
    }
  });

};

const onFinishFailed = (errorInfo: any) => {
  console.log('表单验证失败:', errorInfo);
};
</script>