import Vue from 'vue';
import Router from 'vue-router';
import store from '@/store';
import Login from '@/views/Login';
import NotFound from '@/views/NotFound.vue';
import req from '@/request.js';
import uc from '@/api/uc.js';
import portal from '@/api/portal.js'
import { Message } from 'element-ui';
import SparkMD5 from 'spark-md5'
//路由
import mainRouter from '@/router/module';
// 新窗口页面路由
import blankRouter from '@/router/blank_router.js';

Vue.use(Router);

var router = new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: [
        {
            path: '/frontPlat',
            name: 'frontPlat',
            component: () => import('@/components/layout/Layout'),
            children: [
                {
                    path: 'PersonalInfo',
                    name: 'PersonalInfo',
                    props: true,
                    component: () => import('@/views/PersonalInfo.vue'),
                    meta: {
                        single: true,
                        anonymous: true,
                    },
                },
                ...blankRouter,
            ],
        },
        {
            path: '/bizPlat',
            name: 'bizPlat',
            component: () => import('@/components/layout/BizLayout'),
            children: [...mainRouter],
        },
        {
            path: '/',
        },
        {
            path: '/login/:tenant',
            name: 'loginTenant',
            props: true,
            component: Login,
            meta: {
                single: true,
                anonymous: true,
            },
        },
        {
            path: '/login',
            name: 'login',
            component: Login,
            meta: {
                single: true,
                anonymous: true,
            },
        },
        // 跳转鉴权等待页面
        {
            path: '/sjgx',
            name: 'sjgx',
            component: () => import('@/views/Loading.vue'),
            meta: {
                single: true,
                anonymous: true
            }
        },
        {
            path: '/resetPwdView',
            name: 'resetPwdView',
            props: true,
            component: () => import('@/views/ResetPwdView.vue'),
            meta: {
                single: true,
                anonymous: true,
            },
        },

        {
            path: '/formManage/:instId/:type',
            name: 'formManage',
            component: () => import('@/components/flow/formManage.vue'),
            props: true,
            meta: {
                single: true,
            },
        },

        {
            path: '*',
            component: () => import('@/components/layout/BizLayout'),
            children: [
                {
                    path: '*',
                    component: NotFound,
                },
            ],
            meta: {
                single: true,
            },
        },

        // {
        //   path: '*',
        //   component: NotFound,
        //   meta: {
        //     single: true
        //   },
        // }
    ],
});

const createRouter = () =>
    new Router({
        mode: 'history',
        routes: [],
    });

//重写动态添加路由方法
router.$addRoutes = (params) => {
    const newRouter = createRouter();
    router.matcher = newRouter.matcher; //重置路由规则
    router.addRoutes(params); // 添加路由
};

//动态新增二级路由
router.addList = (path, list) => {
    let isAddPath = false;
    let isChildren = false;
    for (let i = 0; i < list.length; i++) {
        //判断当前点击菜单的路由别名是否存在 router.js 里面
        if (path == list[i].path) {
            //存在
            //动态注册路由
            let index = path.replace('/', '');
            let templatePreview_new = {
                path: 'template/preview/:templateKey',
                name: 'templatePreview_' + index,
                props: true,
                component: (resolve) => require(['@/components/dataTemplate/templatePreview.vue'], resolve),
            }; //数据报表
            let templateHref_new = {
                path: 'href/template/:alias',
                name: 'templateHref_' + index,
                props: true,
                component: (resolve) => require(['@/components/dataTemplate/templateHref.vue'], resolve),
            }; //URL菜单
            let querySql_new = {
                path: 'querySql/queryView/:sqlAlias/:alias',
                name: 'querySql_' + index,
                props: true,
                component: (resolve) => require(['@/components/querySql/querySqlContent.vue'], resolve),
            }; //自定义视图
            let template_new = {
                path: 'template/form/:templateKey/:action',
                name: 'template_' + index,
                props: true,
                component: (resolve) => require(['@/components/dataTemplate/templateForm.vue'], resolve),
            }; //数据报表
            let draftList_new = {
                path: 'draftList/:tempAlias/:dataViewFlag',
                name: 'template_' + index,
                props: true,
                component: (resolve) => require(['@/components/dataTemplate/TemplateDraft.vue'], resolve),
            }; //数据报表
            let templateSingle_new = {
                path: 'template/form/:templateKey/:action/:single',
                name: 'templateSingle_' + index,
                props: true,
                component: (resolve) => require(['@/components/dataTemplate/templateForm.vue'], resolve),
            }; //数据报表
            let templateQuerys_new = {
                path: 'template/preview/:templateKey/:single/:parameterqQuerys',
                name: 'templateQuerys_' + index,
                props: true,
                component: (resolve) => require(['@/components/dataTemplate/templatePreview.vue'], resolve),
            }; //数据报表
            if (list[i].children) {
                //判断是否重复添加路由
                for (let j = 0; j < list[i].children.length; j++) {
                    let children = list[i].children[j];
                    if (children.name == templatePreview_new.name) {
                        isAddPath = true; // true ： 重复路由
                        break;
                    }
                }
                if (!isAddPath) {
                    list[i].children.push(templatePreview_new);
                    list[i].children.push(templateHref_new);
                    list[i].children.push(querySql_new);
                    list[i].children.push(template_new);
                    list[i].children.push(templateSingle_new);
                    list[i].children.push(templateQuerys_new);
                    list[i].children.push(draftList_new);
                    router.$addRoutes(list);
                }
                isChildren = true;
                break;
            } else isChildren = true;
        }
    }
    return isChildren;
};

