import { setLoadComplete } from '@/common/methods';
import { getLoadIsComplete } from '@/common/methods/mixin';
import Layout from '@/layout/index.vue';
import { globalDataRefresh } from '@/services/bus';
import { isLogin, login } from '@/services/bus/login';
import { localStorageUtil } from '@/utils/storage';
import { message } from 'ant-design-vue';
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import eventBus from '../utils/eventBus';
import { registerRoutes } from './dynamic';

const routes: Array<RouteRecordRaw> = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/account/login.vue'),
    },
    {
        path: '/logon',
        name: 'logon',
        component: () => import('@/views/account/logon.vue'),
    },

    {
        path: '/resetPassword',
        name: 'resetPassword',
        component: () => import('@/views/account/resetPassword.vue'),
    },
    {
        path: '/',
        component: Layout,
        props: true,
        redirect: '/login',
        children: [
            {
                path: '/home',
                name: 'home',
                component: () => import('@/views/home.vue'),
            },
            {
                path: '/market-spot/',
                name: 'marketSpot',
                component: () => import('@/views/market/market-spot/index.vue'),
                // props: route => ({ id: route.query.id })
            },
        ],
    },
    {
        path: '/test',
        name: 'test',
        component: () => import('@/views/test/index.vue'),
    },
];

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

// 防止加载动态路由无限死循环
let routerComplete = false;

// 路由拦截
router.beforeEach((to, from, next) => {
    // 前往登录页时 直接走登出流程
    if (to.fullPath === '/login') {
        routerComplete = false;
        eventBus.$emit('logout');
        next();
    } else {
        // 前往其他页 判断是否是登录状态
        if (isLogin()) {
            if (routerComplete) {
                return next();
            } else {
                // 注册动态路由
                registerRoutes().then(() => {
                    routerComplete = true;
                    next({ ...to, replace: true });
                }).catch(() => {
                    message.error('账号没有对应菜单权限');
                })
            }
        } else {
            routerComplete = false;
            if (!getLoadIsComplete()) { // 没有加载对应的资料，表示第一次启动项目
                console.log('to', to);
                const { ACCOUNT, PASSWORD } = to.query
                const name = to.name ? to.name : 'home'
                if (ACCOUNT && PASSWORD) {
                    setLoadComplete(false)
                    globalDataRefresh().then(() => {
                        const { ACCOUNT, PASSWORD } = to.query
                        login(ACCOUNT as string, PASSWORD as string, [], true).then(res => {
                            setLoadComplete(true)
                            localStorageUtil.setItem('loginAccount', ACCOUNT); // 缓存登录账号
                            eventBus.$emit('loginSuccess', true);
                            next({ name })
                        }).catch(err => {
                            // 异常需要跳转到错误页面，让用户手动重试
                            console.log('err', err);
                        })
                    })
                } else { // 跳转到登录页面
                    next()
                }
            } else {    //
                next()
            }
        }
    }
});
export default router;
