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

import CryptoJS from "crypto-js";
import moment from 'moment';
import crypto from '../../public/crypto.js';
import config from '../../public/config.js';
import {iot, uPublic, uComponents} from '../../public/public.js';

iot.ready(init);
function init() {
	
    //通用 图片轮播、跑马灯、开关、按钮、dialog、loading组件
    uPublic.componentsInit(['u-carousel','u-marquee','u-switch','u-button','u-dialog','u-loading','u-text','u-comm-loading']);
    const app = new Vue({
        data:{ 
            //开门记录
            valueOpendoorRecord: 0,
            //安全报警
            valueSecurityAlarm: 0,
            //门锁用户
            valueDoorlockUser: 0,
            //劫持报警
            valueHijackAlarm: 0,
            //远程开门
            valueRemoteOpendoor: 0,
            //门锁管理
            valueDoorlockManage: 0,
            //开门记录
            opendoorRecordDisabledFlag: false,
            //安全报警
            securityAlarmDisabledFlag: false,
            //门锁用户
            doorlockUserDisabledFlag: false,
            //劫持报警
            hijackAlarmDisabledFlag: false,
            //远程开门
            remoteOpendoorDisabledFlag: true,
            //门锁管理
            doorlockManageDisabledFlag: false,
            //门锁最新消息是否滚动
            activeFlag: false,
            //配置组件
            componentsConfig: initComponentsConfig(),
            //
            followShowFlag: false,
            //电量icon
            batteryState: '',
            //电量百分比
            batteryPercent: 100,
            //响铃时间
            ringingTime: null,
            //门铃是否响起
            doorbellRingingFlag: false,
            ringTime: null,
            //点击远程开门提示
            remoteOpendoorFlag: false,
            //设备ID
            deviceId: null,
            //设备mac
            mac: null,
            //设备uuid
            uuid: null,
            //设备model
            model: null,
            //sds设备用户信息
            userInfo: null,
            //门锁id
            lockId: null,
            //获取用户的身份
            role: null,
            lockInfo: {},
            //最新消息
            newMsg: [],
            //是否第一次获取门锁信息
            isFirstGetLockInfo: true,
            opendoorRecordFlag: false,
            securityAlarmFlag: false,
            hijackAlarmFlag: false,
			notifyTime: null,
			alarmTime: null,
			openTime: null,
            //是否显示远程开门页面
            remoteOpendoorShowFlag: false,
            //远程开门密码
            textPassword: null,  
            //远程开门错误提示
            textErrorTip: null,
            //当前状态
            status: 0,
            flag: true,
            time: null,
            timeout: null,
            handle: null
        },
        mounted(){
        	notificationListener(this);
        	let self = this;
        	iot.navigator.closeAllBesidesItself();
        	//获取设备信息
        	getDevices(this);
			//注册监听上报
			registerPushListener(this);
			window.addEventListener('returnPage',function(event){
				//获取设备信息
	        	getDevices(self);
				//注册监听上报
				registerPushListener(self);
			});
//			uPublic.loopUtils(function(){
//				console.log('1233434');
//			}, {
//				success: (response) => {
//					console.log('success');
//				},
//				error: (err) => {
//					console.log(err);
//				}
//			}, 1, 30000);
//			ringBell(this);sss
        },
        methods:{
        	setValueRemoteOpendoor(value){
        		this.valueRemoteOpendoor = value;
        	},
            getOpendoorRecordDisabledFlag(){
                return this.opendoorRecordDisabledFlag;
            },
            setOpendoorRecordDisabledFlag(flag){
                this.opendoorRecordDisabledFlag = flag;
            },
            getSecurityAlarmDisabledFlag(){
                return this.securityAlarmDisabledFlag;
            },
            setSecurityAlarmDisabledFlag(flag){
                this.securityAlarmDisabledFlag = flag;
            },
            getDoorlockUserDisabledFlag(){
                return this.doorlockUserDisabledFlag;
            },
            setDoorlockUserDisabledFlag(flag){
                this.doorlockUserDisabledFlag = flag;
            },
            getHijackAlarmDisabledFlag(){
                return this.hijackAlarmDisabledFlag;
            },
            setHijackAlarmDisabledFlag(flag){
                this.hijackAlarmDisabledFlag = flag;
            }, 
            getRemoteOpendoorDisabledFlag(){
            	return this.remoteOpendoorDisabledFlag;
            },
            setRemoteOpendoorDisabledFlag(flag){
            	this.remoteOpendoorDisabledFlag = flag;
            },
            getDoorlockManageDisabledFlag(){
            	return this.doorlockManageDisabledFlag;
            },
            setDoorlockManageDisabledFlag(flag){
            	this.doorlockManageDisabledFlag = flag;
            },
            getFollowShowFlag(){
                return this.followShowFlag;
            },
            setFollowShowFlag(boolean){
                this.followShowFlag = boolean;
            },       
            getBatteryState(){
            	return this.batteryState();
            },
            setBatteryState(number){
            	this.batteryState = number
            },
            getBatteryPercent(){
            	return this.batteryPercent;
            },
            setBatteryPercent(percent){
            	this.batteryPercent = percent;
            },
            getRingingTime(){
            	return this.ringingTime;
            },
            setRingingTime(time){
            	this.ringingTime = time
            },
            getDoorbellRingingFlag(){
            	return this.doorbellRingingFlag;
            },
            setDoorbellRingingFlag(boolean){
            	this.doorbellRingingFlag = boolean;
            },
            getRingTime(){
            	return this.ringTime;
            },
            setRingTime(time){
            	this.ringTime = time;
            },
            getRemoteOpendoorFlag(){
            	return this.remoteOpendoorFlag;
            },
            setRemoteOpendoorFlag(flag){
            	this.remoteOpendoorFlag = flag;
            },
            getUuid(){
            	return this.uuid;
            },
            setUuid(){
            	this.uuid = id;
            },
            getIsFirstGetLockInfo(){
            	return this.isFirstGetLockInfo;
            },
            setIsFirstGetLockInfo(flag){
            	this.isFirstGetLockInfo = flag
            },
            getLockId(){
            	return this.lockId;
            },
            setLockId(id){
            	this.lockId = id;
            },
            getRole(){
            	return this.role;
            },
            setRole(bool){
            	this.role = bool;
            },
            getLockInfo(){
            	return this.lockInfo;
            },
            setLockInfo(info){
            	this.lockInfo = info;
            },
            getRemoteOpendoorShowFlag(){
            	return this.remoteOpendoorShowFlag;
            },
            setRemoteOpendoorShowFlag(flag){
            	this.remoteOpendoorShowFlag = flag;
            },
            getTextPassword(){
        		return this.textPassword;
        	},
        	setTextPassword(pwd){
        		this.textPassword = pwd;
        	},
        	setTextErrorTip(tip){
        		this.textErrorTip = tip;
        	},
        	getStatus(){
        		return this.status;
        	},
        	setStatus(status){
        		this.status = status;
        	},
            //tap 个人信息
            onMyInfoTap(){
            	myInfoTap(this);
            },
            //tap 绑定门锁
            onBindDoorlockTap(){
            	bindDoorlockTap();
            },
            //tap 门锁管理
            onDoorlockManageTap(){
                doorlockManageTap(this);
            },
            //tap 开门记录
            onOpendoorRecordTap(){
                opendoorRecordTap(this);
            }, 
            //tap 安全报警
            onSecurityAlarmTap(){
                securityAlarmTap(this);
            },
            //tap 门锁用户
            onDoorlockUserTap(){
                doorlockUserTap(this);
            },
            //tap 远程开门
            onRemoteOpendoorTap(){
                remoteOpendoorTap(this);
            },
            //tap 劫持报警
            onHijackAlarmTap(){
                hijackAlarmTap(this);
            },
            //tap 保存二维码到相册
            onSaveQRcodeButtonTap(){
                saveQRcodeButtonTap();
            },
            //tap 稍后关注
            onLaterFollowTap(){
                laterFollowTap(this);
            },
            //tap <
            onBackTap(){
                backTap(this);
            },
            onPasswordChange(text){
                passwordChange(this,text);            
            },  
            //tap 确定
            onConfirmButtonTap(){
                confirmButtonTap(this);
            },    
            onCommLoadingButtonTap(){
            	commLoadingButtonTap(this);
            },
            //tap 停止闪铃
            onStopDoorbellRing(){
            	stopDoorbellRing(this);
            }
        }   
    }).$mount('#app');
}

