 /**
* v_doorlockUsers.js
* Version: 0.1
* User: wy
* Date: 2017-10-09
* 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-button','u-dialog','u-loading']);
    uPublic.closeSlideBack();
    const app = new Vue({
        data:{ 
            userInfo: {},
            bindShowFlag: true,  
            unbindShowFlag: false,
//          stateShowFlag: false,
            guideShowFlag: false,   
            guideStep1ShowFlag: false, 
            guideStep2ShowFlag: false,  
            guideStep3ShowFlag: false,   
            guideStep4ShowFlag: false,
            //配置组件
            componentsConfig: initComponentsConfig(),
            extras: {},
            imageSrc: '../../resources/image/green_unbindSuccess_icon.png',
//          textBindTip: Vue.t('doorlockUser.unbindSuccess'),
            role: null,
            info: null,
            isFirstAddUser: true
        },
        mounted(){     
        	this.extras = iot.navigator.getExtras();
        	this.role = this.extras.role;
        	let self = this;
//      	window.addEventListener('returnPage',function(event){
//				console.log("returnPage");
//				getUserInfo(self);
//			});
			getUserInfo(this);
			let opener = plus.webview.currentWebview().opener();
			if(opener.id == 'addUser'){
				self.isFirstAddUser = true;
			}else{
				self.isFirstAddUser = false;
			}
        },
        methods:{
            getBindShowFlag(){
                return this.bindShowFlag;
            },
            setBindShowFlag(boolean){
                this.bindShowFlag = boolean;
            },
            getUnbindShowFlag(){
                return this.unbindShowFlag;
            },
            setUnbindShowFlag(boolean){
                this.unbindShowFlag = boolean;
            },
//          getStateShowFlag(){
//              return this.stateShowFlag;
//          },
//          setStateShowFlag(boolean){
//              this.stateShowFlag = boolean;
//          },
            getGuideShowFlag(){
                return this.guideShowFlag;
            },
            setGuideShowFlag(boolean){
                this.guideShowFlag = boolean;
            },
            getGuideStep1ShowFlag(){
                return this.guideStep1ShowFlag;
            },
            setGuideStep1ShowFlag(boolean){
                this.guideStep1ShowFlag = boolean;
            },
            getGuideStep2ShowFlag(){
                return this.guideStep2ShowFlag;
            },
            setGuideStep2ShowFlag(boolean){
                this.guideStep2ShowFlag = boolean;
            },
            getGuideStep3ShowFlag(){
                return this.guideStep3ShowFlag;
            },
            setGuideStep3ShowFlag(boolean){
                this.guideStep3ShowFlag = boolean;
            },
            getGuideStep4ShowFlag(){
                return this.guideStep4ShowFlag;
            },
            setGuideStep4ShowFlag(boolean){
                this.guideStep4ShowFlag = boolean;
            },
            setImageSrc(src){
            	this.imageSrc = src;
            },
//          setTextBindTip(tip){
//          	this.textBindTip = tip;
//          },
            getInfo(){
            	return this.info;
            },
            setInfo(object){
            	this.info = object;
            },
            //tap <
            onBackTap(){
                backTap();
            },
            //tap 邀请绑定
            onBindButtonTap(){
                bindButtonTap(this);
            },
            //tap 解绑
            onUnbindButtonTap(){
                unbindButtonTap(this);
            },
            //tap 绑定开锁信息
            onBindUnlockInfoTap(){
                bindUnlockInfoTap(this);
            },
            //tap 编辑用户昵称
            onEditNameTap(){
            	editNameTap(this);
            },
            //tap 历史开门记录
            onOpendoorRecordTap(){
                opendoorRecordTap(this);
            },
            //tap 删除该用户
            onDeleteUserButtonTap(){
                deleteUserButtonTap(this);
            },
//          onUnbindStateDialogTap(){
//              unbindStateDialogTap(this);
//          },
            //tap 下一步
            onNextButtonTap(){
                nextButtonTap(this);
            },
            //tap 我知道了
            onISeeButtonTap(){
                iSeeButtonTap(this);
            }                
        }   
    }).$mount('#app');
}

//配置组件参数
function initComponentsConfig() {
    return {
        //绑定 button 参数
        bindButton: {   
            initParam: {
                class: 'custom-unbind-button',
                text: Vue.t('doorlockUser.inviteBind')
            }
        }, 
        //解绑 button 参数
        unbindButton: {   
            initParam: {
                class: 'custom-unbind-button',
                text: Vue.t('btn.unbind')
            }
        }, 
        //解绑 button 参数
        unbindButton: {   
            initParam: {
                class: 'custom-unbind-button',
                text: Vue.t('btn.unbind')
            }
        }, 
        //解绑 button 参数
        unbindButton: {   
            initParam: {
                class: 'custom-unbind-button',
                text: Vue.t('btn.unbind')
            }
        }, 
        //删除该用户 button 参数
        deleteUserButton: {   
            initParam: {
                class: 'custom-button',
                text: Vue.t('btn.deleteUser')
            }
        }, 
        //下一步 button 参数
        nextButton: {   
            initParam: {
                class: 'custom-dialog-button',
                text: Vue.t('btn.next')
            }
        },
        //我知道了 button 参数
        iSeeButton: {   
            initParam: {
                class: 'custom-dialog-button',
                text: Vue.t('btn.iSee')
            }
        },     
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        }               
    }
}

//判断是否第一次添加用户
function checkFirstAddUser(self){
	iot.storage.getMap('isFirstAddUser', (res) => {
        if (res) {
            
        } else {
            //显示引导动画
            showGuide(self);
        }
    }, () => {
		//显示 引导动画
		showGuide(self);
    });
}

//显示动画
async function showGuide(self){
	self.setGuideShowFlag(true);
	let time = null
	console.log(self.userInfo.role);
	if(self.userInfo.role == 0){
		try{
			time = await sleep(500);
	        self.setGuideStep3ShowFlag(true),   
			
			time = await sleep(500);
			self.setGuideStep4ShowFlag(true);
		}
		catch (err){
			console.log(err);
		}
	}else{
		try{
			time =await sleep(500);
			self.setGuideStep1ShowFlag(true); 
	
			time = await sleep(500);
	        self.setGuideStep2ShowFlag(true);
		}
		catch (err){
			console.log(err);
		}
	}
}

async function nextGuide(self){
	try{		
		let time = await sleep(500);
        self.setGuideStep3ShowFlag(true),   
		
		time = await sleep(500);
		self.setGuideStep4ShowFlag(true);
	}
	catch (err){
		console.log(err);
	}
}

function sleep(time){
	return new Promise(function(resolve, reject){
		setTimeout(()=>{
			resolve(time);
		},time);
	})
}

function getUserInfo(self){
	uComponents.showLoading(self);
	iot.business.api.sendCustom('lock/getUserInfo',{
		data: {
			rel_id: self.extras.id,
			device_id: self.extras.lockId
		},
		success: (response) => {
			let data = uPublic.checkResponseData(response.data);
			console.log(data);
	    	if(data){
	    		self.setInfo(data);
	    		setUserInfo(self, data);
	    		if(self.role == 0){
					checkFirstAddUser(self);
	    		}
	    	}else{}
			
		},
		error: (error) => {
			console.log(error);
//			if(window.iotDebug){
//              iotDebug.push('end: 获取用户信息'+JSON.stringify(error));
//         	}
//	    	if (window.iotDebug) {
//              iotDebug.upload(iot,'获取用户信息');
//          }
	    	uPublic.openRequestErrorAlert(self);
		},
		complete: () => {
			uComponents.hideLoading(self);
		}
	});
}

//设置用户信息
function setUserInfo(self, data){
	self.userInfo = {
		image: data.role == 0 ? '../../resources/image/green_admin_icon.png' : data.user_id == null ? '../../resources/image/gray_unbindHead_icon.png' : '../../resources/image/green_bindHead_icon.png',
        role: data.role,
        title: data.nickname,
        subtitle: ''
	}
	self.setBindShowFlag(data.user_id ? false : true);
	self.setUnbindShowFlag(data.user_id ? true : false);
}

mui.back = function(){
    let opener = plus.webview.currentWebview().opener();
	if(opener.id == 'addUser'){
		opener.close();
		iot.navigator.fire(plus.webview.getWebviewById('doorlockUsers'),'returnPage',{});
		iot.navigator.back();
	}else{
		iot.navigator.fire(plus.webview.currentWebview().opener(),'returnPage',{});
		console.log('returnPage');
   	 	iot.navigator.back();
	}
}

//tap <
function backTap(){
	iot.navigator.aback();
}

//tap 编辑用户昵称
function editNameTap(self){
	if(!self.role && !self.isFirstAddUser){
	    iot.navigator.openWindow({
	        url: './editName.html',
	        id: 'editName',
	        extras: {
	        	id: self.getInfo().id,
	        	nickname: self.getInfo().nickname,
	        	deviceId: self.getInfo().device_id,
	        	role: self.extras.role
	        }
	    });
	}
}

//tap 邀请绑定
function bindButtonTap(self){
    iot.navigator.openWindow({
        url: './inviteBind.html',
        id: 'inviteBind',
        extras: {
        	uuid: self.extras.uuid,
        	id: self.extras.id,
        	deviceId: self.getInfo().device_id,
        	lockId: self.extras.lockId
        }
    });
}

//tap 解绑
function unbindButtonTap(self){
    uComponents.openConfirm(self, Vue.t('doorlockUser.unbindDialogTip'),
       {text: Vue.t('dialog.cancel'), callback: function () {}},
       {text: Vue.t('dialog.unbind'), callback: function () {
            iot.business.sds.unbindByManager({
		        data: {
		            uuid: self.extras.uuid,
					destAuid: self.info.auids
		        },
		        success: (response) => {
		        	console.log(response);
	                iot.business.api.sendCustom('lock/unbindUser',{
				    	data: {
				    		user_id: self.getInfo().user_id,
				    		device_sn: self.getInfo().device_id,
				    		device_id: self.extras.lockId
				    	},
				    	success: (response) => {
				    		console.log(response);
//				    		self.setStateShowFlag(true);
							uComponents.openAlert(self, Vue.t('doorlockUser.unbindSuccess'), {
						        text: Vue.t('dialog.confirm'), callback: function () {
				    				getUserInfo(self);
						       	}
						    });
				    	},
				    	error: (error) => {
				    		console.log(error);
//					    	uPublic.openRequestErrorAlert(self);
//				    		self.setImageSrc('../../resources/image/green_unbindFail_icon.png');
//				    		self.setTextBindTip(Vue.t('doorlockUser.unbindFailue'));
//				    		self.setStateShowFlag(true);
							uComponents.openAlert(self, Vue.t('doorlockUser.unbindFailue'), {
						        text: Vue.t('dialog.confirm'), callback: function () {
						       	}
						    });
				    	},
				    	complete: () => {
							uComponents.hideLoading(self);
				    	}
				    });
		        },
		        error: (error) => {
			    	console.log(error);
		        	uPublic.openRequestErrorAlert(self);
//		        	self.setImageSrc('../../resources/image/green_unbindFail_icon.png');
//		    		self.setTextBindTip(Vue.t('doorlockUser.unbindFailue'));
//		    		self.setStateShowFlag(true);
		    		uComponents.openAlert(self, Vue.t('doorlockUser.unbindSuccess'), {
				        text: Vue.t('dialog.confirm'), callback: function () {
		    				getUserInfo(self);
				       	}
				    });
		        },
		        complete: () => {
		        }
	    	});
       }}
    );
}

//function unbindStateDialogTap(self){
//  self.setStateShowFlag(false);
//  self.setBindShowFlag(true);
//  self.setUnbindShowFlag(false);
//  self.userInfo.image = '../../resources/image/gray_unbindHead_icon.png';
//}

//tap 绑定开锁信息
function bindUnlockInfoTap(self){
    iot.navigator.openWindow({
        url: './unlockInfo.html',
        id: 'unlockInfo',
        extras: {
        	id: self.extras.id,
        	userId: self.getInfo().user_id,
        	deviceId: self.getInfo().device_id,
        	lockId: self.extras.lockId,
        	role: self.extras.role
        }
    });
}

//tap 历史开门记录
function opendoorRecordTap(self){
	if(!self.isFirstAddUser){
	    iot.navigator.openWindow({
	        url: '../device/opendoorRecord.html',
	        id: 'opendoorRecord',
	        extras: {
	        	relId: self.extras.id,
	        	deviceId: self.getInfo().device_id
	        }
	    });
	}
}

//tap 删除该用户
function deleteUserButtonTap(self){
    uComponents.openConfirm(self, Vue.t('doorlockUser.deleteUserDialogTip'),
       {text: Vue.t('dialog.cancel'), callback: function () {}},
       {text: Vue.t('dialog.delete'), callback: function () {
       		deleteUser(self);
       }}
    );
}

//tap 下一步
function nextButtonTap(self){
    self.setGuideStep1ShowFlag(false);
    self.setGuideStep2ShowFlag(false);
    nextGuide(self);
}

//tap 我知道了
function iSeeButtonTap(self){
    self.setGuideShowFlag(false);
    iot.storage.setMap('isFirstAddUser', true,() => {
    }, (err) => {});
}

//删除用户
function deleteUser(self){
	uComponents.showLoading(self);
	if(self.info.auids){
		iot.business.sds.unbindByManager({
	        data: {
	            uuid: self.extras.uuid,
				destAuid: self.info.auids
	        },
	        success: (response) => {
				deleteCloudeUser(self);
			},
	        error: (error) => {
		    	console.log(error);
	        	uComponents.openAlert(self, Vue.t('doorlockUser.deleteFailure'), {
		        text: Vue.t('btn.confirm'), callback: function () {
			        }
		    	});
	        },
	        complete: () => {
	        }
		});
	}else{
		deleteCloudeUser(self);
	}
}

function deleteCloudeUser(self){
	iot.business.api.sendCustom('lock/delLockUser',{
		data: {
			rel_id: self.extras.id,
			user_id: self.getInfo().user_id,
			device_sn: self.getInfo().device_id,
			device_id: self.extras.lockId
		},
		success: (response) => {
			console.log(response);
			if(response.data.success){
				uComponents.openAlert(self, Vue.t('doorlockUser.deleteSuccess'), {
		        text: Vue.t('btn.confirm'), callback: function () {
						iot.navigator.aback();
			        }
		    	});
			}
		},
		error: (error) => {
			console.log(error);
			uComponents.openAlert(self, Vue.t('doorlockUser.deleteFailure'), {
	        text: Vue.t('btn.confirm'), callback: function () {
		        }
	    	});
		},
		complete: () => {
			uComponents.hideLoading(self);
		}
	});
}
