<script setup lang="ts">
import {ref, reactive} from 'vue';
import {MessagePlugin} from 'tdesign-vue-next';
import type {FormProps, FormInstanceFunctions, InputProps} from 'tdesign-vue-next';
import {useUserStore} from "@/store";
import router from "@/router";

const FORM_RULES: FormProps['rules'] = {
    code: [
        {
            required: true,
            message: '账号必填',
        }
    ],
    password: [
        {
            required: true,
            message: '密码必填',
        }
    ]
};
const formData: FormProps['data'] = reactive({
    code: '',
    password: '',

});
const form = ref<FormInstanceFunctions>(null!);
const rememberLogin = ref(false);
const userStore = useUserStore();
userStore.logout();
const logIn = ref(false);
const onSubmit: FormProps['onSubmit'] = async ({validateResult, firstError}) => {
    logIn.value = true;
    if (validateResult === true) {
        await login();
    } else {
        console.log('Validate Errors: ', firstError, validateResult);
        await MessagePlugin.warning(firstError!);
    }
    logIn.value = false;
};


async function login() {
    useUserStore().user = formData!.code;
    useUserStore().login();
    await MessagePlugin.success('登录成功');
    await router.replace({path: '/base'})
}
// 禁用 Input 组件，按下 Enter 键时，触发 submit 事件
const onEnter: InputProps['onEnter'] = (_, {e}) => {
    e.preventDefault();
};
</script>


<template>
    <t-form :class="{form:true}" ref="form" :rules="FORM_RULES" :data="formData" :colon="true" :required-mark=false
            @submit="onSubmit">
        <t-form-item name="code">
            <t-input v-model="formData.code" size='large' placeholder="请输入账号" @enter="onEnter"></t-input>
        </t-form-item>
        <t-form-item name="password">
            <t-input v-model="formData.password" size='large' placeholder="请输入密码" type="password"/>
        </t-form-item>
        <t-form-item>
            <t-checkbox :model="rememberLogin">记住账号</t-checkbox>
        </t-form-item>

        <t-form-item>
            <t-space size="small">
                <t-button :disabled="logIn" theme="primary" type="submit" size="large">登录</t-button>
            </t-space>
        </t-form-item>
    </t-form>
</template>

<style scoped>
.form {
    margin-right: 10vh;
}
</style>