import config from './config.js';
import VueI18n from 'vue-i18n';
import defaultConfig from './defaultConfig';
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: defaultConfig.appId,
    appSecret: defaultConfig.appSecret,
    wx: {
        appId: ''
    },
    cloud: {
//      url: 'http://wx.iotface.com'
		//96环境
		url: defaultConfig.url
		//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.checkString = function (text){
	var pattern = new RegExp("[~!@#$%^&*()_+=|\?/{}<>:;'`]+");
	if(!pattern.test(text)){
		return false
	}else{
		return true;
	}
}

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: () => {}
	});
}

// 更新缓存中history存储的isReadFlag 和 time
uPublic.upDateRead = async function(key, time){
	let oldHistory = {
    	alarm: {
    		time: null,
    		isReadFlag: true
    	},
    	notify: {
    		time: null,
    		isReadFlag: true
    	},
    	open: {
    		time: null,
    		isReadFlag: true
    	}
    };
	try{
		let history = await iot.storage.getMap('history');
		oldHistory = history ? history : oldHistory;
		console.log(oldHistory);
	}
	catch (error){
		console.log(error);
	}
	
	let newHistory = oldHistory;
	newHistory[key].isReadFlag = true;
	newHistory[key].time = time;
	let flag  = await iot.storage.setMap('history', newHistory);
	if(flag){
		return false;
	}
}



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

export {iot, uPublic, uComponents}