<script setup lang="ts">
import { computed, ref } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({ name: 'PwdLogin' });

const authStore = useAuthStore();
const { formRef, validate } = useForm();

interface FormModel {
  userName: string;
  password: string;
}

const model = ref<FormModel>({
  userName: '',
  password: ''
});

const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  // inside computed to make locale ref, if not apply i18n, you can define it without computed
  const { formRules } = useFormRules();

  return {
    userName: formRules.userName,
    password: formRules.pwd
  };
});

async function handleSubmit() {
  await validate();
  await authStore.login(model.value.userName, model.value.password);
}
</script>

<template>
  <ElForm ref="formRef" :model="model" :rules="rules" size="large" @keyup.enter="handleSubmit">
    <ElFormItem prop="userName">
      <ElInput v-model="model.userName" :placeholder="$t('page.login.common.userNamePlaceholder')">
        <template #prefix>
          <SvgIcon icon="mdi:account-outline" />
        </template>
      </ElInput>
    </ElFormItem>
    <ElFormItem prop="password">
      <ElInput
        v-model="model.password"
        type="password"
        show-password
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      >
        <template #prefix>
          <SvgIcon icon="mdi:lock-outline" />
        </template>
      </ElInput>
    </ElFormItem>
    <ElButton
      type="primary"
      size="large"
      class="login-submit-button"
      :loading="authStore.loginLoading"
      @click="handleSubmit"
    >
      {{ $t('route.login') }}
    </ElButton>
  </ElForm>
</template>

<style scoped></style>
