import config from './config.js';
import VueI18n from 'vue-i18n';
var VueTouch = require('vue-touch');
Vue.use(VueTouch);

import ugenComponents from 'ugen-components';
var uComponents = ugenComponents.uComponents;
import projectComponents from './manage';

const iot = new UIOT({
    lang: ['zh', 'en'],
    vue: Vue,
    i18n: VueI18n,
    appId: '10004',
    appSecret: '10004',
    wx: {
        appId: ''
    },
    cloud: {
//      url: 'http://wx.iotface.com'
		//96环境
//		url: 'http://192.168.2.96:20000'
		//96外网
//		url: 'http://jycinema.u-gen.net'
		//正式
		url: 'https://cloud.iot.u-gen.net/'
		//正式测试
//		url: 'https://cloud.iot.u-gen.net/test-openapi/'
    },
    plugin: {
        log: {
            url: 'https://admin.iot.u-gen.net/admin/api/debug'
        }
    }
});

var uPublic = {};
uPublic.console = function (res) {
    console.log(res)
};
// 设置页面字体
uPublic.recalc = function () {
    var docEl = document.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            docEl.style.fontSize = clientWidth / 10 + 'px';
        };
    window.addEventListener(resizeEvt, recalc, false);
    recalc();
};
// 注册组件
uPublic.componentsInit = function (array) {
    array.forEach(function (item, index) {
        Vue.component(item, ugenComponents.manage[item]);
    });
};
// 加载项目自定义组件
uPublic.componentsExtend = function (array) {
    array.forEach(function (item, index) {
        Vue.component(item, projectComponents[item]);
    });
};

//请求发送失败弹框
uPublic.openRequestErrorAlert = function (vmObj, content = Vue.t('request.error')) {
    uComponents.openAlert(vmObj, content, {
        text: Vue.t('dialog.confirm'), callback: function () {
        }
    });
};

// 检查请求成功后data参数
uPublic.checkResponseData = function (data) {
    // json
    if (data != null && typeof data === 'object') {
        if (Object.keys(data).length == 0 || data.hasOwnProperty('msg')) {
            return false;
        } else {
            return data;
        }
        // array
    } else if (Array.isArray(data)) {
        if (data.length > 0) {
            return data;
        } else {
            return false;
        }
    }
};

uPublic.openWindow = function (params){
	console.log("innnnn");
	var wv = plus.webview.create(params.url, params.id, {styles: params.styles || {} }, { IOTData: params.extras });
	console.log(wv);
	wv.addEventListener('titleUpdate', function(){
		wv.show('slide-in-right');
	});
}

//禁用ios侧滑返回

uPublic.closeSlideBack = function (){
	var wv = plus.webview.currentWebview();
	wv.setStyle({
	    popGesture: 'none'
	});
}

iot.ready(() => {
    uPublic.recalc();
});

iot.navigator.getAllWebviw = function () {
    return plus.webview.all();
}

iot.navigator.fire = function (webview, eventType, data) {
    if (webview) {
        if (typeof data === 'undefined') {
            data = '';
        } else if (typeof data === 'boolean' || typeof data === 'number') {
            webview.evalJS("typeof mui!=='undefined'&&mui.receive('" + eventType + "'," + data + ")");
            return;
        } else if (typeof data === 'object' && Object.keys(data).length == 0) {
            data = JSON.stringify(data || {}).replace(/\'/g, "\\u0027").replace(/\\/g, "\\u005c");
        }
        webview.evalJS('iot.navigator.receive("' + eventType + '","' + data + '")');
    }
};

window.iot = iot;
iot.navigator.receive = function (eventType, data) {
    console.log("receive。。。");
    if (eventType) {
        try {
            if (data && typeof data === 'string') {
                data = JSON.parse(data);
            }
        } catch (e) {
        }
        iot.navigator.trigger(document, eventType, data);
    }
};

iot.navigator.trigger = function (element, eventType, eventData) {
    console.log("trigger。。。");
    console.log(element);
    console.log(eventType);
    element.dispatchEvent(new CustomEvent(eventType, {
        detail: eventData,
        bubbles: true,
        cancelable: true
    }));
    return this;
};

iot.navigator.closeAllBesidesItself = function () {
    var wvs = plus.webview.all();
//  var curWb = plus.webview.currentWebview();
    for (var i = 0; i < wvs.length-1; i++) {
//      if (wvs[i].id != curWb.id) {
            wvs[i].close();
//      }
    }
}

iot.navigator.closeAll = function (){
    var wvs = plus.webview.all();
    var curWb = plus.webview.currentWebview();
    for (var i = 0; i < wvs.length; i++) {
         wvs[i].close();
    }
}

iot.ready(function(){
    plus.key.addEventListener('backbutton',iot.navigator.aback,false);
})

var __back__first = null;

iot.navigator.aback =function(){
    var wobj = plus.webview.currentWebview();
            var parent = wobj.parent();
            var wbs = iot.navigator.getAllWebviw();
            if (wbs.length>1) {
                // console.log("不止一个webview...");
                // return;
                iot.navigator.back();
                // console.log("有父webview...");
                // return;
                // parent.evalJS('iot.navigator.back()');
                // parent.evalJS('mui&&mui.back();');
            } else {
                console.log("只有一个webView");
                // return;
                wobj.canBack(function(e) {
                    console.log("是否可以返回canback...");
                    console.log(window.history);
                    window.history.back();
                    console.log(e);
                    //by chb 暂时注释，在碰到类似popover之类的锚点的时候，需多次点击才能返回；
                    if (e.canBack) { //webview history back
                        console.log("e.canback....");
                        // return;
                        window.history.back();
                        // iot.navigator.back();
                    } else { //webview close or hide
                        console.log("不能back。。。");

                        if (!__back__first) {
                                __back__first = new Date().getTime();
                                console.log("给back_first设值....");
                                plus.nativeUI.toast( "再按一次退出应用");
                                // mui.toast('再按一次退出应用');
                                setTimeout(function() {
                                    __back__first = null;
                                }, 2000);
                            } else {
                                console.log("back_first不为空....");
                                if (new Date().getTime() - __back__first < 2000) {
                                    console.log("两次的间隔时间少于2秒");
                                    plus.runtime.quit();
                                }else{
                                    console.log("时间间隔大于2s");
                                }
                            }

                        return;
                    }
                });
            }
}


iot.navigator.getCurrentWebView = function (){
	return plus.webview.currentWebview();
}

uPublic.loopUtils = function(func, opts, intervalTime, time){
	
}

export {iot, uPublic, uComponents}