let registerRouteFresh = true;

const ssoRedirect = () => {
    if (window.ssoConfig.mode == 'cas') {
        let service = window.location.href;
        localStorage.setItem('service', service);
        window.location.href = window.ssoConfig.url + '?service=' + service;
    } else if (window.ssoConfig.mode == 'oauth') {
        if (!window.ssoConfig.clientId) {
            throw 'oauth模式下必须提供clientId';
        }
        const service = window.location.href;
        localStorage.setItem('service', service);
        window.location.href = `${window.ssoConfig.url}?response_type=code&client_id=${window.ssoConfig.clientId}&redirect_uri=${service}`;
    }
};

const handelShortUrl = (to, from, next) => {
    req
        .get('${portal}/portal/shorturlManage/v1/getLongUrlByShortUrl?shortUrl=' + to.fullPath.substr(1), '', false)
        .then((resp) => {
            if (resp && resp.data && resp.data.state) {
                store
                    .dispatch('login/validAndCompletedCurrent', resp.data.value.guestToken)
                    .then(() => {
                        next({
                            path: resp.data.value.url,
                        });
                    })
                    .catch(() => {
                        logoutAndCleanUp(to, from, next);
                    });
            } else {
                next({
                    path: '/messageFillPage/' + resp.data.message,
                });
            }
        })
        .catch(() => {
            logoutAndCleanUp(to, from, next);
        });
};

const logoutAndCleanUp = (to, from, next) => {
    store.dispatch('login/logoutAndCleanUp').then(() => {
        if (window.ssoConfig.mode && window.ssoConfig.mode != 'jwt' && !ticket) {
            ssoRedirect();
        } else if (!window.ssoConfig.mode || window.ssoConfig.mode == 'jwt') {
            next({
                path: '/login',
                query: {
                    redirect: to.fullPath,
                },
            });
        } else {
            throw '登录失败';
        }
    });
};

// 移除url后面的指定参数
const removeUrlParams = (param) => {
    const query = window.location.search.substring(1);
    if (!query) {
        return;
    }
    const vars = query.split('&');
    const newVars = [];
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (pair[0] != param) {
            newVars.push(vars[i]);
        }
    }
    setTimeout(() => {
        const path = `${window.location.pathname}${newVars.length > 0 ? '?' : ''}${newVars.join('&')}`;
        window.history.replaceState(null, null, path);
    }, 1000);
};

const getAllDict = () => {
    portal
        .getSysDict()
        .then((data) => {
            if (data) {
                sessionStorage.setItem(
                    'dict_data',
                    JSON.stringify(data)
                )
            }
        })
        .catch((err) => {
            console.log(err, '字典err')
        })
}

const accountLogin = (userInfo, next) => {
    store.dispatch('login/loginByPrincipal', userInfo).then((loginStatus) => {
        if (loginStatus && loginStatus == true) {
            getAllDict()
            store.dispatch('menu/actionFrontMenus').then((res) => {
                const getPath = (treeData, path = '') => {
                    if (Array.isArray(treeData[0].children) && treeData[0].children.length) {
                        path += `/${treeData[0].alias}`;
                        return getPath(treeData[0].children, path);
                    } else {
                        return path + `/${treeData[0].alias}`;
                    }
                };
                next({
                    path: getPath(res, '/bizPlat'),
                });
                removeUrlParams('ptk');
            });
        }
    });
};

