<template>
    <div class="app-header">
        <div class="header-content">
            <div class="logo">
                <router-link to="/">
                    <el-icon class="logo-icon" :size="24"><Reading /></el-icon>
                    <span>瀚海中文网</span>
                </router-link>
            </div>
            <div class="menu">
                <el-menu 
                    mode="horizontal" 
                    :ellipsis="false" 
                    background-color="#0A2463" 
                    text-color="#fff"
                    active-text-color="#fff" 
                    :router="true"
                    :default-active="activeMenu"
                >
                    <el-menu-item index="/">精品推荐</el-menu-item>
                    <!-- 动态渲染分类菜单 -->
                    <el-menu-item 
                        v-for="category in navigationCategories" 
                        :key="category.id"
                        :index="'/category/' + category.id"
                    >
                        {{ category.title }}
                    </el-menu-item>
                    <el-menu-item index="/ranking">排行榜</el-menu-item>
                    <el-menu-item index="/category">其他</el-menu-item>
                    <el-menu-item index="/bookshelf" @click="goToBookshelf">书架</el-menu-item>
                    <el-menu-item index="/author" @click="goToAuthorCenter">作家专区</el-menu-item>
                </el-menu>
            </div>
            
            <div class="search-box">
                <el-input 
                    placeholder="请输入关键词搜索" 
                    v-model="searchKeyword" 
                    class="search-input"
                >
                    <template #append>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                    </template>
                </el-input>
            </div>
            
            <div class="user-info">
                <div class="notification" @click="goToMessages">

                    <div class="notification-badge" v-if="unreadMessageCount == 0">
                        <el-icon><Bell /></el-icon>
                    </div>

                    <el-badge :value="unreadMessageCount" class="notification-badge" v-else>
                        <el-icon><Bell /></el-icon>
                    </el-badge>
                </div>
                
                <el-button v-if="!isLoggedIn" type="primary" @click="goToLogin" plain>登录/注册</el-button>
                <el-dropdown v-else trigger="click" placement="bottom-end">
                    <div class="user-dropdown-link">
                        <el-avatar :size="32" :src="userAvatar" />
                        <span class="username">{{ userName }}</span>
                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </div>
                    <template #dropdown>
                        <el-dropdown-menu class="user-dropdown-menu">
                            <div class="user-info-card" @click="goToUserCenter">
                                <div class="user-avatar-wrapper">
                                    <el-avatar :size="48" :src="userAvatar" />
                                </div>
                                <div class="user-info-details">
                                    <div class="user-name">{{ userName }}</div>
                                    <div class="user-bean">豆豆: {{ integerPrice }}</div>
                                </div>
                                <div class="user-arrow">
                                    <el-icon><arrow-right /></el-icon>
                                </div>
                            </div>
                            
                            <!-- <el-dropdown-item class="menu-item" @click="goToGiftBox">
                                <el-icon><GiftBox /></el-icon>
                                <span>礼物盒</span>
                            </el-dropdown-item> -->
                            
                            <el-dropdown-item class="menu-item" @click="goToTaskCenter">
                                <el-icon><List /></el-icon>
                                <span>任务中心</span>
                            </el-dropdown-item>
                            
                            <el-dropdown-item class="menu-item" @click="applyForAuthor">
                                <el-icon><Star /></el-icon>
                                <span>{{ store.isAuthor ? '修改作家信息' : '申请成为创作者'}}</span>
                            </el-dropdown-item>
                            
                            <el-dropdown-item class="menu-item" @click="goToMoneyLog">
                                <el-icon><Wallet /></el-icon>
                                <span>钱包流水</span>
                            </el-dropdown-item>
                            
                            <el-dropdown-item class="menu-item" @click="logout">
                                <el-icon><SwitchButton /></el-icon>
                                <span>退出登录</span>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
        </div>
        
        <!-- 个人信息弹窗 -->
        <PersonalInfoModal
            v-model="showPersonalInfoModal"
            @success="handlePersonalInfoUpdate"
        />
    </div>
</template>

