/**
* v_login.js
* Version: 0.1
* User: wy
* Date: 2017-09-06
* Copyright(c)  2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* 登录页面
*/

import {iot, uPublic, uComponents} from '../../public/public.js';
import Update from '../../public/update.js';



iot.ready(init);
function init() {
    //通用 input、按钮、dialog、loading组件
    uPublic.componentsInit(['u-loading','u-process']);
    const app = new Vue({
        data:{  
            //配置组件
            componentsConfig: initComponentsConfig(),
            downloadPercent: null
        },
        mounted(){           
			resolve(this);
        },
        methods:{
        	
        }   
    }).$mount('#app');
}

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

function resolve(self){
	uComponents.showProcess(self, 0, 'loading', []);
	console.log(self)
	cheackSdsDeviceExit(self);
}

//检验在sds中，该用户是否绑定设备
function cheackSdsDeviceExit(self){
	iot.business.sds.getDevicesByUser({
	    success: (response) => {
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
			if(data){
				//sds,绑定关系已存在
				cheackCloudDeviceExit(self, data.sn);
			}else{
				//sds,关系不存在
//				linkToAddDevice();
			}
	    },
	    error: (error) => {
	    	console.log(error);
	    	uPublic.openRequestErrorAlert(self);
	    },
		complete: () => {}
	});
}

//检验在云端中，该用户是否绑定设备
function cheackCloudDeviceExit(self, deviceId){
//	iot.business.api.send('lock/getDeviceProductId', {
//		data: {
//			device_id: deviceId
//		},
//		success: (response) => {
//			console.log(response);
//			let data = uPublic.checkResponseData(response.data);
//			if(data){
				//云端,绑定关系已存在
				linkToIndex(self);
//			}else{
//				//云端,关系不存在
//				linkToAddDevice();
//			}
//		},
//		error: (error) => {
//			console.log(error);
//		},
//		complete: () => {}
//	});
}

//页面跳转到首页
async function linkToIndex(self){
	let updateInfo = await iot.storage.getMap('updateInfo');
	console.log(updateInfo);
//	let newUpdateInfo = data.updateInfo;
	let newUpdateInfo = [{
		'productId': '01',
		'version': '0.0.3',
		'url': 'http://192.168.2.184:8010/custom01.wgtu'
	}];
	
	console.log(newUpdateInfo.length);
	if(newUpdateInfo.length){
		for(let i=0; i<newUpdateInfo.length; i++){
			let curVersion = newUpdateInfo[i].version;
			let oldVersion = '0.0.0';
			
			if(updateInfo){
				for(let j=0; j<updateInfo.length; j++){
					if(newUpdateInfo[i].product_id == updateInfo[j].product_id){
						oldVersion = updateInfo[j].version
					}
				}
			}
	
			console.log(curVersion+oldVersion);
			// 这里传入Update参数
			let update = new Update(curVersion,oldVersion,newUpdateInfo[i].url);
			console.log(update);
	    	//需要更新
	    	//重写 update中的方法，在下面方法中可以对更新app的相关生命周期进行操作
	        update.onDownloadStart = ()=>{
	            console.log("index page log onDownloadStart");
	            uComponents.showProcess(self, 0, '正在下载资源', []);
	        }
	
	        update.onDownloadSuccess = ()=>{
	        	uComponents.showProcess(self, 0, '下载成功', []);
	            console.log("index page log onDownloadSuccess");
	        }
	
	        update.onInstallStart = ()=>{
	        	uComponents.showProcess(self, 0, '安装中...', []);
	        	self.downloadPercent = null;
	            console.log("index page log onInstallStart");
	        }
	
	        update.onInstallSuccess = ()=>{
	        	uComponents.showProcess(self, 0, '安装中成功', []);
	            console.log("index page log onInstallSuccess");
		        //资源包安装成功，跳转到首页
	            iot.navigator.openWindow({
					url: '../../custom/custom'+newUpdateInfo[i].productId+'/view/device/index.html',
			        id: 'device',
			        styles: {
			        	popGesture: 'none'
			        },
			        extras: {
			        	needClose: true
			        }
			    });
			    //更新app缓存的productId和对应版本
			    iot.storage.setMap('updateInfo', newUpdateInfo, (response) => {
					console.log(res);
			    }, () => {});
	        }
	        
	        update.onStateChanged = (download, status) => {
	        	let percent = (download.downloadedSize/download.totalSize).toFixed(2)*100;
	        	console.log(parseInt(percent));
	        	self.downloadPercent = parseInt(percent);
	        }
	
	        update.onError = ()=>{
	            console.log("index page log onError");
	        }
	        
	        update.onNoNeedUpdate = () => {
	        	console.log(".....不需要更新");
		    	//不需要更新
		    	iot.navigator.openWindow({
					url: '../../custom/custom'+newUpdateInfo[i].productId+'/view/device/index.html',
			        id: 'device',
			        styles: {
			        	popGesture: 'none'
			        },
			        extras: {
			        	needClose: true
			        }
			    });
	        }
	
	        update.startUpdate();
			console.log(update);
		}
	}else{
		//无资源包需要更新，跳到默认首页
		iot.navigator.openWindow({
			url: '../device/index.html',
	        id: 'device',
	        styles: {
	        	popGesture: 'none'
	        },
	        extras: {
	        	needClose: true
	        }
	    });
	}
}

//页面跳转到添加设备页面
function linkToAddDevice(){
	iot.navigator.openWindow({
		url: '../addDevice/index.html',
        id: 'devicaddDevice',
        styles: {
        	popGesture: 'none'
        },
        extras: {
        	needClose: true
        }
    });
}
