/**
* 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 {iot, uPublic, uComponents} from '../../public/public.js';

iot.ready(init);
function init() {
    //通用 input、按钮、dialog、loading组件
    uPublic.componentsInit(['u-text','u-button','u-comm-loading','u-dialog','u-loading']);
    const app = new Vue({
        data:{     
        	textWiFiName: null,
            textPassword: null, 
            textErrorTip: null, 
            //配置组件
            componentsConfig: initComponentsConfig(),
            status: 0
        },
        mounted(){       
        	resolve(this);
        	
        },
        methods:{
        	getTextWiFiName(){
        		return this.textWiFiName;
        	},
        	setTextWiFiName(text){
        		this.textWiFiName = text;
        	},
        	getTextPassword(){
        		return this.textPassword;
        	},
        	setTextPassword(pwd){
        		this.textPassword = pwd;
        	},
        	gettTextErrorTip(){
        		return this.textErrorTip;
        	},
        	setTextErrorTip(tip){
        		this.textErrorTip = tip;
        	},
        	getStatus(){
        		return this.status;
        	},
        	setStatus(status){
        		this.status = status;
        	},
            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'
            }
        },
        ucommloading: {
            initParam: {
                class: 'custom-comm-loading',
                buttonText: Vue.t('btn.confirm'),
                text: 'loading',
                status: 0
            }
        }                        
    }
}

function resolve(self){
	iot.business.sds.getSSId({
	    success: (response) => {
	    	console.log(response);
	    	let data = JSON.parse(response);
	    	self.textWiFiName = data.ssid;
	    	console.log(self.textWiFiName);
	    },
	    error: (error) => {
	    	console.log(error);
	    	uPublic.openRequestErrorAlert(self);
	    }
	});
}

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

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

//tap 连接
function connectButtonTap(self){ 
//  uComponents.showCommstatusloading(self);
//  setTimeout(function(){
//      self.setTextLoading(Vue.t('commstatusLoading.connectSuccess'));
//      setTimeout(function(){
//          //绑定成功
//          self.setStatus(1);
//          self.setTextLoading(Vue.t('commstatusLoading.bindSuccess'));
//          //绑定失败
//          //self.setStatus(2);
//          //self.setTextLoading(Vue.t('commstatusLoading.bindFailed'));
//          //uComponents.changeCommstatusButtonText(self,Vue.t('btn.reBound'));
//      },3000);
//  },3000);
	console.log(self.getTextWiFiName());
	
//	self.setTextPassword('macro_scope00');
	console.log(self.getTextPassword());
	if(self.getTextPassword() == null || self.getTextPassword().trim() == ''){
		self.setTextErrorTip(Vue.t('wifiAdd.passwordInputTip'));
	}else{
		iot.business.sds.findWifi({
		    data: {
		        model: 'UGEN_LIVING_ELECTRICALBLANKET_THM_BL',
		        ssid: self.getTextWiFiName(),
		        wifiPwd: self.getTextPassword(),
		        timeout: 20000
		    },
		    success: (response) => {
		    	console.log("findWifi");
		    	console.log(response);
		    	if(response.data == 'onProvisioning'){
		    		//wifi链接中
		    		uComponents.showCommLoading(self);
		    	}else if(response.data == 'provisioned success'){
		    		//wifi连接成功，停止连接wifi
	//	    		iot.business.sds.stopFindWifi({
	//				    success: (response) => {},
	//				    error: (error) => {}
	//				});
		    	}
		    },
		    error: (error) => {
		    	console.log(error);
		    }
		});
		let deviceId = null;
		iot.business.sds.findDevices({
		    success: (response) => {
		    	console.log("findDevices");
		    	console.log(response);
	    		let parameters = {};
//	    		let data = "DeviceInfo:[model = THM_LIVING_ELECTRICALBLANKET_TH_1507,xModel = null,mac = B0:F8:93:10:D5:09,sn = B0F89310D509,uuid = null,connectMode = alibaba_smartconfig_v3,supportRouterProvision = false,productName = null,gatewayUuid = null,deviceType = null,alinkJoinVersion = Bind, ]"
//		    	console.log(data);
		    	if (response.data) {
		    		let info = response.data.split(':[');
		    		if(info[1]){
		    			let query = info[1].split(',');
			        	console.log(query);
			        	for(let i=0; i< query.length; i++){
			        		let pari = query[i].split(' = ');
			        		console.log(pari);
			        		parameters[pari[0]] = pari[1];
			        	}
			        	console.log(parameters.sn);
		    		}
		
			    }
		    	if(parameters.sn){
		    		deviceId = parameters.sn; 	
		    	}
		    	
		    	console.log(typeof(deviceId));
		    	if(response.data == "joined success"){
		    		//云端绑定
		    		iot.business.device.bind({
					    data: {
					        product_id: 2,
					        device_id: deviceId,
//					        mac: parameters.mac,
					        nickname: ''
					    },
					    success: (response) => {
					    	console.log(response);
					    	//连接成功
		    				uComponents.changeCommLoadingStatusAndText(self, 1, '绑定成功');
		    				self.setStatus(1);
					    },
					    error: (error) => {
					    	console.log(error);
					    },
					    complete: () => {}
					});
		    		//连接成功
//		    		uComponents.changeCommLoadingStatusAndText(self, 1, '绑定成功');
//		    		self.setStatus(1);
	//	    		//停止查找设备
		    		iot.business.sds.stopFindDevices({
					    success: (response) => {},
					    error: (error) => {}
					});
					
		    	}else if(response.data == "fail"){
		    		//连接失败
		    		uComponents.changeCommLoadingStatusAndText(self, 2, '绑定失败');
		    		self.setStatus(2);
		    		uComponents.changeCommButtonText('请重新绑定');
		    		//停止查找设备
		    		iot.business.sds.stopFindDevices({
					    success: (response) => {},
					    error: (error) => {}
					});
		    	}
		    },
		    error: (error) => {
		    	console.log(error);
		    }
		});
	}
}

//tap loading button
function commLoadingButtonTap(self) {
	if(self.getStatus() == 1){
		 //绑定成功
	    uComponents.hideCommLoading(self);
	    iot.navigator.openWindow({
	        url: '../device/',
	        id: 'device'
	    });
	}else if(self.getStatus() == 2){
		//绑定失败
      	uComponents.hideCommLoading(self);
	}
}