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'];

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
    }




    // /sys/auth/login
    if (getToken()) {
        to.meta.title && useSettingsStore().setTitle(to.meta.title as string);
        /* has token*/
        if (to.path === '/login') {
            next({path: '/index'});
            NProgress.done();
        } else if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
           next();
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next();
        } else {
            next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
            NProgress.done();
        }
    }
});

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