/**
* v_wifiAdd.js
* Version: 0.1
* User: wy
* Date: 2017-09-07
* Copyright(c)  2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* 连接Wi-Fi页面
*/

import config from '../../public/config.js';
import defaultConfig from '../../public/defaultConfig.js';
import {iot, uPublic, uComponents} from '../../public/public.js';

iot.ready(init);
function init() {
    //通用 input、按钮、dialog、loading组件
    uPublic.componentsInit(['u-text','u-button','u-process','u-dialog','u-loading']);
    uPublic.closeSlideBack();
    const app = new Vue({
        data:{     
        	textWiFiName: null,
            textPassword: null, 
            textErrorTip: null, 
            //配置组件
            componentsConfig: initComponentsConfig(),
            noticeTipShowFlag: false,
            timeout: null,
            countDownText: config.add_wifi_timeout,
        },
        mounted(){       
        	resolve(this);
        	let self = this;
        	window.addEventListener('returnPage',() => {
				self.noticeTipShowFlag = !iot.native.isNotifycationOpen();
				addSuccess(self);
			});
        },
        methods:{
        	getTextWiFiName(){
        		return this.textWiFiName;
        	},
        	setTextWiFiName(text){
        		this.textWiFiName = text;
        	},
        	getTextPassword(){
        		return this.textPassword;
        	},
        	setTextPassword(pwd){
        		this.textPassword = pwd;
        	},
        	getTextErrorTip(){
        		return this.textErrorTip;
        	},
        	setTextErrorTip(tip){
        		this.textErrorTip = tip;
        	},
            onPasswordChange(text){
                passwordChange(this,text);            
            },            
            //tap <
            onBackTap(){
                backTap();
            },
            //tap 连接
            onConnectButtonTap(){
                connectButtonTap(this);    
            },
            //tap loading button
//          onCommLoadingButtonTap(){
//              commLoadingButtonTap(this);
//          }                           
        }   
    }).$mount('#app');
}

//配置组件参数
function initComponentsConfig() {
    return {
        passwordInput: {
            initParam: {
                class: 'custom-password-text',
                icon: '&#xe64d;',
                placeholder: Vue.t('wifiAdd.passwordInputTip'),
                type: 'password'
            }
        },
        //连接 button 参数
        connectButton: {   
            initParam: {
                class: 'custom-button',
                text: Vue.t('btn.connect')
            }
        }, 
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        },
        processLoading: {
            initParam: {
                class: 'custom-process',
                status: 0
            }
        }                        
    }
}

//页面渲染后，获取wifi名称
function resolve(self){
	iot.business.sds.getSSId({
	    success: (response) => {
	    	console.log(response);
	    	self.textWiFiName = response.data.ssid;
	    },
	    error: (error) => {
	    	console.log(error);
	    	if(window.iotDebug){
                iotDebug.push('end: 获取wifi失败'+JSON.stringify(response));
           	}
    		if (window.iotDebug) {
                iotDebug.upload(iot,'获取wifi失败');
            }
	    	uPublic.openRequestErrorAlert(self);
	    }
	});
}

//设置wifi密码
function passwordChange(self,text){
    self.setTextPassword(text);
    console.log('passwordChange: ' + self.getTextPassword());
}

//重新mui.back
mui.back = function(){
	iot.navigator.fire(plus.webview.currentWebview().opener(),'returnPage',{ });
	iot.navigator.back();
}

//tap <
function backTap(){
    iot.navigator.aback();
}