//配置组件参数
function initComponentsConfig() {   
    return {
        //图片轮播
        carousel: {
            initParam: {
                class:'custom-carousel',
                list:  [{image: '../../resources/image/image1.png'},
                        {image: '../../resources/image/image2.png'},
                        {image: '../../resources/image/image3.png'}],
                auto: true,
                autoTime: 2000,
                loop: true
            }
        },
        marquee: {
            initParam: {
                class: "custom-marquee",
                text: [Vue.t('device.defaultNewMsg')],
				pauseTime: 0.8,
				speed: 0,
				intervalTime: 2000,
				horizental: 0,
				direction: 1
            }
        },
        //开门记录switch 参数
        opendoorRecordSwitch: {
            initParam: {
                class: 'custom-switch',
                text: Vue.t('device.opendoorRecord'),
                autoChange: false
            }
        },
        //安全报警switch 参数
        securityAlarmSwitch: {
            initParam: {
                class: 'custom-switch',
                text: Vue.t('device.securityAlarm'),
                autoChange: false
            }
        },
        doorlockUserSwitch: {
            initParam: {
                class: 'custom-switch',
                text: Vue.t('device.doorlockUser'),
                autoChange: false
            }
        },
        //远程开门switch 参数
        remoteOpendoorSwitch: {
            initParam: {
                class: 'custom-switch',
                text: Vue.t('device.remoteOpendoor'),
                autoChange: false
            }
        },
        //劫持报警switch 参数
        hijackAlarmSwitch: {
            initParam: {
                class: 'custom-switch',
                text: Vue.t('device.hijackAlarm'),
                autoChange: false
            }
        },
        doorlockManageSwitch: {
            initParam: {
                class: 'custom-switch',
                text: Vue.t('device.doorlockManage'),
                autoChange: false
            }
        },
        //确定 button 参数
        saveQRcodeButton: {   
            initParam: {
                class: 'custom-button',
                text: Vue.t('btn.saveQRcode')
            }
        },
        confirmButton: {   
            initParam: {
                class: 'custom-button',
                text: Vue.t('btn.confirm')
            }
        },
        passwordInput: {
            initParam: {
                class: 'custom-text',
                icon: '&#xe64d;',
                placeholder: Vue.t('remoteOpendoor.passwordInputTip'),
                maxlength: config.password.maxlength
            }
        },
        ucommloading: {
            initParam: {
                class: 'custom-comm-loading',
                buttonText: Vue.t('btn.confirm'),
                text: Vue.t('remoteOpendoor.loading'),
                status: 0
            }
        },    
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        }                
    }
}

