/**
* v_scanCodeAdd.js
* Version: 0.1
* User: wy
* Date: 2017-09-07
* Copyright(c)  2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* 扫描绑定设备页面
*/

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

iot.ready(init);
function init() {
    //通用 dialog、loading组件
    uPublic.componentsInit(['u-dialog','u-loading','u-process']);
    uPublic.componentsExtend(['checkwgtu']);
//  uPublic.closeSlideBack();
    const app = new Vue({
        data:{            
            //配置组件
            componentsConfig: initComponentsConfig(),
            barcode: null,
            noticeTipShowFlag: false
        },
        mounted(){  
        	let self = this;
        	resolve(self);
            window.addEventListener('returnPage',() => {
				self.noticeTipShowFlag = !iot.native.isNotifycationOpen();
				scanCodeSuccess(self);
			});
			plus.key.addEventListener('backbutton',function(){
				iot.utils.closeScanBarcode(self.barcode);
			},false);	
        },
        methods:{
            //tap <
            onBackTap(){
                backTap(this);
            }                  
        }
    }).$mount('#app');
}

//配置组件参数
function initComponentsConfig() {
    return {
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        },
        processLoading: {
            initParam: {
                class: 'custom-process',
                status: 0
            }
        },
        checkwgtu: {
            initParam: {
                class: 'custom-checkwgtu'
            }
        } 
    }
}

function resolve(self){
	if(plus.os.name == 'Android') {
        iot.permission.checkPermission(['CAMERA'], function (res) {
            console.log('success', res);
            console.log("openScanCode"+ new Date().getTime());
            openScanCode(self);
        }, function (err) {
            console.log('error', err);
            plus.nativeUI.confirm(Vue.t("addDevice.openCameraTip"), (e)=>{
                if(e.index == 1){
                	iot.native.toAppSetting();
                }
                backTap(self);
            },"", [Vue.t("btn.cancel"),Vue.t("addDevice.openCamera")]);
        });
    }else{
    	let isFistOpenCamera = iot.storage.getMap('isFistOpenCamera');
    	if(isFistOpenCamera){
    		iot.permission.checkPermission(['CAMERA'], function (res) {
                console.log('success', res);
                console.log("openScanCode"+ new Date().getTime());
                openScanCode(self);
            }, function (err) {
                console.log('error', err);
                plus.nativeUI.confirm(Vue.t("addDevice.openCameraTip"), (e)=>{
	                if(e.index == 0){
	                	iot.native.toAppSetting();
	                }
	                backTap(self);
	            },"", [Vue.t("addDevice.openCamera"),Vue.t("btn.cancel")]);
            });
    	}else{
    		openScanCode(self);
    		iot.storage.setMap('isFistOpenCamera', true,() => {
			}, (err) => {});
    	}
    }
}

//tap <
function backTap(self){
	iot.utils.closeScanBarcode(self.barcode);
	iot.navigator.aback();
}

function openScanCode(self){
	let bcidBg = '#3a3d54';
//	alert(plus.os.name);
	if(plus.os.name == 'iOS'){
		bcidBg = '#3a3d5400';
	}
	self.barcode = iot.utils.scanBarcode({
	    data: {
	        id: 'bcid',
	        styles: {
	        	frameColor: '#00ffff',
	        	scanbarColor: '#00ffff',
	        	background: bcidBg
	        }
	    },
	    success: (response) => {
	    	console.log("openScanCodeSuccess"+ new Date().getTime());
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
	    	if(data){
	    		let params = uPublic.getUrlQuery(data.result);
	    		//扫描成功
	    		//判断扫描结果是否是下载路径
	    		if(params.url == config.downloadUrl){
	    			//若是下载路径，获取productId并跳转到配网绑定页面
	    			iot.navigator.openWindow({
				        url: './wifiAddHelp.html',
				        id: 'wifiAddHelp',
				        extras: {
				        	productId: params.p
				        }
				    });
	    		}else if(data.result.indexOf('qrKey') != -1){
	    			//若是分享路径，则获取qrKey,lockId,relId绑定
	    			uComponents.showProcess(self, 0, Vue.t('addDevice.loading'));
		    		let result = JSON.parse(data.result);
		    		console.log(result);
		    		console.log(result.hasOwnProperty('qrKey'));
	    		
	    			let qrKey = result.qrKey;
			    	let lockId = result.lockId;
			    	let relId = result.relId;
			    	//绑定设备
		        	iot.business.sds.scanqr({
					    data: {
					        qrKey: qrKey
					    },
					    success: (response) => {
						    console.log(response);
					    	let data = uPublic.checkResponseData(response.data);
		    				if(data){
						    	//获取设备详情
						    	getInfo(self, lockId, relId, data.uuid);
							}else{}
					    },
					    error: (error) => {
					    	//绑定失败
					    	console.log(error);
	    					scanCodeFailue(self);
					    }
					});
	    		}else{
	    			scanCodeFailue(self);
	    		}
	    	}else{}
	    },
	    error: (error) => {
	    	//请求失败
	    	console.log(error);
//  		if(window.iotDebug){
//              iotDebug.push('end: 扫描失败'+JSON.stringify(error));
//         	}
//	    	if (window.iotDebug) {
//              iotDebug.upload(iot,'扫描失败');
//          }
    		scanCodeFailue(self);
	    }
	});
}

