<template>
  <n-form ref="formRef" :model="model" size="large" :show-label="false">
    <n-form-item path="phone">
      <n-input v-model:value="model.phone" placeholder="请输入用户名" />
    </n-form-item>
    <n-form-item path="pwd">
      <n-input v-model:value="model.pwd" type="password" show-password-on="click" placeholder="请输入密码" />
    </n-form-item>

    <n-form-item class="relative" path="code">
      <n-input v-model:value="model.code" placeholder="请输入验证码" />
      <img class="absolute right-1 top-1 h-full cursor-pointer rounded-tr-4px rounded-br-4px h-32px" :src="loginCodeUrl"
        alt="" @click="handleGetLoginCode" />
    </n-form-item>

    <n-space :vertical="true" :size="24">
      <n-button type="primary" color="#29B6FD" size="large" :block="true" :loading="auth.loginLoding" strong
        @click="handleSubmit">
        登 录
      </n-button>
    </n-space>
  </n-form>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import type { FormInst } from 'naive-ui';
import { useAuthStore } from '@/store';
import { getLoginCode } from '@/service';

const auth = useAuthStore();
const { login } = useAuthStore();

const formRef = ref<(HTMLElement & FormInst) | null>(null);
const model = reactive({
  phone: '',
  pwd: '',
  code: '',
  uuid: ''
});

onMounted(() => {
  handleGetLoginCode();
});

const loginCodeUrl = ref('');
/** 获取login code */
async function handleGetLoginCode() {
  const { data } = await getLoginCode();
  const codeData = data as any;
  if (codeData) {
    loginCodeUrl.value = `data:image/gif;base64,${codeData.data.img}`;
    model.uuid = codeData.data.uuid;
  }
}

/** 提交login表单 */
function handleSubmit(e: MouseEvent) {
  if (!formRef.value) return;
  e.preventDefault();

  formRef.value.validate(errors => {
    if (!errors) {
      const { phone, pwd, uuid, code } = model;
      login(phone, pwd, uuid, code, (errorData: any) => {
        if (errorData) {
          handleGetLoginCode();
          model.code = '';
        }
      });
    }
  });
}
</script>
<style scoped></style>