function loopGetLockInfo(self, delay, timeout){
	self.handle = setInterval(function(){
   		getLockInfo(self);
	},delay*1000);
    let time = setTimeout(function () {
        window.clearInterval(self.handle);
        window.clearTimeout(time);
    }, timeout * 1000);
}

function getDevices(self){
	iot.business.sds.getDevicesByUser({
	    success: (response) => {
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
			if(data){
				self.mac = data[0].mac;
				self.deviceId = data[0].sn;
				self.uuid = data[0].uuid;
				self.model = data[0].model;
				if(self.uuid){
					iot.business.device.getInfo({
					    data: {
					        sds: true,
					        uuid: self.uuid
					    },
					    success: (response) => {
					    	console.log("getInfo");
					    	console.log(response);
					    	let data = uPublic.checkResponseData(response.data);
					    	if(data){
					    		console.log(data);
						    	if(data.hasOwnProperty('relAccounts')){
						    		self.userInfo = data.relAccounts;
						    		getLockInfo(self);
						    	}
					    	}
					    },
					    error: (error) => {
					    	console.log(error);
					    },
					    complete: () => {}
					});
				}
			}else{
				setValueOfSwitch(self, true);
				self.setLockId(null);
				self.mac = null;
				self.deviceId = null;
				self.uuid = null;
				uComponents.changeMarqueeText(self, [Vue.t('device.defaultNewMsg')]);
//				console.log("不滚");
				self.activeFlag = false;
				self.opendoorRecordFlag = false;
	            self.securityAlarmFlag = false;
	            self.hijackAlarmFlag = false;
			}
	    },
	    error: (error) => {
	    	console.log(error);
	    	if(window.iotDebug){
                iotDebug.push('end: 获取设备信息'+JSON.stringify(error));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'获取设备信息');
            }
	    	uPublic.openRequestErrorAlert(self);
	    }
	});
}

function registerPushListener(self){
	iot.business.sds.registerPushListener({
	    success: (response) => {
			console.log("registerPushListener");
    		console.log(response);
    		let data = uPublic.checkResponseData(response.data.params.data);
    		if(data){
    			sdsDataPorcessing(self, data);
    		}
	    },
	    error: (error) => {
	    	console.log(error);
	    	if(window.iotDebug){
                iotDebug.push('end: 常链接失败'+JSON.stringify(error));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'常链接失败');
            }
	    	uPublic.openRequestErrorAlert(self);
	    }
	});
}

