<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: '请输入用户名！' }]">
      <a-input v-model:value="formState.phone" placeholder="请输入账号"/>
    </a-form-item>
    <!-- 手动控制密码字段的错误状态 -->
    <a-form-item label="密码" name="code" :help="codeHelp" :rules="[{ required: true, message: '请输入密码！' }]">
      <a-input-password 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 } from 'vue';
import { useRouter } from 'vue-router';
import { login, fetchUserInfo } from '@/apis/modules/login';
import { message, type FormInstance } from 'ant-design-vue';

const router = useRouter();
const formRef = ref<FormInstance>();

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

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

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

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

const setCodeError = (msg: string) => {
  codeValidateStatus.value = 'error';
  codeHelp.value = msg;
};

const onFinish = async (values: FormState) => {
  clearCodeError();

  const loginData = {
    ...values,
    login_method: 'PWD'//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>