<template>
    <div class="login-container">
        <!-- 背景图片 -->
        <div class="background">
            <Welcome />
        </div>
        <!-- 登录框 -->
        <div class="login-box">
            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <span class="title">{{ title }}</span>
                    </div>
                </template>

                <el-form :model="form" label-width="80px">
                    <el-form-item label="用户名">
                        <el-input v-model="form.username" placeholder="请输入用户名" @blur="validateUsername"
                            @input="validateUsernameInput" clearable />
                    </el-form-item>

                    <el-form-item v-if="errors.username">
                        <div class="error-message">
                            {{ errors.username }}
                        </div>
                    </el-form-item>

                    <el-form-item label="密码">
                        <el-input v-model="form.password" type="password" placeholder="请输入密码" @blur="validatePassword"
                            @input="validatePasswordInput" show-password />
                    </el-form-item>
                    <el-form-item v-if="errors.password">
                        <div class="error-message">
                            {{ errors.password }}
                        </div>
                    </el-form-item>

                    <el-form-item v-if="registerEnable" label="确认密码">
                        <el-input v-model="form.duplicatePassword" type="password" placeholder="请再次输入密码"
                            @blur="validateDuplicatePassword" @input="validateDuplicatePasswordInput" show-password />
                    </el-form-item>
                    <el-form-item v-if="errors.duplicatePassword">
                        <div class="error-message">
                            {{ errors.duplicatePassword }}
                        </div>
                    </el-form-item>

                    <div v-if="registerEnable === false" class="button-group">
                        <el-button type="primary" :disabled="isSubmitting" @click="handleLogin">
                            {{ isSubmitting ? '登录中...' : '登录' }}
                        </el-button>
                        <el-button @click="handleStartRegister">注册</el-button>
                    </div>
                    <div v-if="registerEnable" class="button-group">
                        <el-button type="primary" :disabled="isSubmitting" @click="handleRegister">
                            {{ isSubmitting ? '注册中...' : '注册' }}
                        </el-button>
                        <el-button type="danger" @click="handleCancel">返回</el-button>
                    </div>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, inject } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElNotification } from 'element-plus'
import Welcome from '../welcome/welcome.vue'
import { postData } from '../../api/axios.js'
import svgIcon from '@/components/svgIcon.vue'


const useUserInfo = inject('userInfo');
const router = useRouter();

const form = ref({
    username: '',
    password: '',
    duplicatePassword: '',
})

const errors = ref({
    username: '',
    password: '',
    duplicatePassword: '',
})

let title = ref("用户登录");
const registerEnable = ref(false);
const isSubmitting = ref(false);

// 验证用户名
const validateUsername = () => {
    if (form.value.username.length < 5 || form.value.username.length > 12) {
        errors.value.username = '用户名长度需为5-12位'
    } else {
        errors.value.username = ''
    }
}

const validateUsernameInput = () => {
    if (form.value.username.length < 5 || form.value.username.length > 12) {
    } else {
        errors.value.username = ''
    }
}

// 验证密码
const validatePassword = () => {
    if (form.value.password.length < 6 || form.value.password.length > 20) {
        errors.value.password = '密码长度需为6-20位'
    } else {
        errors.value.password = ''
    }
}

const validatePasswordInput = () => {
    if (form.value.password.length < 6 || form.value.password.length > 20) {
    } else {
        errors.value.password = ''
    }
}

//验证确认密码
const validateDuplicatePassword = () => {
    if (form.value.duplicatePassword.length < 6 || form.value.duplicatePassword.length > 20) {
        errors.value.duplicatePassword = '密码长度需为6-20位'
    } else {
        if (form.value.duplicatePassword != form.value.password) {
            errors.value.duplicatePassword = '两次密码输入不同'
        } else {
            errors.value.duplicatePassword = ''
        }
    }
}
const validateDuplicatePasswordInput = () => {
    if (form.value.duplicatePassword.length < 6 || form.value.duplicatePassword.length > 20) {
    } else {
        if (form.value.duplicatePassword === form.value.password) {
            errors.value.duplicatePassword = ''
        }
    }
}

// 用于注册


const handleLogin = async () => {
    validateUsername()
    validatePassword()
    

    // 检查是否有错误
    if (errors.value.username || errors.value.password) {
        console.log("error")
        return
    }

    isSubmitting.value = true;
    useUserInfo.login(form.value.username, form.value.password).then( loginResult => {
        form.value.username = ''
        form.value.password = ''
        if (loginResult.status === 'success'){
            ElNotification({
                title: '登录成功',
                message: '现在您可以开始使用各项功能了',
                type: 'success',
            })
            router.push({
                name: 'select',
            });
        }else{
            ElNotification({
                title: '登录失败',
                message: loginResult.message,
                type: 'error',
            })
        }
        isSubmitting.value = false;
    });
}

const handleStartRegister = () => {
    registerEnable.value = true;
    title.value = "用户注册"
}

const handleRegister = async () => {
    validateUsername()
    validatePassword()
    validateDuplicatePassword()

    // 检查是否有错误
    if (errors.value.username || errors.value.password || errors.value.duplicatePassword) {
        console.log("error")
        return
    }

    isSubmitting.value = true;
    useUserInfo.register(form.value.username, form.value.password).then( registerResult => {
        form.value.username = ''
        form.value.password = ''
        form.value.duplicatePassword = ''
        console.log(registerResult)
        if (registerResult.status === 'success'){
            ElNotification({
                title: '注册成功',
                message: '现在您可以开始使用各项功能了',
                type: 'success',
            })
            router.push({
                name: 'select',
            });
        }else{
            ElNotification({
                title: '注册失败',
                message: registerResult.message,
                type: 'error',
            })
        }
        isSubmitting.value = false;
    });
}

const handleCancel = () => {
    registerEnable.value = false;
    title.value = "用户登录";
    Object.keys(form.value).forEach(key => form.value[key] = '');
    Object.keys(errors.value).forEach(key => errors.value[key] = '');
}
</script>

<style scoped>
.login-container {
    position: relative;
    height: 100vh;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 15%;
}

.background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('https://source.unsplash.com/random/1920x1080');
    background-size: cover;
    background-position: center;
    filter: brightness(0.8);
    z-index: 0;
}

.login-box {
    position: relative;
    z-index: 1;
    width: 400px;
}

.box-card {
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(5px);
    border-radius: 8px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
    text-align: center;
}

.title {
    font-size: 1.5rem;
    font-weight: bold;
    color: #303133;
}

.button-group {
    display: flex;
    justify-content: space-between;
    margin-top: 2rem;
}

.el-button {
    flex: 1;
    margin: 0 8px;
}

.error-message {
    color: #dc3545;
    line-height: 12px !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .login-container {
        padding-right: 5%;
        justify-content: center;
    }

    .login-box {
        width: 90%;
    }
}
</style>