<script setup lang="ts">
import { loginModuleRecord } from '@/constants/app';
import { useRouterPush } from '@/hooks/common/router';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { useAuthStore } from '@/store/modules/auth';
import {useI18n} from "vue-i18n";


defineOptions({
  name: 'PwdLogin'
});
const { t } = useI18n();
const authStore = useAuthStore();
const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useAntdForm();
const { patternRules } = useFormRules();
const codeImg = ref('');


getCheckCode();

const model = reactive({
  username: 'admin',
  password: 'Admin123.',
  code: '',
  uuid: '',
  authType: 'sys'
});

const rules = {
  username: patternRules.username,
};

async function handleSubmit() {
  await validate();//验证表单内容
  await authStore.login({
    loginForm: model,//发送表单的数据
    onError() {
      getCheckCode();//重新获取验证码
    }
  });
}

async function getCheckCode() {
  const { data, error } = await doGetCheckCode();
  if (!error) {
    codeImg.value = `data:image/png;base64,${data.img}`;
    model.uuid = data.uuid;
    if (data?.text) {
      model.code = data.text;
    }
  }
}
</script>

<template>
  <AForm ref="formRef" :model="model" :rules="rules">
    <AFormItem name="username">
      <AInput v-model:value="model.username" size="large" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </AFormItem>
    <AFormItem name="password">
      <AInputPassword
        v-model:value="model.password"
        size="large"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </AFormItem>
    <AFormItem>
      <div class="flex gap-4">
        <AInput v-model:value="model.code" size="large" :placeholder="$t('page.login.common.checkCode')">
          <template #suffix></template>
        </AInput>
        <AImage :preview="false" :src="codeImg" @click="getCheckCode" />
      </div>
    </AFormItem>

    <ASpace direction="vertical" size="large" class="w-full">
      <div class="flex-y-center justify-between">
        <span></span>
        <AButton type="text" @click="toggleLoginModule('reset-pwd')">{{ t('page.login.pwdLogin.forgetPassword') }}</AButton>
      </div>
      <AButton type="primary" block size="large" shape="round" :loading="authStore.loginLoading" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </AButton>
<!--      <div class="flex-y-center justify-between">-->
<!--        <AButton class="h-34px flex-1" block @click="toggleLoginModule('code-login')">-->
<!--          {{ t(loginModuleRecord['code-login']) }}-->
<!--        </AButton>-->
<!--        <div class="w-12px"></div>-->
<!--        <AButton class="h-34px flex-1" block @click="toggleLoginModule('register')">-->
<!--          {{ t(loginModuleRecord.register) }}-->
<!--        </AButton>-->
<!--      </div>-->
    </ASpace>
  </AForm>
</template>

<style scoped></style>
