/**
* v_index.js
* Version: 0.1
* User: wy
* Date: 2017-09-06
* Copyright(c)  2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* 主控页面
*/
import moment from 'moment';
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']);
    const app = new Vue({
        data:{ 
            //开门记录
            valueOpendoorRecord: 1,
            //安全报警
            valueSecurityAlarm: 1,
            //门锁用户
            valueDoorlockUser: 1,
            //远程开门
            valueRemoteOpendoor: 1,
            //劫持报警
            valueHijackAlarm: 1,
            //门锁管理
            valueDoorlockManage: 1,
            activeFlag: true,
            followShowFlag: false,
            doorbellShowFlag: true,
            bindDoorlockShowFlag: false,
            //配置组件
            componentsConfig: initComponentsConfig(),
            //电量
            batteryState: 5,
            //电量百分比
            batteryPercent: 100,
            //响铃时间
            ringingTime: null,
            //门铃是否响起
            doorbellRingingFlag: false,
            //远程开门是否开启
            remoteOpendoorFlag: false,
            //设备ID
            deviceId: null,
            //设备uuid
            uuid: null,
            //最新消息
            newMsg: 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'){
						self.setValueOpendoorRecord(0);
						self.setValueSecurityAlarm(0);
						self.setValueRemoteOpendoor(0);
						self.setValueHijackAlarm(0);
						self.setValueDoorlockUser(0);
						self.setValueDoorlockManage(0);
					}else if(data){
						self.uuid = data[0].uuid;
						self.deviceId = data[0].sn;
						self.setValueOpendoorRecord(1);
						self.setValueSecurityAlarm(1);
						self.setValueRemoteOpendoor(1);
						self.setValueHijackAlarm(1);
						self.setValueDoorlockUser(1);
						self.setValueDoorlockManage(1);
						iot.business.sds.getDeviceStatus({
						    data: {
						        uuid: self.uuid
						    },
						    success: (response) => {
						    	console.log(response);
						    	iot.business.sds.getDeviceStatus({
								    data: {
								        uuid: self.uuid
								    },
								    success: (response) => {
								    	console.log(response);
								    	let data = response.data;
								    	self.setBatteryPercent(data.battery.value);
										self.setBatteryState(config.powerIcon[Math.round(data.battery.value/20)]);
										
										setDevceInfo(self, data);
								    },
								    error: (error) => {
								    	console.log(error);
								    	
								    }
								});
						    },
						    error: (error) => {
						    	console.log(error);
						    	uPublic.openRequestErrorAlert(self);
						    }
						});
						getLockInfo(self);
					}
			    },
			    error: (error) => {}
			});
			
			console.log("in");
			//注册监听上报
			iot.business.sds.registerPushListener({
			    success: (response) => {
			    	console.log(response);
			    	if(typeof(response) == 'string'){
			    		console.log("in");
			    		let data = JSON.parse(response);
			    		console.log(data);
			    		setDevceInfo(self, data.params.data);
//			    		console.log(moment(data.time, "YY-MM-DD-hh-mm-ss").format("HH:mm"));
//			    		switch(data.action){
//				    		case 'lock_log':
//								self.setBatteryPercent(data.battery);
//								self.setBatteryState(config.powerIcon[Math.round(data.battery/20)]);
//								//user_type: 0:密码用户 1:指纹用户 2:卡用户 3:遥控器 4:钥匙
//								//uid: 用户id
//								//time
//								if(lock_action == 0){
//									//再次获取最新记录
//									getLockInfo(self);
//								}
//				    		break;
//				    		case 'notify':
//				    			self.setBatteryPercent(data.battery);
//								self.setBatteryState(config.powerIcon[Math.round(data.battery/20)]);
//				    			if(data.notify_type == 3){
//									self.setDoorbellRingingFlag(true);
//									setTimeout(() => {
//										self.setDoorbellRingingFlag(false);
//										self.setRingingTime(moment(data.time, "YY-MM-DD-hh-mm-ss").format("HH:mm"));
//									},3000);
//								}else if(data.notify_type == 4){
//									self.setRemoteOpendoorFlag(true);	
//								}
//				    		break;
//				    		case 'status':
//				    			self.setBatteryPercent(data.battery);
//								self.setBatteryState(config.powerIcon[Math.round(data.battery/20)]);
//				    		break;
//				    		case 'openDoor':
//				    			
//				    		break;
//				    	}
			    	}
			    },
			    error: (error) => {
			    	console.log(error);
			    	uPublic.openRequestErrorAlert(self);
			    }
			});
			let power = 5;
			this.batteryPercent = power/5*100;
			this.batteryState = config.powerIcon[power];
//			let newMsg = '2017.08.02 18:45 宝贝指纹开门';
//			uComponents.changeMarqueeText(this, newMsg);
			let time = new Date();
			this.ringingTime = moment(time).format("HH:mm");
        },
        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;
            },
            getRemoteOpendoorFlag(){
            	return this.remoteOpendoorFlag;
            },
            setRemoteOpendoorFlag(flag){
            	this.remoteOpendoorFlag = flag;
            },
            getUuid(){
            	return this.uuid;
            },
            setUuid(){
            	this.uuid = id;
            },
            //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);
            }                      
        }   
    }).$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')
            }
        },
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        }                
    }
}

function getLockInfo(self){
	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)]);
				console.log(data.info);
				self.newMsg = moment(data.info[0].time).format("YY.MM.DD  HH:mm") + data.info[0].nickname + Vue.t('opendoorRecord.'+config.openDoorMode[data.info[0].mode]+'');
				uComponents.changeMarqueeText(self, self.newMsg);
			}else{
				
			}
		},
		error: (error) => {
			console.log(error);
			uPublic.openRequestErrorAlert(self);
		}
	});
}

//设置设备信息
function setDevceInfo(self, data) {
	console.log("监听到了");
//	data = {
//		"battery": {"value": "32"},
//		"lock_action": {"value": "0"},
//		"notify_type": {"value": "4"},
//		"time": {"value": "122324433221"}
//	}
	console.log(data);
	self.setBatteryPercent(data.battery.value);
	self.setBatteryState(config.powerIcon[Math.round(data.battery.value/20)]);
	if(data.lock_action.value == 0){
		//再次获取最新记录
		console.log("有最新的开门记录");
		getLockInfo(self);
	}
	if(data.hasOwnProperty('notify_type')){
		if(data.notify_type.value == 3){
			self.setDoorbellRingingFlag(true);
			setTimeout(() => {
				self.setDoorbellRingingFlag(false);
				self.setRingingTime(moment(data.time.value, "YY-MM-DD-hh-mm-ss").format("HH:mm"));
			},3000);
		}else if(data.notify_type.value == 4){
			self.setRemoteOpendoorFlag(true);	
		}
	}
}

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

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

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

//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/',
//	      	id: 'doorlockUsers',
//	      	extras: {
//	        	deviceId: self.deviceId
//	       	}
//	  });	
//	}
}

//tap 远程开门
function remoteOpendoorTap(self){
	if(self.getValueRemoteOpendoor() == 1){
		iot.navigator.openWindow({
	        url: './remoteOpendoor.html',
	        id: 'remoteOpendoor',
	        extras: {
	        	uuid: self.getUuid()
	        }
	    });	
	}
}

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