 /**
* 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']);
    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
        },
        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);
			checkFirstAddUser(this);
        },
        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();
            },
            onEditNameTap(){
                editNameTap(this);
            },
            //tap 邀请绑定
            onBindTap(){
                bindTap(this);
            },
            //tap 解绑
            onUnbindButtonTap(){
                unbindButtonTap(this);
            },
            //tap 绑定开锁信息
            onBindUnlockInfoTap(){
                bindUnlockInfoTap(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 参数
        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);
	try{
		let time =await sleep(1000);
		self.setGuideStep1ShowFlag(true); 

		time = await sleep(1000);
        self.setGuideStep2ShowFlag(true);
		
//		time = await sleep(1000);
//      self.setGuideStep3ShowFlag(true),   
//		
//		time = await sleep(1000);
//		self.setGuideStep4ShowFlag(true);
	}
	catch (err){
		console.log(err);
	}
}

async function nextGuide(self){
	try{		
		let time = await sleep(1000);
        self.setGuideStep3ShowFlag(true),   
		
		time = await sleep(1000);
		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);
	    	}else{}
			
		},
		error: (error) => {
			console.log(error);
		},
		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: data.username
	}
	self.setBindShowFlag(data.user_id ? false : true);
	self.setUnbindShowFlag(data.user_id ? true : false);
}

//tap <
function backTap(){
	let opener = plus.webview.currentWebview().opener();
	console.log(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();
	}
}

//修改用户名称
function editNameTap(self){
    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 bindTap(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 () {
            self.setStateShowFlag(true);
            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);
		    	},
		    	error: (err) => {
		    		console.log(err);
		    		self.setImageSrc('../../resources/image/green_unbindFail_icon.png');
		    		self.setTextBindTip(Vue.t('doorlockUser.unbindFailue'));
		    		self.setStateShowFlag(true);
		    	},
		    	complete: () => {
					uComponents.hideLoading(self);
		    	}
		    });
       }}
    );
}

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){
    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);
	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.fire(plus.webview.currentWebview().opener(),'returnPage',{});
						console.log('returnPage');
	    				iot.navigator.back();
			        }
		    	});
    		}
    	},
    	error: (err) => {
    		console.log(err);
    		uComponents.openAlert(self, Vue.t('doorlockUser.deleteFailure'), {
	        text: Vue.t('btn.confirm'), callback: function () {
		        }
	    	});
    	},
    	complete: () => {
			uComponents.hideLoading(self);
    	}
    });
	
}