async function getRecordTime(self, data){
	try{
		self.notifyTime = await getRecordTimeMap('notifyTime');
	}
	catch (error) {
        console.log(error);
    }
	try{
		self.alarmTime = await getRecordTimeMap('alarmTime');
	}
	catch (error) {
        console.log(error);
    }
	try{
		self.openTime = await getRecordTimeMap('openTime');
	}
	catch (error) {
        console.log(error);
    }
	let newNotifyTime = moment(data.notify_time);
	let newAlarmTime = moment(data.alarm_time);
	let newOpenTime = moment(data.open_time);
//	console.log("newNotifyTime:"+newNotifyTime.format('YYYY-MM-DD hh:mm:ss'));
//	console.log("newAlarmTime:"+newAlarmTime.format('YYYY-MM-DD hh:mm:ss'));
//	console.log("newOpenTime:"+newOpenTime.format('YYYY-MM-DD hh:mm:ss'));
//	console.log("notifyTime:"+moment(self.notifyTime,moment.ISO_8601).format('YYYY-MM-DD hh:mm:ss'));
//	console.log("alarmTime:"+moment(self.alarmTime,moment.ISO_8601).format('YYYY-MM-DD hh:mm:ss'));
//	console.log("openTime:"+moment(self.openTime,moment.ISO_8601).format('YYYY-MM-DD hh:mm:ss'));
	let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
	if(self.notifyTime){
//		console.log("notifyTime"+newNotifyTime.diff(self.notifyTime, 'seconds'));
		self.notifyTime = moment(self.notifyTime,moment.ISO_8601);
		if(newNotifyTime != null && newNotifyTime.diff(self.notifyTime, 'seconds') > 0){
			self.securityAlarmFlag = true;
			self.notifyTime = newNotifyTime;
		}
	}else{
//		console.log("notifyTime"+now.diff(newNotifyTime, 'hours'));
		if(newNotifyTime != null && now.diff(newNotifyTime, 'hours') < 1){
            self.securityAlarmFlag = true;
            self.notifyTime = newNotifyTime;
		}
	}
	if(self.alarmTime){
		self.alarmTime = moment(self.alarmTime,moment.ISO_8601);
//		console.log("Alarm"+newAlarmTime.diff(self.alarmTime, 'seconds'));
		if(newAlarmTime != null && newAlarmTime.diff(self.alarmTime, 'seconds') > 0){
			self.hijackAlarmFlag = true;
			self.alarmTime = newAlarmTime;
		}
	}else{
//		console.log("Alarm"+now.diff(newAlarmTime, 'hours'));
		if(newAlarmTime != null && now.diff(newAlarmTime, 'hours') < 1){
            self.hijackAlarmFlag = true;
            self.alarmTime = newAlarmTime;
		}
	}
	if(self.openTime){
		self.openTime = moment(self.openTime,moment.ISO_8601);
//		console.log("openTime"+newOpenTime.diff(self.openTime, 'seconds'));
		if(newOpenTime != null && newOpenTime.diff(self.openTime, 'seconds') > 0){
			self.opendoorRecordFlag = true;
			self.openTime = newOpenTime;
		}
	}else{
//		console.log("openTime"+now.diff(newOpenTime, 'hours'));
		if(newOpenTime != null && now.diff(newOpenTime, 'hours') < 1){
            self.opendoorRecordFlag = true;
            self.openTime = newOpenTime;
		}
	}
}

//获取websql上的firstLogin
function getRecordTimeMap(time) {
    return new Promise(function (resolve, reject) {
//  	console.log(time);
        iot.storage.getMap(time, (res) => {
            if (res) {
//          	console.log('获取时间：'+moment(res).format('YYYY-MM-DD hh:mm:ss'));
                resolve(res);
            } else {
                reject(res);
            }
        }, (err) => {
            console.log(err);
        });
    })
}

function setValueOfSwitch(self, flag){
	self.setOpendoorRecordDisabledFlag(flag);
    self.setSecurityAlarmDisabledFlag(flag);
    self.setDoorlockUserDisabledFlag(flag);
    self.setHijackAlarmDisabledFlag(flag);
    self.setDoorlockManageDisabledFlag(flag);
    self.valueOpendoorRecord = !flag;
    self.valueSecurityAlarm = !flag;
    self.valueDoorlockUser = !flag;
    self.valueHijackAlarm = !flag;
    self.valueDoorlockManage =  !flag;
}

function getDeviceStatus(self){
	iot.business.sds.getDeviceStatus({
	    data: {
	        uuid: self.uuid
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
    		if(data){
    			setBatteryPercentAndIcon(self, data.BatteryPercentage.value);
    		}
	    },
	    error: (error) => {
	    	console.log(error);
	    	if(window.iotDebug){
                iotDebug.push('end: 获取设备状态'+JSON.stringify(error));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'获取设备状态');
            }
	    	uPublic.openRequestErrorAlert(self);
	    }
	});
}

function getLockInfo(self){  
	console.log("getLockInfo");
	iot.business.api.sendCustom('lock/getLockInfo',{
		data: {
			device_id: self.deviceId
		},
		success: (response) => {
			console.log(response);
			let data = uPublic.checkResponseData(response.data);
			if(data){
				getLockInfoSuccess(self, data);
//				getRecordTime(self, data);
//				//判断云端是否绑定
//				if(data.lock_id){
//					setValueOfSwitch(self, false);
//					self.setLockInfo(data);
//					self.setLockId(data.lock_id);
//					self.setRole(data.role);
//					if(self.isFirstGetLockInfo){
//						getDeviceStatus(self);
//						self.setIsFirstGetLockInfo(false);
//					}
//					if(data.info && data.info.length){
//						self.newMsg = [];
//						for(let i=0; i< data.info.length; i++){
//								let msg = '';
//								if(data.info[i].nickname == null){
//									msg = ' ID:' + data.info[i].openId;
//								}else{
//									msg = data.info[i].nickname;
//								}
//								self.newMsg.push(moment(data.info[i].time).format("YY.MM.DD  HH:mm") + msg + Vue.t('opendoorRecord.'+config.openDoorMode[data.info[i].mode]+''));
////							}
//						}
//						uComponents.changeMarqueeText(self, self.newMsg);
//						if(self.newMsg.length >= 2){
//							self.activeFlag = true;
//						}else{
//							self.activeFlag = false;
//						}
//					}else{
//						uComponents.changeMarqueeText(self, [Vue.t('device.noNewMsg')]);
//						self.activeFlag = false;
//					}
//				}else{
//					uComponents.changeMarqueeText(self, [Vue.t('device.defaultNewMsg')]);
//					self.activeFlag = false;
//				}
			}else{
				setValueOfSwitch(self, true);
				self.setLockId(null);
				self.mac = null;
				self.deviceId = null;
				self.uuid = null;
				uComponents.changeMarqueeText(self, [Vue.t('device.defaultNewMsg')]);
				self.activeFlag = false;
				self.opendoorRecordFlag = false;
	            self.securityAlarmFlag = false;
	            self.hijackAlarmFlag = false;
			}
		},
		error: (error) => {
			uPublic.openRequestErrorAlert(self);
	    	console.log(error);
		},
		complete: () => {
		}
	});
}

