/**
* list.vue
* Version: 0.1
* User: zjx
* Date: 2018-03-15
* Copyright(c)  2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* checkWgtu
*/
<template>
    <div class="checkwgtu" v-show="showFlag" :class="initClass">
        <ul class="checkwgtu-box">
            <li class="checkwgtu-icon"></li>
            <li class="checkwgtu-text">{{ loadingText }}</li>
        </ul>
    </div>
</template>

<script>
	import Update from '../public/update.js';
	import CheckUpdate from '../public/checkUpdate.js';
	import {iot, uPublic, uComponents} from '../public/public.js';
    export default {
        props: ['initParam'],
        data() {
            return {
                // 组件初始化列表
                list: this.initParam.list || [],
                // 组件初始化样式
                initClass: this.initParam.class,
                loadingText: Vue.t('loading'),
                showFlag: false,
                deviceInfo: {}
            }
        },
        mounted() {
        },
        methods: {
            start(){
				this.setShowFlag(true);
				getDeviceList(this);
            },
            setShowFlag(flag){
                this.showFlag = flag;
            },
            setLoadingText(text){
            	this.loadingText = text;
            },
            setDeviceInfo(info){
            	this.deviceInfo = info;
            },
            getDeviceInfo(){
            	return this.deviceInfo;
            }
        }
    }
    
    //获取云端用户列表
    function getDeviceList(self){
    	iot.business.device.getList({
    		data: {
		    },
		    success: (response) => {
		    	console.log(response);
		    	let data = uPublic.checkResponseData(response.data);
				if(data){
					cheackSdsDevice(self, data);
				}else{
					openAddDevice();
				}
		    },
		    error: (error) => {
		    	console.log(error);
		    },
		    complete: () => {}
    	});
    }
    
    //检查sds中该设备是否绑定
    function cheackSdsDevice(self, cloudData){
    	iot.business.sds.getDevicesByUser({
		    success: (response) => {
		    	console.log(response);
		    	let data = uPublic.checkResponseData(response.data);
				if(data){
					let cloudJson = cloudData[0];
					let info = checkData(data,cloudJson);
					console.log(info);
					if(info){
						getWgtuUpdateInfo(self, cloudJson.product_id);
						self.setDeviceInfo(info);
					}else{
						openAddDevice();
					}
				}else{
					//sds,关系不存在
					openAddDevice();
				}
		    },
		    error: (error) => {
		    	console.log(error);
		    	uPublic.openRequestErrorAlert(self);
		    },
			complete: () => {}
		});
    }
    
    //匹配云端门锁信息和sds端门锁信息
    function checkData(data, cloudData){
    	let flag = false;
    	for(let i=0; i<data.length; i++){
    		if(cloudData.device_id == data[i].sn){
    			let info = {
    				"uuid": data[i].uuid,
    				"mac": data[i].mac,
    				"sn": data[i].sn
    			}
    			return info;
    		}
    	}
    	if(flag == false){
    		return false;
    	}
    }
    
	//获取云端资源更新信息
	function getWgtuUpdateInfo(self, productId){
		iot.business.product.getInfoById({
	        data:{
	            pid: productId
	        },
	        success:function(response){
	        	console.log(response);
	            let data = uPublic.checkResponseData(response.data);
	            if(data){
	            	//检查资源包的更新
	            	checkWgtuUpdate(self, data, productId);
	            }else{
	            	//无资源更新，使用默认版本
	            	openDefaultIndex();
	            }
	        },
	        error: (error) => {
	        	console.log(error);
	        },
	        complete: () => {}
	    });
	}
	
	//检查资源包的更新
	async function checkWgtuUpdate(self, data, productId){
		let updateInfo = [];
		let nowVersion = '0.0.0';
		updateInfo = await iot.storage.getMap('updateInfo');
		if(updateInfo){
			for(let j=0; j<updateInfo.length; j++){
				if(productId == updateInfo[j].product_id){
					nowVersion = updateInfo[j].version
				}
			}
		}
		let update = new CheckUpdate().checkWgtuVersion(data.package.min, data.package.now, nowVersion);
		switch(update.wgtu){
			case 2: 
				//必须更新资源包
				//需要更新app,则先更新app
				console.log("必须更新资源包");
	    		if(update.support){
	    			//app更新到最新版本
	    			console.log("必须更新app");
	    			updateApp(self);
	    		}else{
	    			downloadWgtu(self, productId, data.package.now.download, data.package.now.ver, data.product.name);
	    		}
				break;
			case 1:
				//可选择是否更新资源包
				console.log("可选择是否更新资源包");
	    		uComponents.openConfirm(self.$parent, Vue.t('checkwgtu.needUpdateWgtu'),
			       {text: Vue.t('checkwgtu.cancel'), callback: function () {
			       		//不需要更新
				    	openProductIndex(self, productId);
			       }},
			       {text:Vue.t('checkwgtu.update'), callback: function () {
			       		//需要更新app,则先更新app
		        		if(update.support){
		        			//app更新到最新版本
		        			console.log("必须更新app");
		        			updateApp(self);
		        		}else{
		        			downloadWgtu(self, productId, data.package.now.download, data.package.now.ver, data.product.name);
		        		}
			       }}
			    );
				break;
			case 0: 
				openProductIndex(self, productId);
				break;
		}
	}
	
	//更新app
	function updateApp(self){
		console.log(plus.os.name);
	    let os = "";
	    if(plus.os.name == 'Android'){
	    	os = "android";
	    }else if(plus.os.name == 'iOS'){
	    	os = "ios";
	    }
		iot.business.app.getVersion({
	        data:{
	            os:os
	        },
	        success:function(response){
	            console.log(response);
	            let data = response.data;
	            if(data){
		            uComponents.openConfirm(self.$parent, Vue.t('checkwgtu.needUpdateApp'),
				       {text: Vue.t('checkwgtu.cancel'), callback: function () {
				       		//不更新
		        			plus.runtime.quit();
				       }},
				       {text: Vue.t('checkwgtu.update'), callback: function () {
		            		plus.runtime.openURL(data.url);
				       }}
				    );
	            }
	        },
	        error: (error) => {
	        	console.log(error);
	        },
	        complete: () => {}
	    });
	}
	
	//下载资源包
	async function downloadWgtu(self, productId, url, version, name){
		// 这里传入Update参数
		let update = new Update(url);
		console.log(update);
		//需要更新
		//重写 update中的方法，在下面方法中可以对更新app的相关生命周期进行操作
	    update.onDownloadStart = ()=>{
	        self.setLoadingText(Vue.t('checkwgtu.downloadStart'));
	        console.log("index page log onDownloadStart");
	    }
	
	    update.onDownloadSuccess = ()=>{
	        self.setLoadingText(Vue.t('checkwgtu.downloadSuccess'));
	        console.log("index page log onDownloadSuccess");
	    }
	
	    update.onInstallStart = ()=>{
	        self.setLoadingText(Vue.t('checkwgtu.installStart'));
	        console.log("index page log onInstallStart");
	    }
	
	    update.onInstallSuccess = async ()=>{
	    	self.setLoadingText(Vue.t('checkwgtu.installSuccess'));
    		console.log("index page log onInstallSuccess");
	        
		    //更新app缓存的productId和对应版本
		    let updateInfo = [];
		    let flag = false
			updateInfo = await iot.storage.getMap('updateInfo') ? await iot.storage.getMap('updateInfo') : [];
			console.log(updateInfo);
			if(updateInfo){
				for(let j=0; j<updateInfo.length; j++){
					if(productId == updateInfo[j].product_id){
						flag = true;
						updateInfo.splice(j, 1, setUpdateInfoMap(productId, version, name));
						break;
					}
				}
			}else{
				updateInfo.push(setUpdateInfoMap(productId, version, name));
				console.log(updateInfo);
			}
			if(flag == false){
				updateInfo.push(setUpdateInfoMap(productId, version, name));
			}
			console.log(updateInfo);
		    iot.storage.setMap('updateInfo', updateInfo, (response) => {
				console.log(response);
				//资源包安装成功，跳转到首页
            	openProductIndex(self, productId);
		    }, () => {});
	    }
	    
	    update.onStateChanged = (download, status) => {
	    	console.log(download);
	    	console.log(status);
	    	var percent = (download.downloadedSize/download.totalSize).toFixed(2)*100;
	    	console.log(percent);
	    }
	
	    update.onError = ()=>{
	        console.log("index page log onError");
	        uComponents.openAlert(self.$parent, Vue.t('checkwgtu.downloadFailure'), {
		        text: Vue.t('checkwgtu.restart'), callback: function () {
		        	getDeviceList(self);
		       	}
		    });
		    uComponents.openConfirm(self.$parent, Vue.t('checkwgtu.needUpdateWgtu'),
		       {text: Vue.t('checkwgtu.exit'), callback: function () {
		       		//不需要更新
			    	plus.runtime.quit();
		       }},
		       {text: Vue.t('checkwgtu.restart'), callback: function () {
	        		getDeviceList(self);
		       }}
		    );
	    }
	    
	    update.downWgt();
	}
	
	//转为map类型
	function setUpdateInfoMap(pid, v, name){
		let update = {
			'product_id': pid,
			'version': v,
			'name': name
		}
		return update;
	}
	
	//页面跳转到添加设备页面
	function openAddDevice(){
		iot.navigator.openWindow({
			url: '../addDevice/index.html',
		    id: 'devicaddDevice',
		    styles: {
		      	popGesture: 'none'
		    },
		    extras: {
		    	needClose: true
		    }
		});
	}
	
	//页面跳转到默认主页
	function openDefaultIndex(){
		iot.navigator.openWindow({
			url: '../device/index.html',
	        id: 'device',
	        styles: {
	        	popGesture: 'none'
	        },
	        extras: {
	        	needClose: true
	        }
	    });
	}
	
	//页面跳转到默认主页
	function openProductIndex(self, pid){
		//验证存在该页面
		iot.navigator.openWindow({
			url: '../../custom/custom'+pid+'/view/device/index.html',
	        id: 'device',
	        styles: {
	        	popGesture: 'none'
	        },
	        extras: {
	        	needClose: true,
	        	info: self.getDeviceInfo()
	        }
	    });
	}
	

</script>