import { to as tos} from 'await-to-js';
import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import {getToken} from '@/utils/auth';
import {isHttp} from '@/utils/validate';
import {isRelogin} from '@/utils/request';
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';
import usePermissionStore from '@/store/modules/permission';
import { useNoticeStore } from '@/store/modules/notice'
import {LoginData} from "@/api/types";
NProgress.configure({ showSpinner: false });
import { setToken } from '@/utils/auth';
import { ElMessage } from 'element-plus';
const whiteList = ['/login', '/register', '/social-callback', '/index'];

router.beforeEach(async (to, from, next) => {
    NProgress.start();

    // https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww5323bd8ab4394132&redirect_uri=https%3A%2F%2Fsales.test.storlead.com%2Findex&response_type=code&scope=snsapi_base&agentid=1000033&state=fromQYwx#wechat_redirect
    if(to.query.code && to.query.state === 'fromQYwx') {
        const userStore = useUserStore();
        const loginForm = ref<LoginData>({
            wxCode: to.query.code as string
        });
        const res = await tos(userStore.loginWx(loginForm.value));
        // if(err){
        //     ElMessage.error('授权登录失败，请用账号密码登录');
        //     next({path: '/login'});
        //     return
        // }
        let param = {}
        Object.keys(to.query).forEach(item=>{
            if(item!=="code"){
                param[item] = to.query[item]
            }
        })

        let path = to.path + "?" + Object.keys(param).map(item=>item+"="+param[item]).join("&")

        next(path)
        return
    }

    if (to.query.token && to.query.state === 'fromQYwx'){
        debugger
        let redirect = to.query.redirect as string
        let token  = to.query.token as string;
        setToken(token);

        //获取用户信息
        const [err] = await tos(useUserStore().getInfo());
        // if (err) {
        //     await useUserStore().logout();
        //     ElMessage.error(err);
        //     next({path: '/login'});
        // } else {
        //     next(redirect);
        // }
    }



    // /sys/auth/login
    if (getToken()) {
        to.meta.title && useSettingsStore().setTitle(to.meta.title as string);
        /* has token*/
        if (to.path === '/login') {
            next({path: '/'});
            NProgress.done();
        } else if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            if (useUserStore().roles.length === 0) {
                isRelogin.show = true;
                // 判断当前用户是否已拉取完user_info信息
                const [err] = await tos(useUserStore().getInfo());
                if (err) {
                    await useUserStore().logout();
                    ElMessage.error(err);
                    next({path: '/login'});
                } else {
                    isRelogin.show = false;
                    const accessRoutes = await usePermissionStore().generateRoutes();
                    // 根据roles权限生成可访问的路由表
                    accessRoutes.forEach((route) => {

                        if (!isHttp(route.path)) {
                            router.addRoute(route); // 动态添加可访问路由表
                        }
                    });
                    // 邮箱页面不需要循环调未读数接口
                    if(to.path.indexOf('/email') == -1) {
                        useNoticeStore().getCount() // 邮箱未读
                        useNoticeStore().getMessageCount() // 消息未读
                        setInterval(() => {
                            useNoticeStore().getCount()
                            useNoticeStore().getMessageCount()
                        }, 1000 * 60)
                    }
                    next({...to, replace: true}); // hack方法 确保addRoutes已完成
                }
            } else {
                next();
            }
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next();
        } else {
            next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
            NProgress.done();
        }
    }
});

router.afterEach(() => {
    NProgress.done();
});