const decodeToken = (key) => {
    let sparkStr = ''
    let spark = new SparkMD5()
    spark.append(key)
    sparkStr = spark.end()

    console.log('sparkStr', sparkStr)

    let Base64 = require('js-base64').Base64
    let token = Base64.encode(sparkStr);

    return token
}

router.beforeEach((to, from, next) => {
    // 调用 mutation 设置 favicon
    store.commit('system/SET_FAVICON');

    // 统一门户到数据共享 携带ptk
    if (to.name === 'sjgx' && to.query.ptk) {
        const ptk = to.query.ptk
        uc.validateKeyAndGetUser(ptk)
            .then((res) => {
                if (res.state) {
                    console.log(res)
                    const account = res.value.account || "";
                    let key = "Artfess@024"
                    const decodeTokenStr = decodeToken(account + key)
                    accountLogin(
                        {
                            account: account,
                            token: decodeTokenStr,
                            password: '',
                        },
                        next,
                        to.name,
                    )
                } else {
                    Message.error('验证失败')
                    next({ path: '/login' })
                }
            })
            .catch((err) => {
                Message.error(err || '验证失败')
                next({ path: '/login' })
            })
    }



    store.dispatch('menu/getAllmenus', {}).then((menus) => {
        //href菜单不进这段代码
        if (to.fullPath.indexOf('href') == -1) {
            let alias = to.fullPath.split('/')[1];
            for (let i = 0; i < menus.length; i++) {
                if (menus[i].alias === alias) {
                    store.dispatch('menu/getCurrentMenu', {
                        alias: menus[i].alias,
                        name: menus[i].name,
                    });
                    break;
                }
            }
        }
    });
    if (to.fullPath.startsWith('/surl/')) {
        handelShortUrl(to, from, next);
        return;
    }

    // 1.当前为单点登录模式，且要路由到login页面，则做单点登录重定向；
    if (to.name == 'login' && window.ssoConfig.mode && window.ssoConfig.mode != 'jwt') {
        // 单点登录时如果已经携带了code或者ticket时，如果是/login路径需要跳转到默认页面（解决反复跳转的问题）
        if ((window.ssoConfig.mode == 'cas' || window.ssoConfig.mode == 'oauth') && (to.query.code || to.query.ticket)) {
            window.location.href = window.location.href.replace('/login', '');
            return;
        } else {
            ssoRedirect();
        }
    }

    if (from.name != 'defStart' || to.name != 'instStart') {
        sessionStorage.removeItem('formImportTempRefId');
        sessionStorage.removeItem('formImportTempJson');
    }

    if (sessionStorage.menu_alias && to.fullPath && to.fullPath.split('/')[1] == 'home') {
        sessionStorage.menu_alias = '';
    }
    if (to.matched.some((record) => !record.meta.anonymous)) {
        let ticket = to.query.token;
        // 2.当前已经从单点页面重定向回来了，且在url地址中携带了ticket或code；
        if (window.ssoConfig.mode == 'cas') {
            ticket = to.query.ticket;
        } else if (window.ssoConfig.mode == 'oauth') {
            ticket = to.query.code;
        }
        store
            // 3.携带ticket做用户鉴权；
            .dispatch('login/validAndCompletedCurrent', ticket)
            .then(() => {
                store._vm.$root.$emit('login-completed');
                if (registerRouteFresh) {
                    if (sessionStorage.menu_alias) {
                        let path = '/' + sessionStorage.menu_alias;
                        let isChildren = router.addList(path, router.options.routes); //动态新增二级路由
                        //当前点击菜单的路由别名不存在 router.js 里面
                        // if (!isChildren) {
                        //     let alias_new = {
                        //         path: path,
                        //         name: 'alias_new',
                        //         component: resolve =>
                        //             require(['@/views/menuContent.vue'], resolve),
                        //         children: []
                        //     }
                        //     router.options.routes.push(alias_new)
                        //     router.addList(path, router.options.routes) //动态新增二级路由
                        // }
                        router.replace({
                            path: to.path,
                            query: to.query,
                        });
                    }
                    registerRouteFresh = false;
                }
                next();
                // url地址带token的方式认证成功后删除url中的token
                removeUrlParams('token');
            })
            .catch(() => {
                // 4.鉴权失败时根据当前模式重定向到对应页面。
                logoutAndCleanUp(to, from, next);
            });
    } else {
        next();
    }
});

export default router;