function getLockInfoSuccess(self, data){
	//判断云端是否绑定
	if(data.lock_id){
		//获取‘未读’小红点状态
		getRecordTime(self, data);
		//更改按钮为‘可点击’样式
		setValueOfSwitch(self, false);
		//设置门锁信息
		self.setLockInfo(data);
		self.setLockId(data.lock_id);
		self.setRole(data.role);
		//判断是否第一次获取门锁信息
		if(self.isFirstGetLockInfo){
			getDeviceStatus(self);
			self.setIsFirstGetLockInfo(false);
		}
		//拼接首页滚动的三条记录
		if(data.info && data.info.length){
			self.newMsg = [];
			for(let i=0; i< data.info.length; i++){
				let msg = '';
				if(data.info[i].nickname == null){
					msg = ' ID:' + data.info[i].openId;
				}else{
					msg = data.info[i].nickname;
				}
				self.newMsg.push(moment(data.info[i].time).format("YY.MM.DD  HH:mm") + msg + Vue.t('opendoorRecord.'+config.openDoorMode[data.info[i].mode]+''));
			}
			uComponents.changeMarqueeText(self, self.newMsg);
			if(self.newMsg.length >= 2){
				self.activeFlag = true;
			}else{
				self.activeFlag = false;
			}
		}else{
			uComponents.changeMarqueeText(self, [Vue.t('device.noNewMsg')]);
			self.activeFlag = false;
		}
	}else{
		uComponents.changeMarqueeText(self, [Vue.t('device.defaultNewMsg')]);
		self.activeFlag = false;
	}
}

////设置设备信息
//function setDevceInfo(self, data) {
//	console.log(data);
//	let notifyMode = ['1','2','3'];
//	console.log(notifyMode.indexOf(data.notify_type.value));
//	if(data.BatteryPercentage){
//		self.setBatteryPercent(data.BatteryPercentage.value);
//		if(data.BatteryPercentage.value >= 10){
//			//向上取整
//			self.setBatteryState(config.powerIcon[Math.ceil(data.BatteryPercentage.value/20)]);
//		}else{
//			self.setBatteryState(config.powerIcon[Math.round(data.BatteryPercentage.value/20)]);
//		}
//	}
//	if(data.action.value == 'notify'){
//		if(data.notify_type.value == 104){
//			//门铃响了
//			let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
//			let time = moment(data.time.value, "YY-MM-DD-hh-mm-ss");
////			console.log('门铃时间差'+now.diff(time,'seconds')+'timeout'+config.ringBell_timeout);
//			if(now.diff(time,'seconds') < config.ringBell_timeout && now.diff(time,'seconds') > 0){
//				self.setRingingTime(time.format("HH:mm"));
//				ringBell(self);
//			}
//		}else if(data.notify_type.value == 5){
//			//请求远程开门
////			self.setRemoteOpendoorFlag(true);
//			let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
//			let time = moment(data.time.value, "YY-MM-DD-hh-mm-ss");
////			console.log(now.diff(time,'seconds'));
//			if(now.diff(time,'seconds') < config.remote_timeout && now.diff(time,'seconds') > 0){
//				self.setValueRemoteOpendoor(true);
//				self.setRemoteOpendoorDisabledFlag(false);
//				setTimeout(function(){
//					self.setValueRemoteOpendoor(false);
//					self.setRemoteOpendoorDisabledFlag(true);
//				},(300-now.diff(time,'seconds'))*1000);
//			}
//			
//		}else if(notifyMode.indexOf(data.notify_type.value) != -1){
//			loopGetLockInfo(self, config.intervalTime, config.getHistoryTime);
//		}
//	}
//	if(data.action.value == 'lock_log' && (data.lock_action.value == '1' || data.lock_action.value == '4')){
//		//开门或远程开门成功
//		loopGetLockInfo(self, config.intervalTime, config.getHistoryTime);
//		if(data.lock_action.value == '4'){
//			uComponents.changeCommLoadingStatusAndText(self, 1, Vue.t('remoteOpendoor.openDoorSuccess'));
//		    uComponents.changeCommButtonText(self, Vue.t('btn.confirm'));
//		    self.setValueRemoteOpendoor(false);
//			self.setRemoteOpendoorDisabledFlag(true);
//		    self.setStatus(1);
//		}
//	}
//	if(data.ErrorCode.value == 1){
//		//远程开门失败
//		uComponents.changeCommLoadingStatusAndText(self, 2, Vue.t('remoteOpendoor.openDoorFailure'));
//		uComponents.changeCommButtonText(self, Vue.t('remoteOpendoor.remoteOpendoorAgain'));
//		self.setStatus(2);
//	}
//}

