/**
* 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 {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']);
    uPublic.closeSlideBack();
    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: Vue.t('addDevice.loading'),
                status: 0
            }
        }                        
    }
}

function resolve(self){
	iot.business.sds.getSSId({
	    success: (response) => {
	    	console.log(response);
	    	self.textWiFiName = response.data.ssid;
	    	console.log(self.textWiFiName);
	    },
	    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);
	    }
	});
}

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

iot.navigator.aback = function(){
	iot.navigator.fire(plus.webview.currentWebview().opener(),'returnPage',{ });
	iot.navigator.back();
}

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

//tap 连接
function connectButtonTap(self){ 
//	console.log(self.getTextWiFiName());
//	console.log(self.getTextPassword());
	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{
		uComponents.showCommLoading(self);
		iot.business.sds.findWifi({
		    data: {
		        model: config.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.changeCommLoadingStatusAndText(self, 0, Vue.t('wifiAdd.wifiBinding'));
		    	}else if(response.data == 'provisioned success'){
		    		if(window.iotDebug){
	                    iotDebug.push('end: 配网成功'+JSON.stringify(response));
	               	}
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'配网成功');
	                }
		    		//wifi连接成功，停止连接wifi
		    		uComponents.changeCommLoadingStatusAndText(self, 0, Vue.t('wifiAdd.wifiBindSuccess'));
	//		    		iot.business.sds.stopFindWifi({
	//					    success: (response) => {},
	//					    error: (error) => {}
	//					});
		    	}
		    },
		    error: (error) => {
		    	console.log(error);
		    	if(window.iotDebug){
	                iotDebug.push('end: 配网失败'+JSON.stringify(error));
	           	}
		    	if (window.iotDebug) {
	                iotDebug.upload(iot,'配网失败');
	            }
		    	uPublic.openRequestErrorAlert(self);
		    }
		});
		iot.business.sds.findDevices({
		    success: (response) => {
		    	console.log('findDevices');
		    	if(window.iotDebug){
	                iotDebug.push('end: 找设备'+JSON.stringify(response));
	           	}
		    	if (window.iotDebug) {
	                iotDebug.upload(iot,'找设备');
	            }
		    	let productId = config.model;
		    	if(response.data == "onJoining"){
		    		if(window.iotDebug){
	                    iotDebug.push('end: 激活中'+JSON.stringify(response));
	                }
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'激活中');
	                }
		    		uComponents.changeCommLoadingStatusAndText(self, 0, Vue.t('wifiAdd.deviceActivating'));
		    	}else if(response.data == "joined success"){
		    		if(window.iotDebug){
	                    iotDebug.push('end: 激活成功'+JSON.stringify(response));
	                }
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'激活成功');
	                }
		    		let deviceId = response.info.sn;
		    		unbind(self, deviceId, productId);
	//		    		bind(self, deviceId, productId);
		    	}else if(response.data == "fail"){
		    		//连接失败
		    		if(window.iotDebug){
	                    iotDebug.push('end: 激活失败'+JSON.stringify(response));
	                }
		    		if (window.iotDebug) {
	                    iotDebug.upload(iot,'激活失败');
	                }
		    		uComponents.changeCommLoadingStatusAndText(self, 2, Vue.t('wifiAdd.deviceActivateFailure'));
		    		self.setStatus(2);
		    		uComponents.changeCommButtonText(self, Vue.t('addDevice.reBindDevice'));
		    		//停止查找设备
		    		iot.business.sds.stopFindDevices({
					    success: (response) => {},
					    error: (error) => {}
					});
		    	}
		    },
		    error: (error) => {
		    	console.log(error);
		    	if(window.iotDebug){
	                iotDebug.push('end: findDevicesError'+JSON.stringify(error));
	           	}
		    	if (window.iotDebug) {
	                iotDebug.upload(iot);
	            }
		    	uPublic.openRequestErrorAlert(self);
		    }
		});
	}
	setTimeout(function (){
		if(self.getStatus() == 0){
			console.log("timeout");
			//连接失败
    		uComponents.changeCommLoadingStatusAndText(self, 2, Vue.t('wifiAdd.bindTimeout'));
    		self.setStatus(2);
    		uComponents.changeCommButtonText(self, Vue.t('addDevice.reBindDevice'));
    		//停止查找设备
    		iot.business.sds.stopFindDevices({
			    success: (response) => {},
			    error: (error) => {}
			});
		}
	},config.wifi_add_timeout);
}

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

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,'解绑失败');
            }
	    	uComponents.changeCommLoadingStatusAndText(self, 2, Vue.t('wifiAdd.deviceActivateFailure'));
	    	uComponents.changeCommButtonText(self, Vue.t('addDevice.reBindDevice'));
			self.setStatus(2);
	    },
	    complete: () => {
	    }
	});
}

function bind(self, deviceId, productId){
	iot.business.api.sendCustom('lock/bind',{
	    data: {
	        product_id: productId,
	        device_id: deviceId,
//			mac: parameters.mac,
	        nickname: ''
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = response.data;
	    	if(data.success){
				uComponents.changeCommLoadingStatusAndText(self, 1, Vue.t('wifiAdd.deviceActivateSuccess'));
				uComponents.changeCommButtonText(self, Vue.t('btn.confirm'));
				self.setStatus(1);
			}
	    	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,'绑定失败');
            }
	    	uComponents.changeCommLoadingStatusAndText(self, 2, Vue.t('wifiAdd.deviceActivateFailure'));
	    	uComponents.changeCommButtonText(self, Vue.t('addDevice.reBindDevice'));
			self.setStatus(2);
	    },
	    complete: () => {}
	});
}