<script>
import { ref, computed, inject, h, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useMainStore } from '@/store';
import { ArrowDown, ArrowRight, Bell, Reading, List, Star, Wallet, SwitchButton } from '@element-plus/icons-vue';
import { AUTH_INJECTION_KEY } from '@/components/auth/AuthProvider.vue';
import { AUTHOR_APPLICATION_INJECTION_KEY } from '@/components/auth/AuthorApplicationProvider.vue';
import PersonalInfoModal from '@/components/common/PersonalInfoModal.vue';

export default {
    name: 'AppHeader',
    components: {
        ArrowDown,
        ArrowRight,
        Bell,
        Reading,
        List,
        Star,
        Wallet,
        SwitchButton,
        PersonalInfoModal,
        GiftBox: {
            render() {
                return h('svg', {
                    viewBox: '0 0 1024 1024',
                    width: '1em',
                    height: '1em'
                }, [
                    h('path', {
                        fill: 'currentColor',
                        d: 'M832 192H192c-35.3 0-64 28.7-64 64v512c0 35.3 28.7 64 64 64h640c35.3 0 64-28.7 64-64V256c0-35.3-28.7-64-64-64zM766.7 317.3l-210.8 290c-5.7 7.9-14.8 12.6-24.5 12.6s-18.8-4.7-24.5-12.6l-210.8-290c-6.3-8.6-7.2-20.1-2.6-29.8 4.6-9.7 14.3-15.8 25-15.8h425.8c10.7 0 20.4 6.1 25 15.8 4.6 9.7 3.7 21.2-2.6 29.8z'
                    })
                ]);
            }
        }
    },
    setup() {
        const router = useRouter();
        const route = useRoute();
        const store = useMainStore();
        const searchKeyword = ref('');
        const showPersonalInfoModal = ref(false);
        
        // 注入身份验证上下文
        const authContext = inject(AUTH_INJECTION_KEY);
        // 注入作者申请上下文
        const authorApplicationContext = inject(AUTHOR_APPLICATION_INJECTION_KEY);
        
        // 获取用户信息
        const isLoggedIn = computed(() => store.isAuthenticated);
        const userName = computed(() => store.user?.nickName || '未知昵称');
        const userAvatar = computed(() => store.user?.headImage || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png');
        const integerPrice = computed(() => store.user?.integerPrice || '0');
        const unreadMessageCount = computed(() => store.unreadMessageCount || 0);
        
        // 获取分类信息
        const navigationCategories = computed(() => store.navigationCategories);
        
        // 获取当前活动的菜单项
        const activeMenu = computed(() => {
            // 如果是子路由，返回父路由路径
            if (route.path.includes('/book/') || route.path.includes('/user/')) {
                return '/' + route.path.split('/')[1];
            }
            return route.path;
        });

        // 搜索处理
        const handleSearch = () => {
            if (searchKeyword.value.trim()) {
                router.push({
                    path: '/search',
                    query: {
                        q: searchKeyword.value.trim()
                    }
                });
            }
        };

        const goToLogin = () => {
            // 打开登录弹窗
            authContext.openLogin();
        };

        const goToUserCenter = () => {
            showPersonalInfoModal.value = true;
        };

        // 处理个人信息更新成功
        const handlePersonalInfoUpdate = () => {
            // 刷新用户信息
            store.fetchUserInfo();
        };
        
        const goToBookshelf = () => {
            // 检查是否登录，如果未登录则打开登录弹窗
            if (!isLoggedIn.value) {
                authContext.openLogin(() => {
                    router.push('/bookshelf');
                });
                return;
            }
            router.push('/bookshelf');
        };
        
        const goToSettings = () => {
            router.push('/user/settings');
        };

        const logout = () => {
            store.logout();
            router.push('/');
        };

        // 申请成为创作者
        const applyForAuthor = () => {
            // 检查是否登录，如果未登录则先打开登录弹窗
            if (!isLoggedIn.value) {
                authContext.openLogin(() => {
                    authorApplicationContext.openApplicationModal();
                });
                return;
            }
            // 已登录，直接打开申请弹窗
            authorApplicationContext.openApplicationModal();
        };
        
        // 前往礼物盒
        const goToGiftBox = () => {
            // 检查是否登录，如果未登录则打开登录弹窗
            if (!isLoggedIn.value) {
                authContext.openLogin(() => {
                    router.push('/gift-box');
                });
                return;
            }
            router.push('/gift-box');
        };
        
        // 前往任务中心
        const goToTaskCenter = () => {
            // 检查是否登录，如果未登录则打开登录弹窗
            if (!isLoggedIn.value) {
                authContext.openLogin(() => {
                    router.push('/task-center');
                });
                return;
            }
            router.push('/task-center');
        };
        
        // 前往作家专区
        const goToAuthorCenter = () => {
            // 检查是否登录
            if (!isLoggedIn.value) {
                // 未登录，打开登录弹窗
                authContext.openLogin(() => {
                    // 登录成功后检查是否是作家
                    if (!store.isAuthor) {
                        // 不是作家，打开申请弹窗
                        authorApplicationContext.openApplicationModal(() => {
                            router.push('/author');
                        });
                    } else {
                        // 是作家，直接跳转
                        router.push('/author');
                    }
                });
                return;
            }
            
            // 已登录，检查是否是作家
            if (!store.isAuthor) {
                // 不是作家，打开申请弹窗
                authorApplicationContext.openApplicationModal(() => {
                    router.push('/author');
                });
            } else {
                // 是作家，直接跳转
                router.push('/author');
            }
        };

        // 前往消息页面
        const goToMessages = () => {
            // 检查是否登录，如果未登录则打开登录弹窗
            if (!isLoggedIn.value) {
                authContext.openLogin(() => {
                    // 根据未读消息数量决定默认显示的tab
                    const defaultTab = unreadMessageCount.value > 0 ? 'replyToMe' : 'myComments';
                    router.push({
                        path: '/messages',
                        query: { tab: defaultTab }
                    });
                });
                return;
            }
            // 根据未读消息数量决定默认显示的tab
            const defaultTab = unreadMessageCount.value > 0 ? 'replyToMe' : 'myComments';
            router.push({
                path: '/messages',
                query: { tab: defaultTab }
            });
        };
        
        // 前往钱包流水页面
        const goToMoneyLog = () => {
            // 检查是否登录，如果未登录则打开登录弹窗
            if (!isLoggedIn.value) {
                authContext.openLogin(() => {
                    router.push('/money-log');
                });
                return;
            }
            router.push('/money-log');
        };

        // 组件挂载时获取分类数据和未读消息数量
        onMounted(async () => {
            try {
                await store.fetchCategories();
                // 如果已登录，获取未读消息数量
                if (isLoggedIn.value) {
                    await store.getUnreadMessages();
                }
            } catch (error) {
                console.error('获取数据失败:', error);
            }
        });

        return {
            isLoggedIn,
            userName,
            userAvatar,
            integerPrice,
            activeMenu,
            searchKeyword,
            navigationCategories,
            showPersonalInfoModal,
            handleSearch,
            goToLogin,
            goToUserCenter,
            handlePersonalInfoUpdate,
            goToBookshelf,
            goToGiftBox,
            goToTaskCenter,
            goToSettings,
            logout,
            applyForAuthor,
            goToAuthorCenter,
            router,
            goToMessages,
            goToMoneyLog,
            unreadMessageCount,
            store,
        };
    }
};
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as vars;
@use 'sass:color';

.app-header {
    background-color: #0A2463;
    color: #fff;
    height: 3.75rem;  // 60px -> 3.75rem
    box-shadow: 0 0.125rem 0.625rem rgba(0,0,0,0.3);  // 2px 10px -> 0.125rem 0.625rem
    
    .header-content {
        display: flex;
        align-items: center;
        height: 100%;
        width: 1400px;
        margin: 0 auto;
        padding: 0 1.25rem;  // 20px -> 1.25rem
    }
    
    .logo {
        font-size: 1.2rem;  // 22px -> 1.375rem
        font-weight: bold;
        margin-right: 1.25rem;  // 20px -> 1.25rem
        
        a {
            color: #fff;
            text-decoration: none;
            display: flex;
            align-items: center;
            
            .logo-icon {
                margin-right: 0.5rem;  // 8px -> 0.5rem
            }
        }
    }
    
    .menu {
        flex: 1;
        
        .el-menu {
            border-bottom: none;
            background-color: transparent;
            
            .el-menu-item {
                font-size: 1rem;  // 16px -> 1rem
                
                &.is-active {
                    font-weight: bold;
                    background-color: rgba(255, 255, 255, 0.1);
                }
                
                &:hover {
                    background-color: rgba(255, 255, 255, 0.1);
                }
            }
        }
    }
    
    .search-box {
        width: 18.75rem;  // 300px -> 18.75rem
        margin: 0 1.25rem;  // 20px -> 1.25rem
        
        .search-input {
            :deep(.el-input__inner) {
                border-radius: 0.25rem 0 0 0.25rem;  // 4px -> 0.25rem
            }
            
            :deep(.el-input-group__append) {
                padding: 0;
                
                .el-button {
                    border-radius: 0 0.25rem 0.25rem 0;  // 4px -> 0.25rem
                    border: none;
                    background-color: #ef5350;
                    color: white;
                    
                    &:hover {
                        background-color: color.adjust(#ef5350, $lightness: -10%);
                    }
                }
            }
        }
    }
    
    .user-info {
        display: flex;
        align-items: center;
        margin-left: 1.25rem;  // 20px -> 1.25rem
        
        .notification {
            margin-right: 1.25rem;  // 20px -> 1.25rem
            font-size: 1.25rem;  // 20px -> 1.25rem
            cursor: pointer;
            
            .notification-badge {
                :deep(.el-badge__content) {
                    background-color: #ef5350;
                }
            }
        }
        
        .user-dropdown-link {
            display: flex;
            align-items: center;
            cursor: pointer;
            color: #fff;
            padding: 4px 8px;
            border-radius: 4px;
            transition: background-color 0.3s;
            
            &:hover {
                background-color: rgba(255, 255, 255, 0.1);
            }
            
            .username {
                margin: 0 8px;
                font-size: 14px;
                font-weight: 500;
            }
        }
        
        .el-button {
            &.is-plain {
                color: #fff;
                border-color: rgba(255, 255, 255, 0.5);
                background: transparent;
                
                &:hover {
                    background-color: rgba(255, 255, 255, 0.1);
                    border-color: #fff;
                }
            }
        }
    }
}

:deep(.el-dropdown-menu.user-dropdown-menu) {
    min-width: 260px !important;
    padding: 0 !important;
    border-radius: 6px !important;
    overflow: hidden !important;
    box-shadow: 0 4px 16px rgba(0,0,0,0.12) !important;
}

:deep(.user-info-card) {
    display: flex !important;
    align-items: center !important;
    padding: 14px !important;
    cursor: pointer !important;
    border-bottom: 1px solid #f0f0f0 !important;
    transition: background-color 0.3s !important;
    
    &:hover {
        background-color: #f9f9f9 !important;
    }
    
    .user-avatar-wrapper {
        margin-right: 12px !important;
        
        .el-avatar {
            width: 42px !important;
            height: 42px !important;
        }
    }
    
    .user-info-details {
        flex: 1 !important;
        
        .user-name {
            font-size: 15px !important;
            font-weight: 500 !important;
            margin-bottom: 4px !important;
            color: #333 !important;
        }
        
        .user-bean {
            font-size: 13px !important;
            color: #EB8D00 !important;
        }
    }
    
    .user-arrow {
        color: #ccc !important;
        margin-left: 8px !important;
        
        .el-icon {
            font-size: 16px !important;
        }
    }
}

:deep(.el-dropdown-menu__item.menu-item) {
    display: flex !important;
    align-items: center !important;
    height: 48px !important;
    padding: 0 16px !important;
    font-size: 14px !important;
    color: #333 !important;
    cursor: pointer !important;
    
    &:hover {
        background-color: #f7f7f7 !important;
    }
    
    .el-icon {
        font-size: 20px !important;
        margin-right: 12px !important;
        color: #666 !important;
    }
    
    span {
        font-size: 14px !important;
    }
}

/* 响应式调整 */
@media screen and (max-width: vars.$md) {
    .app-header {
        .menu {
            .el-menu-item {
                padding: 0 0.625rem;  // 10px -> 0.625rem
                font-size: 0.875rem;  // 14px -> 0.875rem
            }
        }
        
        .search-box {
            width: 12.5rem;  // 200px -> 12.5rem
            margin: 0 0.625rem;  // 10px -> 0.625rem
        }
    }
}

@media screen and (max-width: vars.$sm) {
    .app-header {
        .logo {
            font-size: 1.125rem;  // 18px -> 1.125rem
        }
    }
}
</style>