/**
* v_index.js
* Version: 0.1
* User: wy
* Date: 2017-09-06
* Copyright(c)  2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* 引导页面
*/

import {iot, uPublic, uComponents} from '../../public/public.js';

iot.ready(init);
function init() {
    //通用 dialog、loading组件
    uPublic.componentsInit(['u-dialog','u-loading','u-button']);
    uPublic.closeSlideBack();
    //是否需要关闭其他页面
    if(iot.navigator.getExtras().needClose){
    	iot.navigator.closeAllBesidesItself();
    }
    const app = new Vue({
        data:{          
            //配置组件
            componentsConfig: initComponentsConfig(),
            clientId: null,
            showLoginButtonFlag: false
        },
        mounted(){
        	if(window.iotDebug){
                iotDebug.push('start: Debug');
           	}
        	console.log(iot.business.user.isLogin());
        	if(iot.business.user.isLogin()){
        		loginButtonTap(this);
        	}
//      	document.addEventListener("resume", () => {
//      		if(!this.showLoginButtonFlag){
//      			resolve(this);
//      		}
//		    }, false);
        },
        methods:{
        	getShowLoginButtonFlag(){
        		return this.showLoginButtonFlag;
        	},
        	setShowLoginButtonFlag(flag){
        		this.showLoginButtonFlag = flag;
        	},
        	onLoginButtonTap(){
				uComponents.showLoading(this);
        		loginButtonTap(this);
        	},
        	getClientId(){
        		return this.clientId;
        	},
        	setClientId(id){
        		this.clientId = id;
        	}
        }   
    }).$mount('#app');
}

//配置组件参数
function initComponentsConfig() {
    return {
    	//登录 button 参数
        loginButton: {   
            initParam: {
                class: 'custom-guide-button',
                text: Vue.t('btn.guideLogin')
            }
        },        
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        }
    }
}

//function resolve(self){
//	if (plus.os.name == 'Android') {
//      iot.permission.checkPermission(['READ_EXTERNAL_STORAGE'], function (res) {
//          console.log('success', res);
//			loginButtonTap(self);
//      }, function (err) {
//          console.log('error', err);
//          //已禁用，跳到系统设置页面
//          iot.native.toAppSetting();
//      });
//  }else{
//  	loginButtonTap(self);
//  }
//}


//sds登陆
function loginButtonTap(self){
	if (plus.os.name == 'Android') {
        iot.permission.checkPermission(['READ_EXTERNAL_STORAGE'], function (res) {
            console.log('success', res);
			openSdsLogin(self);
        }, function (err) {
            console.log('error', err);
            //已禁用，跳到系统设置页面
//          plus.nativeUI.confirm('需要文件读取权限', (e)=>{
//          	if(e.index == 1){
//          		//确认
//          		iot.native.toAppSetting();
//          	}else if(e.index == 1){
//          		//取消
//          		uComponents.hideloading(self);
//          	}
//          },{ "title":"权限请求",
//				"buttons":["取消","确定"],
//				"verticalAlign":"center"});
        });
    }else{
    	openSdsLogin(self);
    }
}

function openSdsLogin(self){
	iot.business.sds.checkSDSInit({
		data: {},
		success: (response) => {
			//初始化成功
			console.log(response);
			iot.business.sds.login({
			    data: {
			        userinfo: {}
			    },
			    success: (response) => {
			    	console.log(response);
			    	if(window.iotDebug){
				        iotDebug.push('end: SDSloginSuccees');
				   	}
			    	var data = uPublic.checkResponseData(response.data);
			    	if(data){
			    		if(data.hasOwnProperty('UserID')){
			    			cloudsLogin(self, data.UserID);
			    		}
			    	}else{
			    		
			    	}
			    },
			    error: (error) => {
			    	self.setShowLoginButtonFlag(true);
			    	console.log(error);
		    		if(window.iotDebug){
		                iotDebug.push('end: sds登陆失败'+JSON.stringify(error));
		           	}
			    	if (window.iotDebug) {
		                iotDebug.upload(iot,'sds登陆失败');
		            }
			    },
			    complete: () => {
			    	uComponents.hideLoading(self);
			    }
			});
		},
		error: (error) => {
			//初始化失败,重新初始化
			console.log('eroor');
			console.log(error);
			if(window.iotDebug){
                iotDebug.push('end: 初始化失败'+JSON.stringify(error));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'初始化失败');
            }
	    	uPublic.openRequestErrorAlert(self, Vue.t('request.initError'));
	    	uComponents.openAlert(self, Vue.t('request.initError'), {
		        text: Vue.t('dialog.confirm'), callback: function () {
		        	iot.navigator.closeAll();
		        }
		    });
		},
		complete: () => {}
	});
}

//云端登陆
function cloudsLogin(self, id){
	uComponents.showLoading(self);
	if(window.iotDebug){
        iotDebug.push('start: cloudsLogin');
   	}
	iot.business.api.send('user/sds_login',{
		data: {
			username: id,
//			clienId: self.getClientId()
			clienId: null
		},
		success: (response) => {
			if(window.iotDebug){
		        iotDebug.push('end: cloudsLogin');
		   	}
    		if (window.iotDebug) {
                iotDebug.upload(iot,'登陆流程时间');
            }
    		var data = uPublic.checkResponseData(response.data);
    		if(data){
    			//更新tocken userinfo
	    		iot.business.user.handleLoginSuccess({
	    			success: (response) => {
	    				if(response && data.nickname == '' || data.nickname == null || data.nickname.trim() == ''){
		    				iot.business.user.setInfo({
							    data: {
							        nickname: Vue.t('login.defaultUser',[data.username.substr(10,3)]),
							        head: ''
							    },
							    success: (response) => {
							    	console.log(response);
							    },
							    error: (error) => {
							    	console.log(error);
									uPublic.openRequestErrorAlert(self);
							    },
							    complete: () => {
									uComponents.hideLoading(self);
							    }
							});
		    			}
	    				iot.navigator.openWindow({
					        url: '../device/index.html',
					        id: 'device',
					        styles: {
					        	popGesture: 'none'
					        },
					        extras: {
					        	needClose: true
					        }
					    });
					    plus.navigator.closeSplashscreen();
	    			},
	    			error: (error) => {
	    				console.log(error);
	    			}
	    		}, response);
			}
		},
		error: (error) => {
			console.log(error);
    		if(window.iotDebug){
                iotDebug.push('end: 云端  登陆失败'+JSON.stringify(error));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'云端登陆失败');
            }
			uPublic.openRequestErrorAlert(self);
		},
		complete: () => {}
	},false);
}