//tap 连接
function connectButtonTap(self){ 
	if(self.getTextWiFiName() == null || self.getTextWiFiName().trim() == ''){
		self.setTextErrorTip(Vue.t('wifiAdd.unbindWifiTip'));
	}else if(self.getTextPassword() == null || self.getTextPassword().trim() == ''){
		self.setTextErrorTip(Vue.t('wifiAdd.passwordInputTip'));
	}else{
		self.countDownText = config.add_wifi_timeout;
		window.clearInterval(self.timeout);
		self.timeout = setInterval(() => {
			self.countDownText --;
			if(self.countDownText <= 0){
				console.log("innnnn");
				window.clearInterval(self.timeout);
				addFailue(self);
			}
		},1000);
		uComponents.showProcess(self, 0, Vue.t('addDevice.loading'), [{
			"class": 'custom-process-button', 'text': Vue.t('btn.cancel'), 'callback': () => {
				uComponents.hideProcess(self);
			}
		}]);
		iot.business.sds.findWifi({
		    data: {
		        model: defaultConfig.model,
		        ssid: self.getTextWiFiName(),
		        wifiPwd: self.getTextPassword(),
		        timeout: 20000
		    },
		    success: (response) => {
		    	console.log("findWifi");
		    	console.log(response);
	    		if(window.iotDebug){
	                iotDebug.push('end: 找WIFI'+JSON.stringify(response));
	           	}
	    		if (window.iotDebug) {
	                iotDebug.upload(iot,'找WIFI');
	            }
		    	if(response.data == 'onProvisioning'){
		    		//wifi链接中
		    		if(window.iotDebug){
	                    iotDebug.push('end: 配网中'+JSON.stringify(response));
	               	}
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'配网中');
	                }
					uComponents.showProcess(self, 0,  Vue.t('wifiAdd.wifiBinding'), [{
						"class": 'custom-process-button', 'text': Vue.t('btn.cancel'), 'callback': () => {
							uComponents.hideProcess(self);
						}
					}]);
		    	}else if(response.data == 'provisioned success'){
		    		if(window.iotDebug){
	                    iotDebug.push('end: 配网成功'+JSON.stringify(response));
	               	}
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'配网成功');
	                }
		    		//wifi连接成功，停止连接wifi
					uComponents.showProcess(self, 0,  Vue.t('wifiAdd.wifiBindSuccess'), [{
						"class": 'custom-process-button', 'text': Vue.t('btn.cancel'), 'callback': () => {
							uComponents.hideProcess(self);
						}
					}]);
		    	}
		    },
		    error: (error) => {
		    	console.log(error);
		    	if(window.iotDebug){
	                iotDebug.push('end: 配网失败'+JSON.stringify(error));
	           	}
		    	if (window.iotDebug) {
	                iotDebug.upload(iot,'配网失败');
	            }
		    	addFailue(self);
		    }
		});
		iot.business.sds.findDevices({
		    success: (response) => {
		    	console.log('findDevices');
		    	console.log(response);
		    	if(window.iotDebug){
	                iotDebug.push('end: 找设备'+JSON.stringify(response));
	           	}
		    	if (window.iotDebug) {
	                iotDebug.upload(iot,'找设备');
	            }
		    	if(response.data == "onJoining"){
		    		if(window.iotDebug){
	                    iotDebug.push('end: 激活中'+JSON.stringify(response));
	                }
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'激活中');
	              	}
					uComponents.showProcess(self, 0,  Vue.t('wifiAdd.deviceActivating'), [{
						"class": 'custom-process-button', 'text': Vue.t('btn.cancel'), 'callback': () => {
							uComponents.hideProcess(self);
						}
					}]);
		    	}else if(response.data == "joined success"){
		    		if(window.iotDebug){
	                    iotDebug.push('end: 激活成功'+JSON.stringify(response));
	                }
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'激活成功');
	                }
		    		joinedSuccess(self, response);
				}else if(response.data == "fail"){
		    		//连接失败
		    		if(window.iotDebug){
	                    iotDebug.push('end: 激活失败'+JSON.stringify(response));
	                }
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'激活失败');
	                }
					addFailue(self);
		    	}
		    },
		    error: (error) => {
		    	console.log(error);
		    	if(window.iotDebug){
	                iotDebug.push('end: findDevicesError'+JSON.stringify(error));
	           	}
		    	if (window.iotDebug) {
	                iotDebug.upload(iot);
	            }
		    	addFailue(self);
		    }
		});
	}
}

function joinedSuccess(self, response){
	let deviceId = response.info.sn;
	let uuid = null;
	let productId = defaultConfig.model;
	if(response.info.uuid){
		uuid = response.info.uuid;
		sendDeviceStatus(self, deviceId, productId, uuid);
	}else{
		let target = response.info.model;
        let nickname = target;
        let product_id = target;
		iot.business.device.getList({
	        data: {
	            sds: true
	        },
	        success: (response) => {
	            console.log("sds云返回设备数据。。。↓↓");
	            console.log(response);
	            response.data.map((item,index)=>{
	                console.log("展示sds设备...");
	                console.log(item);
	               	if (item.sn == deviceId) {
	                	console.log("匹配到了sn一致...");
	                	let deviceInfo = {
	                        mac:item.sn,
	                        device_id:item.uuid,
	                        nickname:nickname,
	                        product_id:product_id
	                    };
	                    uuid = deviceInfo.device_id;
	   					sendDeviceStatus(self, deviceId, productId, uuid);
	               	}
	            });
	        },
	        error: (error) => {
	            console.log(error);
	        },
	        complete: () => {}
	   	});
	}
}