//sds消息处理方法
function sdsDataPorcessing(self, data){
	console.log(data);
	//设置电量百分比和icon
	setBatteryPercentAndIcon(self, data.BatteryPercentage.value);
	switch(data.action.value){
		case 'notify': 
			switch(data.notify_type.value){
				case '104': 
					//门铃
					setBellRing(self, moment(new Date(), "YYYY-MM-DD hh:mm:ss"));
					break;
				case '5':
					//远程开门请求
					setRemoteOpendoor(self, moment(new Date(), "YYYY-MM-DD hh:mm:ss"));
					break;
				case '1':
				case '2':
				case '3':
					//防撬、试错、欠电报警
					//轮循获取最新的历史记录
					loopGetLockInfo(self, config.intervalTime, config.getHistoryTime);
					break;
			}
		break;
		case 'lock_log':
			switch(data.lock_action.value){
				case '4':
					//远程开门成功
					//切换轮循loading样式
					setRemoteOpenDoorLoading(self, 1, Vue.t('remoteOpendoor.openDoorSuccess'), Vue.t('btn.confirm'));
				case '1':
					//轮循获取最新的历史记录
					loopGetLockInfo(self, config.intervalTime, config.getHistoryTime);
				break;
				case '5':
					//远程开门失败
					setRemoteOpenDoorLoading(self, 2, Vue.t('remoteOpendoor.openDoorFailure'), Vue.t('remoteOpendoor.remoteOpendoorAgain'));
				break;
			}
		break;
	}
//	if(data.ErrorCode.value == 1){
//		//远程开门失败
//		setRemoteOpenDoorLoading(self, 2, Vue.t('remoteOpendoor.openDoorFailure'), Vue.t('remoteOpendoor.remoteOpendoorAgain'));
//	}
}

//设置电量百分比、电量icon
function setBatteryPercentAndIcon(self, value){
	console.log('setBatteryPercentAndIcon'+value);
	self.setBatteryPercent(value);
	let state = 0;
	if(value >= 10){
		//向上取整
		state = config.powerIcon[Math.ceil(value/20)];
	}else{
		state = config.powerIcon[Math.round(value/20)];
	}
	self.setBatteryState(state);
}

//设置门铃
function setBellRing(self, time){
	let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
	time = moment(time, "YYYY-MM-DD hh:mm:ss");
	if(now.diff(time,'seconds') < config.ringBell_timeout && now.diff(time,'seconds') >= 0){
		self.setRingingTime(now.format("HH:mm"));
		ringBell(self);
	}
}

//设置远程开门
function setRemoteOpendoor(self, time){
	let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
	time = moment(time, "YYYY-MM-DD hh:mm:ss");
	console.log(now.diff(time,'seconds'));
	if(now.diff(time,'seconds') < config.remote_timeout && now.diff(time,'seconds') >= 0){
		self.setValueRemoteOpendoor(true);
		self.setRemoteOpendoorDisabledFlag(false);
		setTimeout(function(){
			self.setValueRemoteOpendoor(false);
			self.setRemoteOpendoorDisabledFlag(true);
		},(config.remote_timeout-now.diff(time,'seconds'))*1000);
	}
}

//设置远程开门样式
function setRemoteOpenDoorLoading(self, status, text, buttonText){
	switch(status){
		case 1:
			self.setValueRemoteOpendoor(false);
			self.setRemoteOpendoorDisabledFlag(true);
		case 2:
		case 0:
			self.setStatus(status);
			uComponents.changeCommLoadingStatusAndText(self, status, text);
		    uComponents.changeCommButtonText(self, buttonText);
			break;
	}
}

//响铃动画和铃声设置
function ringBell(self){	
	window.clearInterval(self.time);
	window.clearTimeout(self.timeout);
	let i = 0;
	simpleRingBell(self,i);
	self.setRingTime(config.ring_time);
	self.time = setInterval(function(){
		i++;
		simpleRingBell(self,i);
	},config.await_time*2);
}

function simpleRingBell(self,i){
	window.clearTimeout(self.timeout);
	self.setDoorbellRingingFlag(true);
	let p = plus.audio.createPlayer(config.audioUrl);
	p.play( function () {
		console.log( "Audio play success!" ); 
	}, function ( e ) {
		console.log( "Audio play error: " + e.message ); 
	});
	self.timeout = setTimeout(function(){
		p = plus.audio.createPlayer(config.audioUrl);
		p.play( function () {
			console.log( "Audio play success!" ); 
		}, function ( e ) {
			console.log( "Audio play error: " + e.message ); 
		});
		window.clearTimeout(self.timeout);
		self.timeout = setTimeout(function(){
			self.setDoorbellRingingFlag(false);
			window.clearTimeout(self.timeout);
			if(i>2){
				window.clearInterval(self.time);
			}
		},config.await_time*3/5);
		if(i>2){
			window.clearInterval(self.time);
		}
	},config.await_time*2/5);
	if(i>2){
		window.clearInterval(self.time);
	}
}

