<template>
    <Modal v-model="showFormModal" :footer-hide="true" class="login-modal">
        <div style="padding-top: 30px;"></div>
        <Login v-if="signInOrSignUp" @on-submit="handleSignIn">
            <UserName name="username" />
            <Password name="password" />
            <div class="auto-login">
                <Checkbox v-model="autoLogin" size="large">记住登录状态</Checkbox>
                <!-- <a>忘记密码</a> -->
            </div>
            <Submit :loading="submitLoading" />
            <Space split>还未拥有账号？<Button type="text" @click="signInOrSignUp = false">前往注册</Button></Space>
        </Login>
        <Login v-else @on-submit="handleSignUp">
            <UserName name="username" />
            <Email name="mail" />
            <Password name="password" />
            <Password name="passwordConfirm" placeholder="确认密码" />
            <Submit :loading="submitLoading">注册</Submit>
            <Space split>已经拥有账号？<Button type="text" @click="signInOrSignUp = true">前往登录</Button></Space>
        </Login>
    </Modal>
</template>

<script setup>
import { SignIn, SignUp, SendSignUpEmail, CheckLoginStatus, Logout } from '/src/utils/userHandler';
import { ref, watch, onMounted } from "vue";
import { Message } from 'view-ui-plus';

const props = defineProps({
    visible: {
        type: Boolean,
        required: true,
        default: false,
    },
    loginStatus: {
        type: Boolean,
        required: true,
        default: false,
    },
});

const emit = defineEmits([
    'update:visible',
    'update:loginStatus',
]);

// 是否弹出对话框。要求双向绑定
const showFormModal = ref(props.visible);
watch(() => props.visible, (visible) => {
    showFormModal.value = visible;
})
watch(showFormModal, (visible) => {
    emit('update:visible', visible);
})

const signInOrSignUp = ref(true);
const autoLogin = ref(false);
const submitLoading = ref(false);

const handleSignIn = (valid, { username, password }) => {
    if (!valid) {
        return;
    }
    submitLoading.value = true;
    SignIn(username, password, autoLogin.value)
        .then((data) => {
            Message.success('登录成功');
            // 将登录成功的状态通知父组件
            emit('update:loginStatus', true);
            // 停止 loading，关闭对话框
            submitLoading.value = false;
            showFormModal.value = false;
        })
        .catch((error) => {
            submitLoading.value = false;
            Message.error(`登录发生异常: ${error}`);
        });
};

const handleSignUp = (valid, { username, mail, password, passwordConfirm }) => {
    if (!valid) {
        return;
    }
    if (passwordConfirm !== password) {
        Message.error('输入的密码不一致，请重新输入');
        return;
    }

    submitLoading.value = true;
    SignUp(username, mail, password)
        .then((data) => {
            // 注册后会返回一个 userID，用于发送激活邮件
            SendSignUpEmail(data.id)
                .then((data) => {
                    Message.success('请前往邮箱激活账号(没收到的话检查垃圾箱)，激活后再回来登录账号');
                    // 发送邮件成功，（从注册界面）回到登录窗口
                    submitLoading.value = false;
                    signInOrSignUp.value = true;
                })
                .catch((error) => {
                    submitLoading.value = false;
                    Message.error(`发送激活邮件发生异常: ${error}`);
                });
        })
        .catch((error) => {
            submitLoading.value = false;
            Message.error(`注册发生异常: ${error}`);
        });
};

const checkLoginStatus = async () => {
    CheckLoginStatus()
        .then((data) => {
            emit('update:loginStatus', true);
        })
        .catch((error) => {
            Message.error(`检查登录状态发生异常: ${error}`);
        });
}

const logout = async () => {
    Logout()
        .then((data) => {
            Message.info('登出成功');
            emit('update:loginStatus', false);
        })
        .catch((error) => {
            Message.error(`登出发生异常: ${error}`);
        });
}

defineExpose({
    logout,
})

onMounted(async () => {
    // 检查是否已登录
    checkLoginStatus();
});
</script>

<style scoped>
.login-modal {
    width: 400px;
    margin: 0 auto !important;
}

.auto-login {
    margin-bottom: 24px;
    text-align: left;
}

.auto-login a {
    float: right;
}
</style>
