<script setup lang="ts">
import { reactive, ref } from "vue";
import type {
  ICommonResponse,
  IUserLoginData,
  IUserLoginRequest
} from "#shared/types";
import { useUserStore } from "~/stores";

type FormRef = {
  validate: () => Promise<boolean>;
  resetFields: () => void;
};

const emit = defineEmits<{
  success: [response: ICommonResponse<IUserLoginData>];
}>();

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const { isOnline, getUserInfoLoading } = storeToRefs(userStore);
const formRef = ref<FormRef>();

const form = reactive<Required<IUserLoginRequest>>({
  username: "",
  password: ""
});

const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
};

const submit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  const response = await userStore.login({
    username: form.username.trim(),
    password: form.password
  });

  if (response?.code === 0) {
    emit("success", response);
  }
};

const resetForm = () => {
  formRef.value?.resetFields();
};

const goToRegister = () => {
  router.replace({
    query: {
      ...route.query,
      _loginAction: "signUp"
    }
  });
};

defineExpose({
  resetForm
});
</script>

<template>
  <div class="w-full max-w-sm">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      @submit.prevent="submit"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="form.username"
          autocomplete="username"
          placeholder="请输入用户名"
          size="large"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          autocomplete="current-password"
          placeholder="请输入密码"
          show-password
          size="large"
          type="password"
          @keyup.enter="submit"
        />
      </el-form-item>

      <el-button
        class="w-full"
        native-type="submit"
        size="large"
        type="primary"
        :loading="userStore.loginLoading"
        :disabled="getUserInfoLoading || isOnline"
      >
        登录
      </el-button>
    </el-form>

    <div class="mt-4 text-center text-sm">
      没有账户？
      <span class="cursor-pointer text-blue-600" @click="goToRegister">
        注册
      </span>
    </div>
  </div>
</template>