function pushAction(self, msg) {
    var payload = msg.payload;
    if (typeof payload == 'string') {
        payload = JSON.parse(msg.payload);
    }
    notifyDataProcessing(self, payload);
//  if(payload.type == "open"){
//  //开门推送
//  	getLockInfo(self);
//  }else if(payload.type == "notify"){
//  //安全报警
//  	getLockInfo(self);
//  }else if(payload.type == "alarm"){
//  //劫持报警
//  	getLockInfo(self);
//  }else if(payload.type == "ring"){
//  //门铃
//  	let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
//		let time = moment(payload.time, "YYYY-MM-DD hh:mm:ss");
//		console.log(now.diff(time,'seconds'));
//		if(now.diff(time,'seconds') < config.ringBell_timeout && now.diff(time,'seconds') > 0){
//			if(!self.getRingTime()){
//				self.setRingingTime(time.format("HH:mm"));
//				ringBell(self);
//			}
//		}
//  }else if(payload.type == "remoteOpen"){
//  //远程开门通知
//		let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
//		let time = moment(payload.time, "YYYY-MM-DD hh:mm:ss");
//		console.log(now.diff(time,'seconds'));
//		if(now.diff(time,'seconds') < config.remote_timeout && now.diff(time,'seconds') > 0){
//			self.setValueRemoteOpendoor(true);
//			self.setRemoteOpendoorDisabledFlag(false);
//			setTimeout(function(){
//				self.setValueRemoteOpendoor(false);
//				self.setRemoteOpendoorDisabledFlag(true);
//			},(300-now.diff(time,'seconds'))*1000);
//		}
//  }
}

//推送消息处理方法
function notifyDataProcessing(self, payload){
	switch(payload.type){
//  	case 'open':
//  	case 'notify':
//  	case 'alarm':
//  		//开门推送、安全报警、劫持报警
//  		//历史记录信息只拿一遍，不需要轮询
//  		getLockInfo(self);
//  	break;
//  	case 'ring':
//  		//门铃
//  		setBellRing(self, payload.time);
//  	break;
    	case 'remoteOpen':
    		//远程开门
    		setRemoteOpendoor(self, payload.time);
    	break;
    }
}

function notificationListener(self) {
//	if (plus.os.name == 'Android') {
//      setInterval(function () {
//          var pushMsgArray = plus.push.getAllMessage();
////          console.log(pushMsgArray);
//          if (pushMsgArray) {
//              var pushMsgLength = pushMsgArray.length;
//              if (pushMsgLength) {
//                  var pushMsg = pushMsgArray[(pushMsgArray.length - 1)];
//                  pushAction(self, pushMsg);
//                  plus.push.clear();
//              }
//          }
//      }, 2000);
//  }
    // 从系统消息中心点击消息启动应用事件
    plus.push.addEventListener('click', function (msg) {
//  	console.log("收到了click");
        pushAction(self, msg);
//      alert("click"+JSON.stringify(msg));
    }, false);
    // 应用从推送服务器接收到推送消息事件
    plus.push.addEventListener('receive', function (msg) {
//  	alert("收到了receive");
//      pushAction(self, msg);
//      alert("receive"+JSON.stringify(msg));
    }, false);
}


//tap 个人信息
function myInfoTap(self){
	iot.navigator.openWindow({
        url: '../myInfo/index.html',
        id: 'myInfo',
        extras: {
        	nickname: self.nickname
        }
    });
// uPublic.openWindow({
// 	 	url: '../myInfo/index.html',
//      id: 'myInfo',
//      extras: {
//      	nickname: self.nickname
//      }
// });
}

//tap 绑定门锁
function bindDoorlockTap(){
	iot.navigator.openWindow({
        url: '../addDevice/index.html',
        id: 'addDevice'
    });
}


//tap 门锁管理
function doorlockManageTap(self){
	if(self.valueDoorlockManage){
		iot.navigator.openWindow({
	        url: '../doorlockManage/index.html',
	        id: 'doorlockManage',
	        extras: {
	        	deviceId: self.deviceId,
	        	uuid: self.getUuid(),
	        	lockInfo: self.getLockInfo()
	        }
	    });
	}
}

//tap 开门记录
function opendoorRecordTap(self){
	
	if(self.valueOpendoorRecord){
		if(self.opendoorRecordFlag){
			console.log("停止所以interval");
			window.clearInterval(self.handle);
		}
		self.opendoorRecordFlag = false;
//		let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
//		setRecordTime('openTime', self.openTime.toISOString());
		iot.navigator.openWindow({
	        url: './opendoorRecord.html',
	        id: 'opendoorRecord',
	        extras: {
	        	deviceId: self.deviceId
	        }
	    });	
	}
}

//tap 安全报警
function securityAlarmTap(self){
	if(self.valueSecurityAlarm){
		if(self.notifyTime != null){
			if(self.securityAlarmFlag){
				window.clearInterval(self.handle);
			}
			self.securityAlarmFlag = false;
//			let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
//			setRecordTime('notifyTime', self.notifyTime);
		}
		iot.navigator.openWindow({
	        url: './alarmInfo.html',
	        id: 'alarmInfo',
	        extras: {
	        	deviceId: self.deviceId
	        }
	    });	
	}
}