function sendDeviceStatus(self, deviceId, productId, uuid){
	iot.business.sds.setDeviceStatus({
	    data: {
	        uuid: uuid,
	        setParams: {
	        	'action': {
	        		'value': 'registerSuccess'
	        	}
	        }
	    },
	    success: (response) => {
	    	//激活成功
			bind(self, deviceId, productId);
	    	console.log(response);
	    },
	    error: (error) => {
	    	console.log(error);
           	uPublic.openRequestErrorAlert(self);
           	uComponents.hideProcess(self);
		},
	    complete(){}
	});	
}

//云端绑定之前先解绑
function unbind(self, deviceId, productId){
	console.log(deviceId);
	iot.business.api.sendCustom('lock/unbindDevice',{
	    data: {
	    	device_sn: deviceId
	    },
	    success: (response) => {
	    	console.log(response);
			bind(self, deviceId, productId);
			if(window.iotDebug){
                iotDebug.push('end: 解绑成功'+JSON.stringify(response));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'解绑成功');
            }
	    },
	    error: (error) => {
	    	console.log(error);
			if(window.iotDebug){
                iotDebug.push('end: 解绑失败'+JSON.stringify(error));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'解绑失败');
            }
			addFailue(self);
	    },
	    complete: () => {
	    }
	});
}

//云端绑定
function bind(self, deviceId, productId){
	iot.business.api.sendCustom('lock/bind',{
	    data: {
	        product_id: productId,
	        device_id: deviceId,
//			mac: sn,
	        nickname: ''
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = response.data;
	    	if(data.success){
				addSuccess(self);
			}
	    	if(window.iotDebug){
                iotDebug.push('end: 绑定成功'+JSON.stringify(response));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'绑定成功');
            }
	    },
	    error: (error) => {
	    	console.log(error);
			if(window.iotDebug){
                iotDebug.push('end: 绑定失败'+JSON.stringify(error));
           	}
	    	if (window.iotDebug) {
                iotDebug.upload(iot,'绑定失败');
            }
			addFailue(self);
	    },
	    complete: () => {}
	});
}

function addFailue(self){
	//停止配网
	iot.business.sds.stopFindDevices({
	    success: (response) => {},
	    error: (error) => {}
	});
	window.clearInterval(self.timeout);
	uComponents.showProcess(self, 2,  Vue.t('wifiAdd.deviceActivateFailure'), [{
		"class": 'custom-process-button', 'text': Vue.t('addDevice.reBindDevice'), 'callback': () => {
			//激活失败
			uComponents.hideProcess(self);
		}
	}]);
}

function addSuccess(self){
	//停止配网
	iot.business.sds.stopFindDevices({
	    success: (response) => {},
	    error: (error) => {}
	});
	window.clearInterval(self.timeout);
	self.noticeTipShowFlag = !iot.native.isNotifycationOpen();
	if(self.noticeTipShowFlag){
		uComponents.showProcess(self, 1,  Vue.t('wifiAdd.deviceActivateSuccess'), [{
			"class": 'custom-process-button', 'text': Vue.t('btn.openNotify'), 'callback': () => {
				//开启推送通知
				if(plus.os.name == 'Android'){
//					alert("打开通知页面");
					iot.navigator.openWindow({
				        url: '../device/notify.html',
				        id: 'notify',
				        styles: {
				        	popGesture: 'none'
				        }
				    });
				}else{
					iot.native.toNotifycationSetting();
				}
			}
		},{
			"class": 'custom-process-button custom-process-cancelButton', 'text': Vue.t('btn.ignore'), 'callback': () => {
				//暂不开启
				uComponents.hideProcess(self);
			    iot.navigator.fire(plus.webview.getWebviewById('device'),'returnPage',{
			    	needClose: true
			    });
			    iot.navigator.openWindow({
			        url: '../device/index.html',
			        id: 'device'
			    });
			}
		}]);
	}else{
		uComponents.showProcess(self, 1,  Vue.t('wifiAdd.deviceActivateSuccess'), [{
			"class": 'custom-process-button', 'text': Vue.t('btn.startNow'), 'callback': () => {
				//立即体验
				uComponents.hideProcess(self);
			    iot.navigator.fire(plus.webview.getWebviewById('device'),'returnPage',{
			    	needClose: true
			    });
			    iot.navigator.openWindow({
			        url: '../device/index.html',
			        id: 'device'
			    });
			}
		}]);
	}
}