import config from './config.js';
import VueI18n from 'vue-i18n';
import defaultConfig from './defaultConfig.js';
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: defaultConfig.url
		//正式测试
//		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'
	});
}

//logout退出
uPublic.logout = function(opts){
	iot.business.user.logout({
	    data: opts.data,  
	    success: (response) => {
	    	console.log("sdsLogout:"+response);
	    	var sdsResponse = response;
	    	iot.business.api.send('user/logout',{
	    		data: {
	    			key: ['clienId']
	    		},
	    		success: (response) => {
	    			console.log("logout"+response)
	    			iot.business.websql.delMaps(['utoken', 'userinfo'], (response) => {
				        iot.storage.delMaps(['notifyTime','alarmTime','openTime'], (response) => {
				        	console.log("clearMap"+response);
							opts.success(sdsResponse);
					    }, (error) => {
					    	opts.error(error);
					    });
				    }, (error) => {
				    	opts.error(error);
				    });
	    		},
	    		error: (error) => {
	    			opts.error(error);
	    		},
		    	complete: () => {
		    		opts.complete();
		    	}
	    	}, true, false);
	    },
	    error: (error) => {
	    	opts.error(error);
	    },
	    complete: () => {}
	});
}

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

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

iot.navigator.fire = function (webview, eventType, data) {
    mui.fire(webview, 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 () {
	setTimeout(function () {
		var wvs = plus.webview.all();
		var page = plus.webview.currentWebview();
		for (var i = 0; i < wvs.length; i++) {
			if (wvs[i].id != page.id && wvs[i]) {
//				wvs[i].close();
				plus.webview.close(wvs[i],"none",0,{});
			}
		}
		var wvs = plus.webview.all();
	}, 500);
}


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);
})

iot.navigator.aback = function(){
	mui.back();
}

var __back__first = null;

mui.back = 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();
}



//function requestsend(url, opts, i){
//	let data = [0,0,0,0,0,0,0,1,0,0,0];
//	opts.success(data[i]);
//}
//
//function clearTime(interval, timeout){
//	window.clearInterval(interval);
//	window.clearTimeout(timeout);
//}
//
//function sendRequest(url, params, canSend){
//	var opts = {
//      type: 'post',
//      data: params.data,
//      success: params.success,
//      error: params.error,
//      complete: params.complete
//  };
//	canSend = false;
//	requestsend(url, {
//		type: 'post',
//		data: {
//			params.data
//		},
//		success: (response) => {
//			intervalcb.success(response);
//			if(stopcondition(response)){
//				params.success(response);
//				clearTime(handle, time);
//				canSend = false;
//			}else{
//				canSend = true;
//			}
//		},
//		error: (error) => {
//			intervalcb.error(error);
//			//在intervalcb.error(error)中返回的如果是true则继续执行，否则结束轮询
//			if(intervalcb.error(error)){
//				canSend = true;
//			}else{
//				params.error(error);
//				clearTime(handle, time);
//			}								
//		},
//		complete: {}
//	}, true, false);
//	return canSend;
//}
//
//uComponents.loop = function(request, timeout, interval, fincb, stopcondition){
//	var handle = null;
//	var time = null;
//	var url = request.url;
//	var opts = request.opts;
//	var intervalTime = interval.delay;
//	var intervalcb = interval.opts;
//	var flag = true;
//	var canSend = true;
//	var canDo = true;
//	var i = 0;
//	time = setTimeout(function(){
//		clearTime(handle, time);
//		fincb.error('timeout');
//	},timeout);
//	var watcher = setInterval(function(){
//		if(canSend && canDo){
//			var send = sendRequest(url, opts, canSend, canDo);
//		}
//	},1000);
//	//一开始执行一次，发送一次请求
//	requestsend(url, {
//		data: {},
//		success: (response) => {
//			intervalcb.success(response);
//			if(stopcondition(response)){
//				//首次请求结果符合条件的话，结束整个方法
//				fincb.success(response);
//				clearTime(handle, time);
//			}else{
//				//首次请求结果不符合条件的话，每隔intervalTime时间发送请求
//				handle = setInterval(() => {
//					i++;  
//					console.log(i);
//					if(flag){
//						flag = false;
//						requestsend(url, {
//							data: {},
//							success: (response) => {
//								intervalcb.success(response);
//								if(stopcondition(response)){
//									fincb.success(response);
//									clearTime(handle, time);
//								}
//								flag = true;
//							},
//							error: (error) => {
//								if(intervalcb.error(error)){
//									flag = false;
//								}else{
//									fincb.error(error);
//									clearTime(handle, time);
//								}								
//							},
//							complete: {}
//						}, i);
//					}
//				},intervalTime);
//			}
//		},
//		error: (error) => {
//			intervalcb.error(error);
//			fincb.error(error);
//			clearTime(handle, time);
//		},
//		complete: {}
//	}, 0);
//	
//}
//
////传递的参数依次是：
////1.request: 请求参数（数据类型： map,包括：url、header等）；
////2.timeout: 整个方法的超时时间；
////3.interval: 发送请求的间隔时间、callback；
////4.fincb: 整个方法的callback；
////5.stopcondition： 请求停止所要符合的条件
//uComponents.loop({url:'getLockInfo',opts: {
//	success: (response) => {
//		console.log(response);
//	},
//	error: (error) => {
//		console.log(error);
//	}
//}}, 8000, {
//	delay: 1000,
//	opts: {
//		success: (response) => {
//			console.log('intervalcbSuccess:'+response);	
//		},
//		error: (error) => {
//			console.log('intervalcbSuccess:'+error);
//		}
//	}
//}, {
//	success: (response) => {
//		console.log('fincbSuccess:'+response);
//	},
//	error: (error) => {
//		console.log('fincbError'+error);
//	}
//}, (response) => {
//	if(response == 1){
//		return true;
//	}else{
//		return false;
//	}
//});

export {iot, uPublic, uComponents}