import VueRouter from "vue-router"
import {getInterceptor, runInterceptor} from "./interceptor"

function treeRouteOption(routers) {
    let options = [];
    let home = routers[0]? routers[0].path:'/404';
    while(true){
        let route = routers[0];

        if(!route) break;

        if(route.home){
            home = route.path;
        }

        //119309 在页面挂载之前获取自定义属性
        let meta = {};
        for (var key in route) {
          //108613 view.name作为内置属性
          if (['component', 'path', 'parent', 'home', 'name'].indexOf(key) == -1) {
            meta[key] = route[key];
          }
        }

        if(!route.parent){
            options.push({
                path:route.path,
                component:route.component,
                children:[],
                meta: meta
            });
        }else{
            let node = queryTree(options,route.parent);
            if(node){
                node.children.push({
                    path:route.path,
                    component:route.component,
                    children:[],
                    meta: meta
                })
            }else{
                let tmp = routers[0];
                routers.push(tmp);
            }
        }
        routers.splice(0,1);
    }
    return {options,home};
}

/**
 * 这里的递归算法有问题？
 * 有什么问题呢？
 * 导致这个方法无法退出，递归无法终止导致浏览器卡死，不是假死是真死！
 * @param options
 * @param path
 * @returns {*}
 */
function queryTree(options, path) {
    for(let i=0;i<options.length;i++){
        let op = options[i];
        if(op.path===path){
            return op;
        }

        if(op.children&&op.children.length>0 && path.indexOf(op.path)===0){
            return queryTree(op.children,path)
        }
    }
}

function processView(view) {
    if(view.component._isProcess) return
    view.component._isProcess = true
    //201407 【lighting小程序】小程序pageid 稳定性和正确性的问题，vue框架小程序持有的pageId在reload时更新丢失问题
    // props既有可能是数组也有可能是对象
    if(process.env.RUNTIME==='miniapp') {
        view.component.props  = view.component.props  || [];
        if(Array.isArray(view.component.props)){
            view.component.props.push('$page');
        }else{
            view.component.props['$page'] = {
                default:{}
            }
        }
    }

    
    let orginMounted = view.component.mounted;

    let mounted = [];
    let rt = view.component;
    if (rt) {
        let before = rt.beforeShow || rt.beforeRender;
        if (before) {
            mounted.push(before)
        }
        let after = rt.afterShow || rt.afterRender;

        const ENV = __ENV__;
        if (ENV && ENV.config && ENV.config.showMode === 1){
            if(after) mounted.push(after);
            mounted.push(orginMounted);
        }else{
            mounted.push(orginMounted);
            if(after) mounted.push(after);
        }
    }else{
        mounted.push(orginMounted)
    }
    view.component.mounted = [function () {
        const that = this;
        //98891 $route.meta 增加用户自定义属性
        //119309 在页面挂载之前获取自定义属性

        let bundleUrl;
        if(process.env.RUNTIME === "native"){
            bundleUrl =  weex.config.bundleUrl;
        }
        if(process.env.RUNTIME === "miniapp"){
            bundleUrl =  __base__.bundleUrl;
        }
        //jsn运行模式下追加请求参数
        if (bundleUrl) {
            let path =bundleUrl.split("#");
            //小程序环境下生命周期不执行
            if(path.length == 2) {
                path = path[1].split("?");
                if (path[0] === view.path && path[1]) {
                    //视图对了
                    let query = path[1].split("&");
                    query.forEach(function (qr) {
                        if (!qr) {
                            return
                        }
                        qr = qr.split("=");
                        that.$set(that.$route.query, qr[0], decodeURIComponent(qr[1] || ''))
                    });
                }
            }
        }

        this.view = this;
        this.model = this;
        this.data = this;
        const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
        deepFlatten(mounted).forEach( (mountedItem) => {
            mountedItem&&mountedItem.call(this, this.$route.query, this.$route);
        })

    }];

    let orginDestroyed = view.component.destroyed;
    view.component.destroyed = [function () {
        let rt = view.component;
        if (rt) {
            let before = rt.beforeHide || rt.beforeUnRender;
            if (before) {
                before.call(this);
            }
            let after = rt.afterHide || rt.afterUnRender;
            if (after) {
                after.call(this);
            }
        }
    }].concat(orginDestroyed ? [orginDestroyed] : []);
}

export default {
    initVueRouter (routeOpt,views,callback) {

        //触发ready，每个视图的ready都在这个时候触发出来
        // views.forEach(function (view) {
        //     if(view.component.ready)view.component.ready();
        // });

        //将生命周期函数缓存起来
        views.forEach(view=>{
            if(typeof view.component === "function"){
                //异步视图
                let originComp = view.component;
                view.component = function () {
                    return originComp().then(function (component) {
                        //108613异步视图支持自定义视图属性
                        processView({
                            ...view,
                            component,
                            //90835 jsn异步视图传参，不能正常的在自定义生命周期中使用参数
                        });
                        return component;
                    })
                }
            }else{
                processView(view);
            }
        });

        //梳理负责关系
        let {options,home} = treeRouteOption(views);
        options.push({
            path:"/",
            redirect:home
        });

        callback(function () {
            const router = new VueRouter({
                routes: options,
                mode:routeOpt.mode
            });

            //导航钩子注册
            getInterceptor("view").forEach(function (hook) {
                router.beforeEach((to, from, next) => {
                    hook.call(this,from,to,next);
                })
            });

            //135321 过滤视图:#/index&xxxx=1
            router.beforeEach(function (to, from, next) {
                if (!/\?/.test(to.fullPath) && /&/.test(to.fullPath)) {
                    let target = {};
                    Object.keys(to).forEach(function (key) {
                        target[key] = to[key];
                    });
                    var fullPath = target.fullPath.replace('&', '?');
                    target.fullPath = fullPath;
                    var queryStr = fullPath.split('?')[1];
                    target.path = fullPath.split('?')[0];
                    target.query[queryStr.split('=')[0]] = queryStr.split('=')[1] || '';
                    next(target);
                } else {
                    next();
                }
            });
            return router;
        })
    },
    VueRouter
}

