const Light = require("../lib/core");
import { parse2query,resolvePath,query2params } from "../lib/utils"

let routerStack = [];
function processJSCoreEvent(type, args) {
    Light.trigger(type, args)
    if (type === "navigateBack") {
        if (routerStack.length > 1) {
            routerStack.pop();
            __base__.currentRoute = __base__.pageId =  routerStack[routerStack.length - 1].pageId;
        }
    }
    if (type === "navigate") {
        let pathParsed = args.path.split("?");
        let params = {};
        if (pathParsed.length === 2) {
            pathParsed[1].split("&").forEach(function (o) {
                let arg = o.split("=");
                //处理路由参数
                params[arg[0]] = decodeURIComponent(arg[1]);
            })
        }
        __base__.currentRoute = __base__.pageId =  args && args.pageId;
        __base__.postPatch(`addCssNative("${__base__.bundlePath + "/app.miniapp.css"}")`, args.pageId || '');

        //167503 小程序olight模块支持openGMU 时 传入pageId
        params.__page_id = args.pageId;

        let router = Light.getRouter();
        //201407 【lighting小程序】小程序pageid 稳定性和正确性的问题，vue框架小程序持有的pageId在reload时更新丢失问题
        const app = new Light.Vue({
            router,
            template: `<div page-id="${args.pageId}"><router-view :$page="{id:'${args.pageId}'}" /></div>`
        });
        router.push({
            path: pathParsed[0],
            query: params
        });
        //160945 navigate接口支持replace:true
        routerStack.push({
            pageId:args.pageId,
            router
        });
        app.$mount()
    }
};
function reloadCheck(){
    let myId = new Date().getTime()+Math.random();
    if(process.env.NODE_ENV === "dev" && typeof LightJSBridge !== "undefined" && __base__.bundlePath && __base__.bundlePath.indexOf("http://") === 0){
        setInterval(()=>{
            LightJSBridge.call("stream.fetch",{
                url:__base__.bundlePath+'/check_reload_me?id='+myId
            },function(data){
                if(data.data && data.data.data && JSON.parse(data.data.data).reload){
                    LightJSBridge.call("miniapp.reload",{})
                }
            })
        },5000)
    }
}

module.exports = {
    start(router,options){
    },
    init() {
        __base__.bundlePath = /^(.*)\/[^\/]*$/ig.exec(__base__.bundleUrl.split("#")[0])[1];
        if(__base__.EventHub){
            __base__.EventHub.subscribe((type,data)=>{
                processJSCoreEvent(type,data);
            })
        } 
        //vue小程序事件触发
        else if(__thread__.event) {
            __thread__.event.saveEvent("native", (event, data)=>{
                processJSCoreEvent(event, data);
            })       
        }
        else{
            __thread__.triggerEvent = processJSCoreEvent;
        }
        reloadCheck();
    },
    navigateBack(number) {
        if (routerStack[routerStack.length - 1].router.history.stack.length > 1) {
            routerStack[routerStack.length - 1].router.go(-1);
        } else {
            LightJSBridge.call("native.back", { number: number }, null);
        }
    },
    navigateTo(path, params, options) {
        //160945 【Light小程序】【双进程渲染】支持小程序地址互相跳转
        let router = routerStack[routerStack.length - 1].router;
        var distUrl = '';

        //166093【框架】优化light.navigate路由跳转时无入参的路由
        if (path.view) {
            //175679 【框架】统一小程序与h5/jsn的视图跳转参数形式
            path.view = path.view.replace(/^\//,'');
            //路由参数
            distUrl = `${__base__.bundleUrl.split("#")[0]}#/${resolvePath(path.view, params)}`;
            path.type = __base__.config.env.container;
        } else {
            distUrl = resolvePath(path.url, params);
            //167515 小程序olight模块支持navigate跳转区分lightweb和miniapp
            if(path.type==='lightweb') {
                path.type = options.miniappContainer || __base__.config.env.container;
            }
        }
       
        if (options.replace === true && path.view) {
            router.push({
                path: "/" + path.view,
                query: params
            });
        } else {
            //185505 【框架】小程序lightweb容器支持跳转gmu://协议路径
            //196697 兼容国君项目：pageId作为第四个参数传入
            if(path.module) {
                //231717 支持打开gmu://web?startPage=xxx（lightweb）
                let query = path.url.indexOf('?')>-1 ? path.url.split('?')[1] : ''
                let queryParams = query=='' ? {} : query2params(query)
                LightJSBridge.call("miniapp.openGmu", {
                    gmuName: path.module,
                    params: {
                        ...queryParams,
                        ...params
                    }
                }, ()=>{}, options.pageId || __base__.currentRoute)
            } else {
                LightJSBridge.call("miniapp.openGmu", {
                    gmuName: path.type,
                    params: {
                        startPage: distUrl,
                        ...options
                    }
                }, ()=>{}, options.pageId || __base__.currentRoute)
            }
        }
    },
    getCurrentFile() {
        return '';
    },
    ajax(options) {
        //get 不支持 body 传参
        let body = options.data;
        if (!options.headers || !options.headers['Content-Type'] || options.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
            // 166775【Light小程序】【框架】请求data为空时不报错
            body = parse2query(options.data || {});
        }
        var settings = {
            method: options.type,
            headers: options.headers || {},
            type: options.dataType || "json",
            timeout: options.timeout
        };

        if (options.type.toLowerCase() !== 'get') {
            settings.body = body
            settings.url = options.url;
        } else {
            settings.url = (options.url) + "?" + parse2query(options.data || {});
        }
        //166947【Light小程序】【双进程渲染】Light.ajax()支持相对路径
        if (!/^http/.test(settings.url)) {
            settings.url = __base__.bundlePath + '/' + settings.url;
        }
        //S2101040111 【type-vue】vue小程序支持查看network面板信息
        let startTime = new Date(), endTime;

        LightJSBridge.call("stream.fetch", settings, function (data) {
            if (+data.info.error_code !== 0) {
                options.error(data.data.data);
            } else {
                endTime = new Date();
                //向webview发送请求结果
                if (__base__.DEBUG_MODE == true && __base__.DEBUG_SHOW_NETWORK_INFO == true) {
                    if(settings.body) settings.body = JSON.stringify(settings.body)
                    let reqObj = settings;
                    reqObj.headers = data['data']&&data.data.headers;
                    reqObj.costTime = endTime - startTime;
                    reqObj.callBackData = data['data']&&data.data['data'];
                    reqObj.statusCode = data['data']&&data.data['status'];
                    __base__.postPatch(`window.XMLHttpRequestUser(${JSON.stringify(reqObj)})`, __base__.currentRoute)
                }
                //194797 小程序支持在success中获取响应头
                let request = {
                    getAllResponseHeaders() {
                        return JSON.stringify(data.data.headers || {}) 
                    },
                    getResponseHeader(key) {
                        return data.data.headers[key]
                    }
                };
                options.success(data.data.data, data.data.status, request)
            }
        }, __base__.currentRoute)
    }
};
