<template>
  <a-form ref="formRef" :model="formState" name="normal_login" class="login-form" @finish="onFinish"
    @finish-failed="onFinishFailed">
    <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>
      <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 { login, fetchUserInfo } from '@/apis/modules/login';
import { message, type FormInstance } from 'ant-design-vue';
import SmsCodeInput from '@/components/SmsCodeInput.vue';
const router = useRouter();
const formRef = ref<FormInstance>();

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

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

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

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

const onFinish = async (values: FormState) => {
  clearCodeError();
  const loginData = {
    ...values,
    login_method: 'SMS'//PWD表示密码登录，SMS表示短信验证码登录
  };
  formRef.value?.validateFields().then(async () => {
    try {
      const res: any = await login(loginData);
      console.log('登录请求成功:', res);
      // 登录成功后，将token存入localStorage
      const token = res?.access_token;
      if (!token) {
        throw new Error('登录失败：未返回有效凭证');
      }
      localStorage.setItem('token', token);
      const userRes = await fetchUserInfo();
      localStorage.setItem('userInfo', JSON.stringify(userRes));
      router.push('/layout/home');
    } catch (error: any) {
      console.error('登录请求失败:', error);
      message.error(error || '用户名或密码错误');
    }
  });

};

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