<template>
    <div class="blog">
        <el-container>
            <el-header>
                <el-menu :default-active="activeMenu" mode="horizontal" :ellipsis="false" class="menu"
                    menu-trigger="click">
                    <router-link to="/"><el-menu-item index="1">首页</el-menu-item></router-link>
                    <router-link to="/articles"><el-menu-item index="2">文章</el-menu-item></router-link>
                    <!-- <router-link><el-menu-item index="3">联系站长</el-menu-item></router-link> -->
                    <el-sub-menu index="4" class="sub-menu">
                        <template #title>
                            在线应用
                        </template>
                        <router-link to="/myplayer">
                            <el-menu-item index="4-1">MyPlayer</el-menu-item>
                        </router-link>
                    </el-sub-menu>

                    <div class="login-btn">
                        <div class="login" @click="blogLogin()">{{ u_name }}</div>
                    </div>
                </el-menu>
            </el-header>
            <el-main>
                <div class="blog-content">
                    <router-view />
                </div>
            </el-main>
            <el-footer style="text-align: right;">
                <!-- <p>© 2025 烛火创意科技 保留所有权利</p> -->
                <p>粤ICP备2025400740-1号</p>
            </el-footer>
        </el-container>
    </div>

    <!-- 用户登录、注册弹窗 -->
    <el-dialog title="用户登录" v-model="loginDialog" style="min-width: 400px; max-width: 500px;">
        <el-form :model="loginInfo" label-width="auto" style="width: 100%;" :rules="isadmin ? null : rules">
            <el-form-item label="账号or邮箱" prop="account">
                <el-input v-model="loginInfo.account"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginInfo.password" type="password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="isadmin">管理员登录</el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button @click="login()">登录</el-button>
                <!-- <el-button @Click="goToRegister()" type="primary">注册</el-button> -->
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog title="用户注册" v-model="registDialog" style="min-width: 400px; max-width: 500px;">
        <el-form ref="formRef" :model="loginInfo" label-width="auto" style="width: 100%;" :rules="rules">
            <el-form-item label="邮箱" prop="account">
                <el-input v-model="loginInfo.account"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="loginInfo.password" type="password"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="password_confirm">
                <el-input v-model="loginInfo.password_confirm" type="password"></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
                <el-input v-model="loginInfo.code" style="width: 50%; margin-right: 10px" />
                <el-button :disabled="countdown > 0" @click="getCode()">
                    {{ countdown > 0 ? `${countdown}s 后重试` : '获取验证码' }}
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-button style="margin-left: auto;" type="primary" @click="submitForm">注册</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>

</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { userInfoStore } from '@/store/store';
import { getUserInfo } from '@/function/user';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const userinfo = userInfoStore();
const activeMenu = ref('1');
const u_name = ref('')

// 控制登录弹窗的显示与隐藏
const loginDialog = ref(false);
const registDialog = ref(false);

const isadmin = ref(false);

const route = useRoute(); // 获取当前路由信息
const router = useRouter(); // 获取路由实例

const formRef = ref(null); // 用于表单验证的引用

const loginInfo = reactive({
    account: '',
    password: '',
    password_confirm: '',
    code_id: '',
    code: ''
})
const hashpassword = ref('')

const countdown = ref(0);
let timer = null;

const rules = reactive({
    account: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'blur' }
    ],
    password_confirm: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== loginInfo.password) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ]
});

// 根据当前路由设置 activeMenu
const updateActiveMenu = () => {
    switch (route.path) {
        case '/':
            activeMenu.value = '1';
            break;
        case '/about':
            activeMenu.value = '2';
            break;
        case '/contact':
            activeMenu.value = '3';
            break;
        case '/myplayer':
            activeMenu.value = '4';
            break;
        default:
            activeMenu.value = '1'; // 默认选中首页
    }
};

// 初始化时设置 activeMenu
updateActiveMenu();

// 监听路由变化，动态更新 activeMenu
watch(route, () => {
    updateActiveMenu();
});

const blogLogin = () => {
    if (userinfo.user.role === 'admin') {
        const origin = window.location.origin
        const redirect_uri = `${origin}/admin`
        window.open(redirect_uri, '_blank')
    }
    if (u_name.value === '登录') {
        loginDialog.value = true;
    } else {
        router.push('/me')
    }

}

const goToRegister = () => {
    loginDialog.value = false;
    registDialog.value = true;
}

const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            register()
        } else {
            console.log('error submit!!')
            return false
        }
    })
}

const login = async () => {
    if (isadmin.value) {
        const response = await axios.post('/api/login', {
            account: loginInfo.account,
            password: loginInfo.password
        })
        if (!response.data.code == 200) {
            ElMessage.error(response.data.message)
            return
        } else {
            userinfo.token = response.data.data.token
            userinfo.user.account = loginInfo.account
            loginDialog.value = false;
            userinfo.user.name = response.data.data.userInfo.name
            userinfo.user.role = response.data.data.role
            u_name.value = userinfo.user.name
            const origin = window.location.origin
            const redirect_uri = `${origin}/admin`
            window.open(redirect_uri, '_blank')
        }
    } else {
        const response = await axios.post('/api/login', {
            account: loginInfo.account,
            password: loginInfo.password
        }).then((response) => {
            console.log(response.data);
            if (response.data.code == 200) {
                userinfo.token = response.data.data.token;
                userinfo.user.name = response.data.data.userInfo.name
                u_name.value = userinfo.user.name
                loginDialog.value = false;
                ElMessage.success('登录成功');
            } else {
                ElMessage.error(response.data.msg)
            }
        })
    }


}

const register = async () => {
    ElMessage.success('注册成功');
}


const startCountdown = () => {
    countdown.value = 60
    timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0 && timer) {
            clearInterval(timer)
        }
    }, 1000)
}
const getCode = async () => {
    if (countdown.value > 0) return

    // 此处调用你的发送验证码接口逻辑
    // 例如 axios.post('/api/code', { email: loginInfo.value.account })

    // 成功后开始倒计时
    startCountdown()
}

watch(u_name,u_name.value=userinfo.token === null?'登录':userinfo.user.name,{ immediate: true })


</script>

<style>
.blog {
    width: 100vw;
    height: 100vh;
}

.el-header {
    margin: auto;
    padding: 0;
    width: 100%;
}

.el-container {
    width: 100%;
    height: 100%;
}

.blog-content {
    width: 80%;
    margin: auto;
    height: 100%;
}


.menu {
    width: 100%;
    display: flex;
    background-color: #727272;
    border-radius: 13px;
    height: 62px;
    align-items: center;
}

.el-sub-menu__title {
    border-radius: 15px;
    color: #ffffff !important;
}

.el-sub-menu__title:hover {
    border-radius: 15px;
    color: #000000 !important;
    background-color: #ececec;
}

.menu .el-menu-item {
    border-radius: 15px;
    color: #ffffff !important;
}

.menu .el-menu-item:hover {
    background-color: #ececec !important;
    color: #000000 !important;
}

.menu .el-menu-item.is-active {
    text-decoration: underline !important;
    background-color: #444444 !important;
}


.login-btn {
    display: flex;
    align-items: center;
    margin-left: auto;
    height: 100%;
}

.login {
    color: #ffffff;
    cursor: pointer;
    padding: 5px 10px;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.login:hover {
    background-color: #ececec;
    color: #000000;
}

@media (max-width: 767px) {
    .blog-content {
        width: 100%;
        margin: auto;
        height: 100%;
    }

    /* .login-btn {
        display: none;
    } */
}
</style>