//获取设备详情
function getInfo(self, lockId, relId, uuid){
	if(uuid){
		iot.business.device.getInfo({
		    data: {
		        sds: true,
		        uuid: uuid
		    },
		    success: (response) => {
		    	console.log(response);
		    	let data = uPublic.checkResponseData(response.data);
		    	if(data){
		    		console.log("phoneNumber");
		    		console.log(uPublic.getPhoneNumber(data));
		    		//云端绑定
					deviceBind(self, lockId, relId, data.auid);
		    	}
		    },
		    error: (error) => {
		    	console.log(error);
		    },
		    complete: () => {}
		});
	}
}

// 云端绑定
function deviceBind(self, lockId, relId, auid){
	iot.business.api.sendCustom('lock/bindUser',{
	    data: {
	        device_id: lockId,
	        rel_id: relId,
	        auid: auid,
//		    mac: parameters.mac,
	        nickname: ''
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = response.data;
			if(data.success){
				scanCodeSuccess(self);
//				uComponents.openAlert(self, Vue.t('addDevice.bindSuccess'), {
//			        text: Vue.t('dialog.confirm'), callback: function () {
//			        	iot.navigator.fire(plus.webview.getWebviewById('device'),'returnPage',{
//			        		needClose: true
//			        	});
//			        	iot.navigator.openWindow({
//					        url: '../device/index.html',
//					        id: 'device'
//					    });
//			        }
//			    });
			}
	    },
	    error: (error) => {
	    	console.log(error);
//	    	if(window.iotDebug){
//              iotDebug.push('end: 云端绑定失败'+JSON.stringify(error));
//         	}
//	    	if (window.iotDebug) {
//              iotDebug.upload(iot,'云端绑定失败');
//          }
		    scanCodeFailue(self);
	    },
	    complete: () => {}
	});
}

function scanCodeSuccess(self){
	iot.navigator.closeAllBesidesItself();
	self.noticeTipShowFlag = !iot.native.isNotifycationOpen();
	if(self.noticeTipShowFlag){
		uComponents.showProcess(self, 1,  Vue.t('addDevice.bindSuccess'), [{
			"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',
//			        extras: {
//			        	needClose: true
//			        }
//			    });
				uComponents.hideProcess(self);
				projectMethods.checkUpdate(self);
			}
		}]);
	}else{
		console.log("通知开启了");
		uComponents.showProcess(self, 1,  Vue.t('addDevice.bindSuccess'), [{
			"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',
//			        extras: {
//			        	needClose: true
//			        }
//			    });
				projectMethods.checkUpdate(self);
			}
		}]);
	}
}

function scanCodeFailue(self){
	uComponents.showProcess(self, 2,  Vue.t('addDevice.bindFailure'), [{
		"class": 'custom-process-button', 'text': Vue.t('addDevice.reBindDevice'), 'callback': () => {
			//激活失败
			uComponents.hideProcess(self);
			iot.utils.closeScanBarcode(self.barcode);
//			uComponents.showProcess(self, 0, Vue.t('addDevice.loading'));
	    	openScanCode(self);
		}
	}]);
}
