/**
* 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 Request from "../../public/request.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';
import uloop from '../../public/uloop.js';
import unotify from '../../public/unotify.js';

const ON_LINE = 'on';
const OFF_LINE = 'off';
iot.ready(init);
function init() {
	uPublic.closeSlideBack();
    //通用 图片轮播、跑马灯、开关、按钮、dialog、loading组件
    uPublic.componentsInit(['u-carousel','u-marquee','u-switch','u-button','u-dialog','u-loading','u-text','u-comm-loading']);
//  uPublic.componentsExtend(['update-app']);
	Request.versionRequest('device/getVersion',(info)=>{
        let json = {
                    downloadUrl : info.url,
                    version: info.version,
                    title :Vue.t('newFeature.tip'),
                    content :Vue.t('newFeature.newVersion'),
                    ok :Vue.t('newFeature.update'),
                    cancel :Vue.t('newFeature.miss')
        };
        iot.native.checkUpdate(json);
    },(err)=>{
            console(err);
    });

    if(iot.navigator.getExtras().needClose){
    	iot.navigator.closeAllBesidesItself();
    }
    
//  console.log(iot.native.isNotifycationOpen());
//  iot.native.toNotifycationSetting();

    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: true,
            //配置组件
            componentsConfig: initComponentsConfig(),
            //
            followShowFlag: false,
            //电量icon
            batteryState: '',
            //电量百分比
            batteryPercent: 100,
            //消息时间
            msgTime: null,
            //消息文本提示
            msgText: '',
            //门铃是否响起
            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,
            msgClass: "default_img",
            warmingShowFlag: false,
            normalApertureShow: false,
            warmingApertureShow: false,
            //是否显示远程开门页面
            remoteOpendoorShowFlag: false,
            //远程开门密码
            textPassword: null,  
            //远程开门错误提示
            textErrorTip: null,
            //当前状态
            status: 0,
            flag: true,
            //门铃等待计时器
            time: null,
            //门铃总计时器
            timeout: null,
            //远程开门计时器
            remoteTime: null,
            boolPasswordMinlength: false
        },
        mounted(){
        	//显示loading
			uComponents.showLoading(this);
			//监听推送
        	notificationListener(this);
        	//获取设备信息
        	getDevices(this);
			//注册监听上报
//			registerPushListener(this);
			unotify.getCid((response) => {
				console.log(response);
			},(error) => {
				console.log(error);
			});
			let self = this;
			window.addEventListener('returnPage',function(event){
				console.log('returnPage');
				//获取设备信息
	        	getDevices(self);
				//注册监听上报
//				registerPushListener(self);
				if(event.detail.needClose){
					iot.navigator.closeAllBesidesItself();
				}
			});
//			ringBell(self);
//			setTimeout(() => {
//				ringBell(self);
//				setTimeout(() =>{
//					ringBell(self);
//				},1000);
//			},1000);
        },
        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;
            },
            getMsgTime(){
            	return this.msgTime;
            },
            setMsgTime(time){
            	this.msgTime = time
            },
            getMsgText(){
            	return this.msgText;
            },
            setMsgText(text){
            	this.msgText = text;
            },
            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;
            },
            getMsgClass(){
            	return this.msgClass;
            },
            setMsgClass(src){
            	this.msgClass = src;
            },
            getWarmingShowFlag(){
            	return this.warmingShowFlag;
            },
            setWarmingShowFlag(flag){
            	this.warmingShowFlag = flag;
            },
            getNormalApertureShow(){
            	return this.normalApertureShow;
            },
            setNormalApertureShow(flag){
            	this.normalApertureShow = flag;
            },
            getWarmingApertureShow(){
            	return this.warmingApertureShow;
            },
            setWarmingApertureShow(flag){
            	this.warmingApertureShow = flag;
            },
            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);
            },
            onPasswordMatchlength(value){
            	passwordMatchlength(this, value);
            }
        }   
    }).$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,
                minlength: config.password.minlength
            }
        },
        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 getDevices(self){
	iot.business.sds.getDevicesByUser({
	    success: (response) => {
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
			if(data){
				getDevicesSuccess(self, data);
			}else{
				initDeviceInfo(self);
				uComponents.hideLoading(self);
			}
	    },
	    error: (error) => {
	    	console.log(error);
	    	if(window.iotDebug){
                iotDebug.push('end: 获取设备信息'+JSON.stringify(error));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'获取设备信息');
            }
//	    	uPublic.openRequestErrorAlert(self);
			uComponents.openAlert(self, Vue.t('device.networkError'), {
		        text: Vue.t('btn.iSee'), callback: function () {
		        	plus.runtime.quit();
		        }
		    });
	    	uComponents.hideLoading(self);
	    },
		complete: () => {}
	});
}

function getDevicesSuccess(self, 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(response);
		    	let data = uPublic.checkResponseData(response.data);
		    	if(data){
			    	getLockInfo(self);
		    	}
		    },
		    error: (error) => {
		    	console.log(error);
		    },
		    complete: () => {}
		});
	}
}

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);
			}else{
				initDeviceInfo(self);
			}
		},
		error: (error) => {
			uPublic.openRequestErrorAlert(self);
			initDeviceInfo(self);
	    	console.log(error);
		},
		complete: () => {
			uComponents.hideLoading(self);
		}
	});
}

function getLockInfoSuccess(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);
//		}
		//存储最后一条历史记录的ID
		let historyId = null
		historyId = data.info.historyId ? data.info.historyId : null;
		iot.storage.setMap('historyId', historyId, (res) => {
			console.log(res);
	    }, () => {
	    });
	    //存储历史、安全、劫持记录的时间
	    let historyRecord = data.info.history;
	    if((historyRecord.open.length != 0) || Boolean(historyRecord.alarm) || Boolean(historyRecord.notify)){
	    	updateHistoryMap(self, historyRecord);
	    }else{
	    	iot.storage.delMaps(['historyId','history'], (response) => {
	    		console.log(response);
	    		updateHistoryMap(self, historyRecord);
		    }, (error) => {
		    	console.log(error);
		    });
	    }
		//拼接首页滚动的三条记录
		getTreenRecord(self, data.info.history.open);
	}else{
		uComponents.changeMarqueeText(self, [Vue.t('device.defaultNewMsg')]);
		self.activeFlag = false;
	}
}

//拼接首页滚动的三条记录
function getTreenRecord(self, record){
	if(record && record.length){
		self.newMsg = [];
		for(let i = record.length - 1; i >= 0; i--){
			let msg = '';
			if((record[i].mode != 30) && (record[i].mode != 5)){
				msg = record[i].nickname;
			}
			self.newMsg.push(moment(record[i].time).format("YY.MM.DD  HH:mm")+ ' ' + msg + Vue.t('device.use') + Vue.t('opendoorRecord.'+config.openDoorMode[record[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;
	}
}

//获取设备的初始状态
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);
    			iot.storage.setMap('onLineState', data.onlineState.value, (response) => {
					console.log(res);
			    }, () => {});
    			registerPushListener(self);
    		}
	    },
	    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 updateHistoryMap(self, historyRecord){
	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;
	}
	catch (error) {
        console.log(error);
   	}
	let openHistory = historyRecord.open;
	
	let newHistory = oldHistory;
	
	let now = moment(new Date()).unix();
	
    if(openHistory.length && oldHistory.open.time < moment(openHistory[0].time).unix() && now - moment(openHistory[0].time).unix() < config.newMsg_timeout){
    	newHistory.open.time = moment(openHistory[0].time).unix();
    	newHistory.open.isReadFlag = false;
    	let record = openHistory;
    	if(record && record.length){
			for(let i=0; i< record.length; i++){
				let msg = '';
				if((record[i].mode != 30) && (record[i].mode != 5)){
					msg = record[i].nickname;
				}
				self.newMsg.shift();
				self.newMsg.push(moment(record[i].time).format("YY.MM.DD  HH:mm")+ ' ' + msg + Vue.t('device.use') + Vue.t('opendoorRecord.'+config.openDoorMode[record[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;
		}
    }
    
    let historyType = ['alarm','notify'];
    for(let i=0 ; i < historyType.length; i++){
    	if(historyRecord.hasOwnProperty(historyType[i]) && oldHistory[historyType[i]].time < moment(historyRecord[historyType[i]]).unix() && now - moment(historyRecord[historyType[i]]).unix() < config.newMsg_timeout){
	    	newHistory[historyType[i]].time = moment(historyRecord[historyType[i]]).unix();
	    	newHistory[historyType[i]].isReadFlag = false;
	    	
	    	console.log(moment(historyRecord[historyType[i]]).unix());
	    }
    }
    
    console.log(oldHistory);
    console.log(newHistory);
    
    
    iot.storage.setMap('history', newHistory, (response) => {
		console.log(res);
    }, () => {
    });
    
    iot.storage.getMap('history', (response) => {
		self.securityAlarmFlag = !response.notify.isReadFlag;
		self.hijackAlarmFlag = !response.alarm.isReadFlag;
		self.opendoorRecordFlag = !response.open.isReadFlag;
		console.log(self.securityAlarmFlag);
		if(self.hijackAlarmFlag == true){
			if(historyRecord.alarm){
				//显示劫持报警
				setMsgStatus(self, true, "hijack_img", false, true, moment(historyRecord.alarm,"YYYY-MM-DD hh:mm:ss").format("HH:mm"), Vue.t('device.hijackAlarm'));
			}else{
				//显示劫持报警
				setMsgStatus(self, true, "hijack_img", false, true, moment.unix(response.alarm.time).format("HH:mm"), Vue.t('device.hijackAlarm'));
			}
		}else if(self.securityAlarmFlag == true){
			if(historyRecord.notify){
				//显示安全报警
				setMsgStatus(self, true, "securityAlarm_img", false, true, moment(historyRecord.notify,"YYYY-MM-DD hh:mm:ss").format("HH:mm"), Vue.t('device.securityAlarm'));
			}else{
				//显示安全报警
				setMsgStatus(self, true, "securityAlarm_img", false, true, moment.unix(response.notify.time).format("HH:mm"), Vue.t('device.securityAlarm'));
			}
		}else{
			if((self.getMsgClass() == 'hijack_img') || (self.getMsgClass() == 'securityAlarm_img')){
				setMsgStatus(self, false, "default_img", false, false, '', '');
			}
		}
    }, () => {
    });
}

//云端获取设备信息失败
function initDeviceInfo(self){
    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;
    self.setRemoteOpendoorDisabledFlag(true);
    self.setValueRemoteOpendoor(0);
}

async function loopGetLockInfo(self, delay, timeout){
	
	let oldHistoryId = null;
    try{
    	let historyId = await iot.storage.getMap('historyId');
    	if(historyId){
    		oldHistoryId = historyId;
    	}
    }
    catch (error){
    	console.log(error);
    }
    console.log(oldHistoryId);
	new uloop({
		loopContent: () => {
			var urlParams = {
					type: 'post',
					data: {
					history_id: oldHistoryId,
					device_id: self.deviceId
				}
			};
			return iot.business.api.send('lock/getNewInfo', urlParams, true, false);
//			return plus.push.getClientInfo().clientid;
		},
		times: 3,
		interval:{
			delay: config.intervalTime*1000,
			cb: {
				success: (response) => {
					console.log('intervalcbSuccess:'+JSON.stringify(response));	
				},
				error: (error) => {
					console.log('intervalcbError:'+JSON.stringify(error));
				}
			}
		}, 
		fincb: {
			success:(response) => {
				console.log(response);
				let historyRecord = response.data.history;
				updateHistoryMap(self, historyRecord);
			},
			error: (error) => {
		    	console.log(error);
			},
			complete: () => {
				uComponents.hideLoading(self);
			}
		},
		stopcondition: async (response) => {
			console.log(response);
			let data = response.data;
			if(data.hasOwnProperty('historyId')){
				let newHistoryId = data.historyId;
	    		if(oldHistoryId != newHistoryId){
					iot.storage.setMap('historyId', newHistoryId, (res) => {
						console.log(res);
				    }, () => {
				    });
	    			return true;
	    		}
			}
	    }
	}).start();
}

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

//sds消息处理方法
async function sdsDataPorcessing(self, data){
	let onlineState = await iot.storage.getMap('onLineState');
	console.log(data);
	//设置电量百分比和icon
	setBatteryPercentAndIcon(self, data.BatteryPercentage.value);
	if(onlineState == data.onlineState.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;
					case '6':
						//远程开门超时
						if(self.getRemoteOpendoorShowFlag()){
							uComponents.openAlert(self, Vue.t('remoteOpendoor.remoteTimeout'), {
						        text: Vue.t('dialog.confirm'), callback: function () {
						        	self.setValueRemoteOpendoor(false);
									self.setRemoteOpendoorDisabledFlag(true);
									self.setRemoteOpendoorShowFlag(false);
									if(self.getMsgClass() == 'remoteOpendoor_img'){
										setMsgStatus(self, false, "default_img", false, false, '', '');
									}
									window.clearTimeout(self.remoteTime);
									uComponents.hideCommLoading(self);
						        }
						    });
						}else{
							self.setValueRemoteOpendoor(false);
							self.setRemoteOpendoorDisabledFlag(true);
							if(self.getMsgClass() == 'remoteOpendoor_img'){
								setMsgStatus(self, false, "default_img", false, false, '', '');
							}
						}
					break;
				}
			break;
		}
	}else{
		iot.storage.setMap('onLineState', data.onlineState.value, (response) => {
			console.log(res);
	    }, () => {});
	}
}

//设置电量百分比、电量icon
function setBatteryPercentAndIcon(self, value){
	console.log('setBatteryPercentAndIcon'+value);
	self.setBatteryPercent(value);
	let state = 5;
	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.pushMsg_timeout && now.diff(time,'seconds') >= 0){
		ringBell(self, time);
	}
}

//设置远程开门
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.pushMsg_timeout && now.diff(time,'seconds') >= 0 && (self.getRole() == 0)){
		self.setValueRemoteOpendoor(true);
		self.setRemoteOpendoorDisabledFlag(false);
		//停止响铃
		stopDoorbellRing(self);
		if((self.getMsgClass() != 'hijack_img') && (self.getMsgClass() != 'securityAlarm_img')){
			setMsgStatus(self, false, "remoteOpendoor_img", true, false, time.format("HH:mm"), Vue.t('device.remoteOpendoor'));
		}
//		//设置当前为普通状态
//		self.setWarmingShowFlag(false);
//		//更换icon
//		self.setMsgIconSrc("../../resources/image/green_remoteOpendoor_icon.png");
//		//开启普通动画效果
//		self.setNormalApertureShow(true);
//		self.setMsgTime(time.format("HH:mm"));
//		self.setMsgText(Vue.t('device.remoteOpendoor'));
		setTimeout(function(){
			self.setValueRemoteOpendoor(false);
			self.setRemoteOpendoorDisabledFlag(true);
			if(self.getMsgClass() == 'remoteOpendoor_img'){
				setMsgStatus(self, false, "default_img", false, false, '', '');
			}
		},(config.remote_timeout-now.diff(time,'seconds'))*1000);
	}
}

//设置信息提示
function setMsgStatus(self, warmingShow, imgClass, normalAperture, warmingAperture, msgTime, msgText){
	//设置当前为普通状态
	self.setWarmingShowFlag(warmingShow);
	//更换icon
	self.setMsgClass(imgClass);
	//开启普通动画效果
	self.setNormalApertureShow(normalAperture);
	self.setWarmingApertureShow(warmingAperture);
	self.setMsgTime(msgTime);
	self.setMsgText(msgText);
}


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

//响铃动画和铃声设置
function ringBell(self, time){	
	if(self.getDoorbellRingingFlag() === false && (self.getMsgClass() != 'remoteOpendoor_img') && (self.getMsgClass() != 'hijack_img') && (self.getMsgClass() != 'securityAlarm_img')){
		self.setDoorbellRingingFlag(true);
		setMsgStatus(self, false, "doorbell_img", true, false, time.format("HH:mm"), Vue.t('device.doorLockRinging'));
		let p = plus.audio.createPlayer(config.audioUrl);
		self.timeout = setTimeout(() => {
			p = plus.audio.createPlayer(config.audioUrl);
			p.play( function () {
				console.log( "Audio play success!" ); 
			}, function ( e ) {
				console.log( "Audio play error: " + e.message ); 
			});
			console.log(self.timeout);
			self.timeout  = setTimeout(() => {
				console.log("in2");
				p = plus.audio.createPlayer(config.audioUrl);
				p.play( function () {
					console.log( "Audio play success!" ); 
				}, function ( e ) {
					console.log( "Audio play error: " + e.message ); 
				});
				console.log(self.timeout);
				self.timeout  = setTimeout(() => {
					self.setDoorbellRingingFlag(false);
					self.setNormalApertureShow(false);
					console.log(self.timeout);
				},1500);
			},2000);
		},500);
	}
}

function pushAction(self, msg) {
    var payload = msg.payload;
    if (typeof payload == 'string') {
        payload = JSON.parse(msg.payload);
    }
    notifyDataProcessing(self, payload);
}

//推送消息处理方法
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) {
    // 从系统消息中心点击消息启动应用事件
    plus.push.addEventListener('click', function (msg) {
        pushAction(self, msg);
    }, false);
    // 应用从推送服务器接收到推送消息事件
    plus.push.addEventListener('receive', function (msg) {
    }, false);
}


//tap 个人信息
function myInfoTap(self){
	iot.navigator.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 opendoorRecordTap(self){
	if(self.valueOpendoorRecord){
		self.opendoorRecordFlag = false;
		iot.navigator.openWindow({
	        url: './opendoorRecord.html',
	        id: 'opendoorRecord',
	        extras: {
	        	deviceId: self.deviceId
	        }
	    });	
	}
}

//tap 安全报警
function securityAlarmTap(self){
	if(self.valueSecurityAlarm){
		self.securityAlarmFlag = false;
		iot.navigator.openWindow({
	        url: './alarmInfo.html',
	        id: 'alarmInfo',
	        extras: {
	        	deviceId: self.deviceId
	        }
	    });	
	}
}

//tap 劫持报警
function hijackAlarmTap(self){
	if(self.valueHijackAlarm){
		self.hijackAlarmFlag = false;
		iot.navigator.openWindow({
	        url: './hijackRecord.html',
	        id: 'hijackRecord',
	        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){
	iot.business.sds.getDeviceStatus({
	    data: {
	        uuid: self.uuid
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
    		if(data){
    			if(data.onlineState.value == ON_LINE){
					if(self.valueRemoteOpendoor){
						self.setTextPassword('');
						self.setRemoteOpendoorShowFlag(true);
					}
    			}else{
	    			uComponents.openAlert(self, Vue.t('remoteOpendoor.offlineTip'), {
				        text: Vue.t('dialog.confirm'), callback: function () {
				        	self.setValueRemoteOpendoor(false);
							self.setRemoteOpendoorDisabledFlag(true);
							if(self.getMsgClass() == 'remoteOpendoor_img'){
								setMsgStatus(self, false, "default_img", false, false, '', '');
							}
				        }
				    });
	    		}
    		}
	    },
	    error: (error) => {
	    	console.log(error);
	    	uPublic.openRequestErrorAlert(self);
	    }
	});
}

//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 stopDoorbellRing(self){
	self.setDoorbellRingingFlag(false);
	self.setNormalApertureShow(false);
	self.setRingTime(0);
	window.clearInterval(self.time);
	window.clearTimeout(self.timeout);
}

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

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

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

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

//获取远程密码是否达到最小长度
function passwordMatchlength(self, bool) {
	console.log(bool);
	self.boolPasswordMinlength = bool;
}

//tap 确定（远程开门密码）
function confirmButtonTap(self){
	iot.business.sds.getDeviceStatus({
	    data: {
	        uuid: self.uuid
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
    		if(data){
				if(data.onlineState.value == ON_LINE){
					if(self.boolPasswordMinlength){
						if(self.getTextPassword() == null || self.getTextPassword().trim() == ''){
							self.setTextErrorTip(Vue.t('remoteOpendoor.error.noPasswordTip'));	
						}else if(uPublic.checkString(self.getTextPassword())){
							self.setTextErrorTip(Vue.t('remoteOpendoor.textlengthTip'));
						}else if(self.textErrorTip == ''){
							uComponents.showCommLoading(self);
							setRemoteOpenDoorLoading(self, 0, Vue.t('remoteOpendoor.loading'));
							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);
							    },
							    error: (error) => {
							    	console.log(error);
							    	if(window.iotDebug){
						                iotDebug.push('end: 远程开门密码下发失败'+JSON.stringify(error));
						           	}
							    	if (window.iotDebug) {
						                iotDebug.upload(iot,'远程开门密码下发失败');
						            }
						           	uPublic.openRequestErrorAlert(self);
						           	uComponents.hideCommLoading(self);
								},
							    complete(){
							    }
							});	
						}
						self.remoteTime = setTimeout(function (){
							if(self.getStatus() == 0){
								setRemoteOpenDoorLoading(self, 2, Vue.t('remoteOpendoor.remoteTimeout'), Vue.t('remoteOpendoor.remoteOpendoorAgain'));
							}
						},config.remote_opendoor_timeout);
					}else{
						self.setTextErrorTip(Vue.t('remoteOpendoor.textlengthTip'));	
//						uComponents.openAlert(self, Vue.t('remoteOpendoor.textlengthTip'), {
//					        text: Vue.t('dialog.confirm'), callback: function () {
//					        	
//					        }
//					    });
					}
				}else{
					uComponents.openAlert(self, Vue.t('remoteOpendoor.offlineTip'), {
				        text: Vue.t('dialog.confirm'), callback: function () {
				        	self.setRemoteOpendoorShowFlag(false);
				        	self.setValueRemoteOpendoor(false);
							self.setRemoteOpendoorDisabledFlag(true);
							if(self.getMsgClass() == 'remoteOpendoor_img'){
								setMsgStatus(self, false, "default_img", false, false, '', '');
							}
				        }
				    });
				}
			}else{}
	    },
	    error: (error) => {
	    	console.log(error);
	    	uPublic.openRequestErrorAlert(self);
	    	uComponents.hideCommLoading(self);
	    }
	});
}

//tap comm-loading ‘确认’
function commLoadingButtonTap(self){
	if(self.getStatus() == 1){
		//远程开门成功
	    self.setRemoteOpendoorShowFlag(false);
	}
	uComponents.hideCommLoading(self);
}