//tap 门锁用户
function doorlockUserTap(self){
	if(self.valueDoorlockUser){
		iot.navigator.openWindow({
	      	url: '../doorlockUsers/index.html',
	      	id: 'doorlockUsers',
	      	extras: {
	        	deviceId: self.deviceId,
	        	uuid: self.getUuid(),
	        	lockId: self.getLockId(),
	        	role: self.getRole(),
	       	}
	  });	
	}
}

//tap 远程开门
function remoteOpendoorTap(self){
//	if(self.valueRemoteOpendoor){
//		iot.navigator.openWindow({
//	        url: './remoteOpendoor.html',
//	        id: 'remoteOpendoor',
//	        extras: {
//	        	uuid: self.getUuid(),
//	        	mac: self.mac
//	        }
//	    });	
//	} 
	if(self.valueRemoteOpendoor){
		self.setTextPassword('');
		self.setRemoteOpendoorShowFlag(true);
//		self.setValueRemoteOpendoor(false);
//		self.setRemoteOpendoorDisabledFlag(true);
	}
}

//tap 劫持报警
function hijackAlarmTap(self){
	
	if(self.valueHijackAlarm){
		console.log(self.alarmTime);
		if(self.alarmTime != null){
			if(self.hijackAlarmFlag){
				window.clearInterval(self.handle);
			}
			self.hijackAlarmFlag = false;
//			let now = moment(new Date(), "YYYY-MM-DD hh:mm:ss");
//			setRecordTime('alarmTime', self.alarmTime.toISOString());
		}
		iot.navigator.openWindow({
	        url: './hijackRecord.html',
	        id: 'hijackRecord',
	        extras: {
	        	deviceId: self.deviceId
	        }
	    });	
	}
}

//tap 保存二维码到相册
function saveQRcodeButtonTap(){
    alert('保存二维码到相册');
}

//tap 稍后关注
function laterFollowTap(self){
    self.setFollowShowFlag(false);
}

//tap 远程开门页面返回
function backTap(self){
	self.setRemoteOpendoorShowFlag(false);
//	self.setValueRemoteOpendoor(false);
//	self.setRemoteOpendoorDisabledFlag(true);
}

//远程开门密码
function passwordChange(self,text){
    self.setTextPassword(text);
    self.setTextErrorTip('');
    console.log('passwordChange: ' + self.textPassword);
}

//tap 确定
function confirmButtonTap(self){
	if(self.getTextPassword() == null || self.getTextPassword().trim() == ''){
		self.setTextErrorTip(Vue.t('remoteOpendoor.error.noPasswordTip'));	
	}else{
		uComponents.showCommLoading(self);
		self.setStatus(0);
    	uComponents.changeCommLoadingStatusAndText(self, 0, Vue.t('remoteOpendoor.loading'));
		console.log(self.mac);
		let keyIv = crypto.enkey(self.mac.replace(/:/g,''));
		console.log(keyIv);
		let pwd = crypto.encode(self.getTextPassword(), keyIv);
		console.log(pwd);
		let msg = crypto.decode(pwd, keyIv);
		console.log(msg);
		iot.business.sds.setDeviceStatus({
		    data: {
		        uuid: self.getUuid(),
		        setParams: {
		        	'action': {
		        		'value': 'openDoor'
		        	},
		            'remote_open_door': {
		                'value': pwd
		            }
		        }
		    },
		    success: (response) => {
		    	//密码下发成功
		    	console.log(response);
		    	self.getStatus(0);
		    },
		    error: (error) => {
		    	console.log(error);
		    	if(window.iotDebug){
	                iotDebug.push('end: 远程开门密码下发失败'+JSON.stringify(error));
	           	}
		    	if (window.iotDebug) {
	                iotDebug.upload(iot,'远程开门密码下发失败');
	            }
	           	uPublic.openRequestErrorAlert(self);
			},
		    complete(){
		    }
		});	
	}
	console.log('aaaa');
	setTimeout(function (){
		console.log(self.getStatus());
		if(self.getStatus() == 0){
			console.log("timeout");
			//连接失败
    		uComponents.changeCommLoadingStatusAndText(self, 2, Vue.t('remoteOpendoor.openDoorFailure'));
    		uComponents.changeCommButtonText(self, Vue.t('remoteOpendoor.remoteOpendoorAgain'));
    		self.setStatus(2);
		}
	},config.remote_opendoor_timeout);
}

//tap comm-loading ‘确认’
function commLoadingButtonTap(self){
	if(self.getStatus() == 1){
		//绑定成功
	    uComponents.hideCommLoading(self);
	    self.setRemoteOpendoorShowFlag(false);
	}else if(self.getStatus() == 2){
		//绑定失败
      	uComponents.hideCommLoading(self);
	}
}

function stopDoorbellRing(self){
	self.setDoorbellRingingFlag(false);
	self.setRingTime(0);
	window.clearInterval(self.time);
	window.clearTimeout(self.timeout);
}
