/**
* 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() {
	notificationListener();
    //通用 图片轮播、跑马灯、开关、按钮、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,
            //远程开门
            valueRemoteOpendoor: 0,
            //劫持报警
            valueHijackAlarm: 0,
            //门锁管理
            valueDoorlockManage: 0,
            activeFlag: true,
            followShowFlag: false,
            doorbellShowFlag: false,
            bindDoorlockShowFlag: false,
            //配置组件
            componentsConfig: initComponentsConfig(),
            //电量
            batteryState: null,
            //电量百分比
            batteryPercent: 100,
            //响铃时间
            ringingTime: null,
            //门铃是否响起
            doorbellRingingFlag: false,
            //是否显示"门铃响了"文本
            textDoorbellRingingFlag: false,
            //远程开门是否开启
            remoteOpendoorFlag: false,
            //设备ID
            deviceId: null,
            mac: null,
            //设备uuid
            uuid: null,
            //最新消息
            newMsg: '',
            //是否第一次获取门锁信息
            isFirstGetLockInfo: true,
            lockId: null,
            //获取用户的身份
            role: null,
            //是否显示远程开门页面
            remoteOpendoorShowFlag: false,
            //远程开门密码
            textPassword: null,  
            //远程开门错误提示
            textErrorTip: null,
            status: null
        },
        mounted(){
        	let self = this;
        	iot.navigator.closeAllBesidesItself();
        	//获取设备信息
        	iot.business.sds.getDevicesByUser({
			    success: (response) => {
			    	console.log(response);
			    	let data = uPublic.checkResponseData(response.data);
					if(response.data == 'success'){
						setValueOfSwitch(self, 0);
					}else if(data){
						self.mac = data[0].mac;
						self.deviceId = data[0].sn;
						self.uuid = data[0].uuid;
						getLockInfo(self);
					}
			    },
			    error: (error) => {}
			});
			
			//注册监听上报
			iot.business.sds.registerPushListener({
			    success: (response) => {
			    	console.log(response);
		    		let data = response.data;
		    		console.log(data);
//		    		if(data.hasOwnProperty('params')){
						console.log("registerPushListener");
		    			setDevceInfo(self, data.params.data);
//		    		}
			    },
			    error: (error) => {
			    	console.log(error);
			    	uPublic.openRequestErrorAlert(self);
			    }
			});
			
        },
        methods:{
            getValueOpendoorRecord(){
                return this.valueOpendoorRecord;
            },
            setValueOpendoorRecord(value){
                this.valueOpendoorRecord = value;
            },
            getValueSecurityAlarm(){
                return this.valueSecurityAlarm;
            },
            setValueSecurityAlarm(value){
                this.valueSecurityAlarm = value;
            },
            getValueRemoteOpendoor(){
                return this.valueRemoteOpendoor;
            },
            setValueRemoteOpendoor(value){
                this.valueRemoteOpendoor = value;
            },
            getValueHijackAlarm(){
                return this.valueHijackAlarm;
            },
            setValueHijackAlarm(value){
                this.valueHijackAlarm = value;
            }, 
            getValueDoorlockUser(){
            	return this.valueDoorlockUser;
            },
            setValueDoorlockUser(value){
            	this.valueDoorlockUser = value;
            },
            getValueDoorlockManage(){
            	return this.valueDoorlockManage;
            },
            setValueDoorlockManage(value){
            	this.valueDoorlockManage = value;
            },
            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;
            },
            getTextDoorbellRingingFlag(){
            	return this.textDoorbellRingingFlag;
            },
            setTextDoorbellRingingFlag(flag){
            	this.textDoorbellRingingFlag = flag;
            },
            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;
            },
            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);
            }
        }   
    }).$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')
            }
        },
        //开门记录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')
            }
        },
        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 setValueOfSwitch(self, flag){
	self.setValueOpendoorRecord(flag);
	self.setValueSecurityAlarm(flag);
	self.setValueRemoteOpendoor(flag);
	self.setValueHijackAlarm(flag);
	self.setValueDoorlockUser(flag);
	self.setValueDoorlockManage(flag);
}

function getDeviceStatus(self){
	iot.business.sds.getDeviceStatus({
	    data: {
	        uuid: self.uuid
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = response.data;
//			self.setBatteryPercent(data.BatteryPercentage.value);
//			self.setBatteryState(config.powerIcon[Math.round(data.BatteryPercentage.value/20)]);
			console.log("getStatus");
			setDevceInfo(self, data);
	    },
	    error: (error) => {
	    	console.log(error);
	    	uPublic.openRequestErrorAlert(self);
	    }
	});
}

function getLockInfo(self){
	console.log("getLockInfo");
	iot.business.api.sendCustom('lock/getLockInfo',{
		data: {
//			device_id:"600194283588"
			device_id: self.deviceId
		},
		success: (response) => {
			console.log(response);
			let data = uPublic.checkResponseData(response.data);
			if(data){
//				self.setBatteryPercent(data.battery);
//				self.setBatteryState(config.powerIcon[Math.round(data.battery/20)]);
				//判断云端是否绑定
				if(data.lock_id){
					setValueOfSwitch(self, 1);
					self.setLockId(data.lock_id);
					self.setRole(data.role);
					console.log(data.info);
					if(self.isFirstGetLockInfo){
						getDeviceStatus(self);
						self.setIsFirstGetLockInfo(false);
					}
					if(data.info && data.info.length){
						console.log(data.info);
						self.newMsg = '';
						for(let i=0; i< data.info.length; i++){
							let now = moment();
							let time = moment(data.info[i].time);
							console.log(now.diff(time,'hours'));
							if(now.diff(time,'hours') < 24){
								if(data.info[i].nickname == null){
									self.newMsg += moment(data.info[i].time).format("YY.MM.DD  HH:mm") + ' ID:' + data.info[i].openId + Vue.t('opendoorRecord.'+config.openDoorMode[data.info[i].mode]+'')+'<br>';
								}else{
									self.newMsg += moment(data.info[i].time).format("YY.MM.DD  HH:mm") + data.info[i].nickname + Vue.t('opendoorRecord.'+config.openDoorMode[data.info[i].mode]+'')+'<br>';
								}
							}
						}
						uComponents.changeMarqueeText(self, self.newMsg);
					}else{
						uComponents.changeMarqueeText(self, Vue.t('device.noNewMsg'));
						self.setRingingTime(null);
					}
				}else{
					uComponents.changeMarqueeText(self, Vue.t('device.defaultNewMsg'));
				}
			}else{
//				uComponents.changeMarqueeText(self, Vue.t('device.noNewMsg'));
//				self.setRingingTime(null);
			}
		},
		error: (error) => {
			console.log(error);
			uPublic.openRequestErrorAlert(self);
		},
		complete: () => {
		}
	});
}

//设置设备信息
function setDevceInfo(self, data) {
	console.log(data);
	self.setBatteryPercent(data.BatteryPercentage.value);
//	self.setBatteryState(config.powerIcon[Math.round(data.BatteryPercentage.value/20)]);
	if(data.BatteryPercentage.value >= 10){
		//向上取整
		//self.setIsYellow(true);
		self.setBatteryState(config.powerIcon[Math.ceil(data.BatteryPercentage.value/20)]);
	}else{
		//
		//self.setIsRed(true);
		self.setBatteryState(config.powerIcon[Math.round(data.BatteryPercentage.value/20)]);
	}
	if(data.action.value == 'notify'){
		if(data.notify_type.value == 104){
			//门铃响了
			let now = moment();
			let time = moment(data.time.value, "YY-MM-DD-hh-mm-ss");
			if(now.diff(time,'hours') < 24){
				self.setTextDoorbellRingingFlag(true);
				self.setRingingTime(time.format("HH:mm"));
				console.log("innnnn");
				ringBell(self);
			}
		}else if(data.notify_type.value == 5){
			//请求远程开门
			self.setRemoteOpendoorFlag(true);
		}
	}
	if(data.action.value == 'lock_log' && (data.lock_action.value == '1' || data.lock_action.value == '4')){
		//开门或远程开门成功
		getLockInfo(self);
		if(data.lock_action.value == '4'){
			uComponents.changeCommLoadingStatusAndText(self, 2, Vue.t('remoteOpendoor.openDoorSuccess'));
		    uComponents.changeCommButtonText(self, Vue.t('btn.confirm'));
		    self.setStatus(1);
		}
	}
}
async function ringBell(self){
		try{		
			for(let i =0 ; i< (config.ring_time/(config.shake_times+config.await_time));){
				self.setDoorbellRingingFlag(true);
				let time = await sleep(1000*config.shake_times);
	        	self.setDoorbellRingingFlag(false);  
	        	time = await sleep(config.await_time);
				i++;
			}
		}
		catch (err){
			console.log(err);
		}
}

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

function pushAction(msg) {
    console.log(msg);
//  var payload = msg.payload;
//  if (typeof payload == 'string') {
//      payload = JSON.parse(msg.payload);
//  }
//  console.log(payload);
//  if (payload.hasOwnProperty('date')) {
//      console.log('in evaluation');
//  } else if (payload.hasOwnProperty('report')) {
//      console.log('in slim');
//  }
}

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


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

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


//tap 门锁管理
function doorlockManageTap(self){
	if(self.getValueDoorlockManage() == 1){
		iot.navigator.openWindow({
	        url: '../doorlockManage/index.html',
	        id: 'doorlockManage',
	        extras: {
	        	deviceId: self.deviceId,
	        	uuid: self.getUuid(),
	        	role: self.getRole()
	        }
	    });
	}
}

//tap 开门记录
function opendoorRecordTap(self){
	if(self.getValueOpendoorRecord() == 1){
		iot.navigator.openWindow({
	        url: './opendoorRecord.html',
	        id: 'opendoorRecord',
	        extras: {
	        	deviceId: self.deviceId
	        }
	    });	
	}
}

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

//tap 门锁用户
function doorlockUserTap(self){
	if(self.getValueDoorlockUser() == 1){
		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.getValueRemoteOpendoor() == 1){
//		iot.navigator.openWindow({
//	        url: './remoteOpendoor.html',
//	        id: 'remoteOpendoor',
//	        extras: {
//	        	uuid: self.getUuid(),
//	        	mac: self.mac
//	        }
//	    });	
//	} 
	self.setRemoteOpendoorShowFlag(true);
	self.setRemoteOpendoorFlag(false);
}

//tap 劫持报警
function hijackAlarmTap(self){
	if(self.getValueHijackAlarm() == 1){
		iot.navigator.openWindow({
	        url: './hijackRecord.html',
	        id: 'hijackRecord',
	        extras: {
	        	deviceId: self.deviceId
	        }
	    });	
	}
}

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

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

function backTap(self){
	self.setRemoteOpendoorShowFlag(false);
}

function passwordChange(self,text){
    self.setTextPassword(text);
    self.setTextErrorTip('');
    console.log('passwordChange: ' + self.textPassword);
}

//tap 确定
function confirmButtonTap(self){
	console.log(self.getTextPassword());
	if(self.getTextPassword() == null || self.getTextPassword().trim() == ''){
		self.setTextErrorTip(Vue.t('remoteOpendoor.error.noPasswordTip'));	
	}else{
		uComponents.showCommLoading(self);
		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
		                'value': self.getTextPassword()
		            }
		        }
		    },
		    success: (response) => {
		    	//密码下发成功
		    	console.log(response);
		    	self.setStatus(0);
		    },
		    error: (error) => {
		    	console.log(error);
			},
		    complete(){
				uComponents.hideLoading(self);
		    }
		});	
	}
	setTimeout(function (){
		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);
}

function commLoadingButtonTap(self){
	if(self.getStatus() == 1){
		 //绑定成功
	    uComponents.hideCommLoading(self);
	    self.setRemoteOpendoorShowFlag(false);
	    
	}else if(self.getStatus() == 2){
		//绑定失败
      	uComponents.hideCommLoading(self);
      	self.setStatus(0);
      	uComponents.changeCommLoadingStatusAndText(self, 0, Vue.t('remoteOpendoor.loading'));
	}
}
