import {trigger} from "../lib/event";
import {parse2query,resolvePath,query2params} from "../lib/utils"

const Light = require("../lib/core");
function initFetch() {
    Light.fetch = (options, callback) => {
        options.method = options.method.toUpperCase()
        try{
            window.LightJSBridge.call('stream.fetch', options, (data) => {
                callback(data.data || {})
            })
        } catch(e){
            console.error('当前环境不支持 LightJSBridge 接口调用')
        }
    }
}

module.exports = {
    init() {
        if(weex.config.env.platform === 'HarmonyOS') {
            if(window.LightJSBridge) {
                initFetch()
            } else {
                document.addEventListener('deviceready', () => {
                    initFetch()
                })
            }
        } else{
            const stream = weex.requireModule('stream');
            Light.fetch = stream.fetch;
        }
        Light.requireModule = weex.requireModule;

        //设置页面宽度保持对这种页面的兼容
        // const meta = weex.requireModule('meta');
        // meta.setViewport({
        //     width: weex.config.env.deviceWidth
        // });

        Light.requireModule("globalEvent").addEventListener('AppWillEnterForeground', function () {
            trigger("appappear")
        });
        Light.requireModule("globalEvent").addEventListener('AppDidEnterBackground', function () {
            trigger("appdisappear")
        });
        //232293【type-vue插件】globalEvent新增screenWidthChange事件监听屏幕折叠变化后的宽度值
        Light.requireModule("globalEvent").addEventListener('screenWidthChange', function (data) {
            trigger("screenWidthChange",data.width)
        });
        //globalEvent新增ontabbarchage事件监听app首页tab按钮切换
        Light.requireModule("globalEvent").addEventListener('onTabBarChange', function (data) {
            trigger("ontabbarchange",data)
        });
        Light.requireModule("globalEvent").addEventListener('onScreenShot', function (data) {
            data.screenShot=data.screenShot.replace(/\r\n/g,"");  //	 231663	native 插件新增支持jsn环境的监听屏幕截图配置,图片显示错误问题修复
            data.screenShot=data.screenShot.replace(/\s+/g,"");
            trigger("screenshot", data.screenShot)
        });
        //TS:202104220132-财富经纪业务群_刘向锋
        Light.requireModule("globalEvent").addEventListener('onScreenCaptured', function (data) {
            trigger("screencaptured",data.screenCaptured)
        });
        Light.Vue.prototype.$page = weex;
    },
    start(router, options) {
        //设置页面宽度保持对这种页面的兼容
        var viewportOptions = options;
        const meta = weex.requireModule('meta');
        if (options.viewport) {
            viewportOptions.width = options.viewport;
            meta.setViewport(viewportOptions);
        } else if (options.remMode && options.remMode === 'screen') {
            if (process.env.RUNTIME === 'web') {
                meta.setViewport(viewportOptions);
            }
        }
        if(process.env.RUNTIME==="native"){
            let defaultView = "/";
            let checkView = /#(.+)/ig.exec(weex.config.bundleUrl);
            if (checkView && checkView[1]) {
                defaultView = checkView[1];
            }
            router.push(defaultView);
        }
        const app = new Light.Vue({
            router,
            el:options.el||"#main",
            render: process.env.RUNTIME==="native" ? function () {
                let _vm = this;
                let _h = _vm.$createElement;
                let _c = _vm._self._c || _h;
                return _c('div', {
                    on: {
                        "androidback": _vm.back,
                        "viewappear": _vm.viewappear,
                        "viewdisappear": _vm.viewdisappear
                    }
                }, [_c('router-view', {
                    staticStyle: {
                        flex: "1"
                    }
                })], 1)
            }:undefined,
            methods:{
                back: function () {
                    this.$router.back();
                } ,
                viewappear(arg) {
                    trigger("viewappear",arg)
                } ,
                viewdisappear() {
                    trigger("viewdisappear")
                }
            }
        })
    },
    navigateTo(path,params,options){
        const event = weex.requireModule("event");
        const navigator = weex.requireModule("navigator");
        //166093【框架】优化light.navigate路由跳转时无入参的路由
        let distURL = resolvePath(path.url, params);
       
        if(path.type === "jsnative"){
            if(options.replace===true && path.view){
                Light.router.push({
                    path:path.view,
                    query:params
                })
            }else{
                navigator.push({
                    url: distURL,
                    animated: "true",
                    ...options
                }, event=>{
                    if(options.callback) options.callback();
                })
            }
        }
        if(path.type === "web"){
            event.openNative("web", {
                startPage: distURL,
                ...options
            })
        }
        if(path.type === "native"){
            //231599 支持打开gmu://web?startPage=xxx（jsn）
            let query = path.url.indexOf('?')>-1 ? path.url.split('?')[1] : ''
            let queryParams = query=='' ? {} : query2params(query)
            params = {
                ...queryParams,
                ...params
            }
            event.openNative(path.module, params)
        }

        //160945 【Light小程序】【双进程渲染】支持小程序地址互相跳转
        //167515 小程序olight模块支持navigate跳转区分lightweb和miniapp
        if(path.type === 'lightweb') {
            event.openNative(options.miniappContainer || path.type, {
                startPage: distURL,
                ...options
            })
        }
    },
    navigateBack(number) {
        weex.requireModule('LightJSBridge').call('native.back', {number: number}, null);
    },
    getCurrentFile(){
        return  weex.config.bundleUrl.split(/([#])/)[0];
    },
    ajax(options){
        var settings = {};
        settings.method = options.type;
        settings.type = options.dataType;

        settings.headers = options.headers;
        let success = options.success;
        let error = options.error;
        settings.headers['Content-Type'] = settings.headers['Content-Type'] || 'application/x-www-form-urlencoded';
        //119069 GET 请求不支持 body 方式传递参数，请使用 url 传参
        if(options.type.toLowerCase()!=='get') {
            // 212807 修复Light.ajax在jsn上get请求多传body参数的问题
            settings.body = options.data || {};
            settings.url = options.url;
        } else {
            settings.url = (options.url) + "?" + parse2query(options.data || {});
        }
        if (options.dataType === 'jsonp') {
            let jsonpID = 0;
            let callbackName = options.jsonpCallback || ('jsonp' + (++jsonpID));
            settings.url = settings.url + `&callback=${callbackName}`;
        }

        //jsn环境-cache
        if(options.cache === true){
            const cacheKEY = `${settings.url}#${JSON.stringify(settings.body)}#${JSON.stringify(settings.headers)}#${settings.type}`;
            weex.requireModule("storage").getItem(cacheKEY,function (data) {
                if(data.data&&data.data!=='undefined'){
                    success(JSON.parse(data.data))
                }else{
                    weex.requireModule("stream").fetch(settings, function (ret) {
                        if (ret.ok) {
                            weex.requireModule("storage").setItem(cacheKEY,JSON.stringify(ret.data),function () {
                                success && success(ret.data);
                            })
                        } else {
                            error && error(ret.data);
                        }
                    })
                }
            });
        }else{
            weex.requireModule("stream").fetch(settings, function (ret) {
                if (ret.ok) {
                    success && success(ret.data);
                } else {
                    error && error(ret.data);
                }
            })
        }


    }
};