import { createRouter, createWebHistory } from 'vue-router';
import { AUTH_INJECTION_KEY } from '../components/auth/AuthProvider.vue';

import layout from '../layout/index.vue';

const routes = [
    {
        path: '/',
        name: 'layout',
        component: layout,
        children: [
            {
                path: '',
                name: 'Home',
                component: () => import('../views/home/Home.vue')
            },
            {
                path: 'book/:id',
                name: 'BookDetail',
                component: () => import('../views/book/index.vue'),
                props: true
            },
            {
                path: 'book/:id/chapter/:chapterId',
                name: 'ChapterDetail',
                component: () => import('../views/book/chapter.vue'),
                props: true
            },
            {
                path: 'category',
                name: 'Category',
                component: () => import('../views/home/category.vue'),
                props: true
            },
            {
                path: 'category/:id',
                name: 'CategoryDetail',
                component: () => import('../views/home/category.vue'),
                props: true
            },
            {
                path: 'search',
                name: 'Search',
                component: () => import('../views/home/Search.vue')
            },
            {
                path: 'ranking',
                name: 'ranking',
                component: () => import('../views/home/ranking.vue')
            },
            {
                path: 'notice/:id',
                name: 'NoticeDetail',
                component: () => import('../views/home/NoticeDetail.vue'),
                props: true
            },
            {
                path: 'bookshelf',
                name: 'Bookshelf',
                component: () => import('../views/home/Bookshelf.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'task-center',
                name: 'TaskCenter',
                component: () => import('../views/user/TaskCenter.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'gift-box',
                name: 'GiftBox',
                component: () => import('../views/user/GiftBox.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'messages',
                name: 'Messages',
                component: () => import('../views/user/Messages.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'recharge',
                name: 'Recharge',
                component: () => import('../views/user/Recharge.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'money-log',
                name: 'MoneyLog',
                component: () => import('../views/user/MoneyLog.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'author',
                name: 'authorCenter',
                component: () => import('../views/author/AuthorCenter.vue'),
                meta: { requiresAuth: true, requiresAuthor: true },
                redirect: { name: 'authorWorks' },
                children: [
                    {
                        path: 'works',
                        name: 'authorWorks',
                        component: () => import('../views/author/components/WorksManagement.vue'),
                        meta: { requiresAuth: true, requiresAuthor: true }
                    },
                    {
                        path: 'readers',
                        name: 'authorReaders',
                        component: () => import('../views/author/components/ReadersManagement.vue'),
                        meta: { requiresAuth: true, requiresAuthor: true }
                    }
                ]
            },
            {
                path: 'author/work/create',
                name: 'createWork',
                component: () => import('../views/author/CreateWork.vue'),
                meta: { requiresAuth: true, requiresAuthor: true }
            },
            {
                path: 'author/work/:id/setup',
                name: 'workSetup',
                component: () => import('../views/author/WorkSetup.vue'),
                meta: { requiresAuth: true, requiresAuthor: true }
            },
            {
                path: 'author/work/:id/edit',
                name: 'workEdit',
                component: () => import('../views/author/WorkEdit.vue'),
                meta: { requiresAuth: true, requiresAuthor: true }
            }
        ]
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('../views/NotFound.vue')
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

// 创建一个事件总线用于通信
export const routerEvents = {
    triggerLogin: null
};

// 全局路由守卫
router.beforeEach((to, from, next) => {
    // 调试信息
    console.log('[Router] 路由切换:', { 
        from: from.path, 
        to: to.path,
        meta: to.meta
    });
    
    // 首先尝试从localStorage获取登录和作家状态（统一使用X-Access-Token）
    const token = localStorage.getItem('X-Access-Token') || localStorage.getItem('token');
    const userData = localStorage.getItem('user');
    const isLoggedIn = !!(token && userData);
    const isAuthor = localStorage.getItem('isAuthor') === 'true';
    
    // 输出当前状态
    console.log('[Router] 当前状态:', { isLoggedIn, isAuthor });
    
    // 获取路由需要的权限
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    const requiresAuthor = to.matched.some(record => record.meta.requiresAuthor);

    // 如果路由不需要任何权限，直接放行
    if (!requiresAuth && !requiresAuthor) {
        next();
        return;
    }

    // 处理需要登录的路由
    if (requiresAuth && !isLoggedIn) {
        const targetRoute = to.fullPath;
        console.log('[Router] 需要登录权限，未登录，跳转到首页');
        
        // 尝试调用登录弹窗
        setTimeout(() => {
            const authContext = window.$authContext;
            if (authContext && typeof authContext.openLogin === 'function') {
                authContext.openLogin(() => {
                    // 登录成功后导航到原来想要去的页面
                    router.push(targetRoute);
                });
            } else {
                // 如果authContext还未挂载，则设置事件供之后触发
                routerEvents.triggerLogin = () => {
                    const context = window.$authContext;
                    if (context && typeof context.openLogin === 'function') {
                        context.openLogin(() => {
                            router.push(targetRoute);
                        });
                    }
                };
            }
        }, 0);
        
        // 跳转到首页
        next({ path: '/' });
        return;
    }

    // 处理需要作家权限的路由
    if (requiresAuthor) {
        // 如果已经是作家，直接放行
        if (isAuthor) {
            console.log('[Router] 需要作家权限，已是作家，直接放行');
            next();
            return;
        }
        
        console.log('[Router] 需要作家权限，非作家，跳转到首页');
        
        // 未登录或不是作家，需要先登录再申请成为作家
        if (!isLoggedIn) {
            const targetRoute = to.fullPath;
            setTimeout(() => {
                const authContext = window.$authContext;
                if (authContext && typeof authContext.openLogin === 'function') {
                    authContext.openLogin(() => {
                        // 登录成功后显示作家申请
                        const authorContext = window.$authorApplicationContext;
                        if (authorContext && typeof authorContext.openApplicationModal === 'function') {
                            authorContext.openApplicationModal(() => {
                                // 申请成功后导航到作家专区
                                router.push(targetRoute);
                            });
                        }
                    });
                }
            }, 0);
        } else {
            // 已登录但不是作家，直接显示作家申请
            setTimeout(() => {
                const authorContext = window.$authorApplicationContext;
                if (authorContext && typeof authorContext.openApplicationModal === 'function') {
                    authorContext.openApplicationModal(() => {
                        // 申请成功后导航到作家专区
                        router.push(to.fullPath);
                    });
                }
            }, 0);
        }
        
        // 跳转到首页
        next({ path: '/' });
        return;
    }
    
    // 通过所有检查
    console.log('[Router] 通过所有权限检查');
    next();
});

export default router;