/**
* v_index.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 {projectMethods} from '../../public/components.js';

iot.ready(init);
function init() {
    //通用 按钮、dialog、loading组件
    uPublic.componentsInit(['u-button','u-dialog','u-loading']);
    //项目 list组件
    uPublic.componentsExtend(['grid-list']);
    const app = new Vue({
        data:{            
            //配置组件
            componentsConfig: initComponentsConfig(),
            //设备列表
            deviceList: [],
            showDeviceList: []
            },
        mounted(){   
			let self = this;
			window.addEventListener('returnPage',function(event){
				self.showDeviceList = [];
				getDeviceList(self);
			});
	    	//获取设备列表
	    	getDeviceList(self);
        },
        methods:{
        	getDeviceList(){
        		return this.deviceList;
        	},
        	setDeviceList(list){
        		this.deviceList = list;
        	},
        	getShowDeviceList(){
        		return this.showDeviceList;
        	},
        	setShowDeviceList(list){
        		this.showDeviceList = list;
        	},
            //tap <
            onBackTap(){
                backTap();
            },       
            //tap +
            onAddTap(){
                addTap();
            },
            //tap list row device
            onDoorlockListTap(){
                doorlockListTap();
            },
            //tap list row button
            onDoorlockListButtonTap(value, buttonValue){
                doorlockListButtonTap(this, value, buttonValue);
            },
            //tap 退出系统
            onLogoutButtonTap(){
                logoutButtonTap(this);
            }
        }   
    }).$mount('#app');
}


//配置组件参数
function initComponentsConfig() {
    return {
        doorlockList: {
            initParam: {
                class: '',
                list: [],
                tip: Vue.t('doorlockManage.noDeviceTip')
            }
        },
        //退出系统 button 参数
        logoutButton: {   
            initParam: {
                class: 'custom-button',
                text: Vue.t('btn.logout')
            }
        }, 
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        }                
    }
}

//获取所有的设备
function getDeviceList(self){
	//显示loading
	uComponents.showLoading(self);
	iot.business.device.getList({
	    data: {
	        sds: true,
//	        product_id: 'product_id',
//	        parent_id: 0,
//	        start_id: 0,
//	        number: 10
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
	    	if(data){
	    		self.setDeviceList(data);
	    		for(let i=0; i<data.length; i++){
	    			self.getShowDeviceList().push({
		    			value: data[i].uuid,
		    			leftImage: '../../resources/image/device.png',
		    			title: (data[i].nickName && data[i].nickName != 'null') ? data[i].nickName : Vue.t('doorlockManage.defaultNickname'),
		    			buttons: [{'icon': '&#xe728;'},{'icon': '&#xe61b;'},{'icon': '&#xe63e;'},{'icon': '&#xe742;'}]
		    		});
	    		}
	    		//更新设备列表
	    		projectMethods.changeGridList(self, self.getShowDeviceList());
	    		uComponents.hideLoading(self);
	    	}else{
	    		uComponents.hideLoading(self);
	    	}
	    },
	    error: (error) => {
	    	console.log(error);
	    	//请求失败
    		uPublic.openRequestErrorAlert(self);
	    },
	    complete: () => {
	    	uComponents.hideLoading(self);
	    }
	});
}

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

//tap +
function addTap(){
    iot.navigator.openWindow({
        url: '../addDevice/',
        id: 'addDevice'
    });
}

//tap list row device
function doorlockListTap(){
    iot.navigator.openWindow({
        url: '../device/',
        id: 'device'
    });
}

//tap list row button
function doorlockListButtonTap(self, value, buttonValue) {
    //tap 修改名称
    if(buttonValue == '0'){
        iot.navigator.openWindow({
            url: './editName.html',
            id: 'editName',
            extras: {
                uuid: self.getDeviceList()[value].uuid,
		        model: self.getDeviceList()[value].model,
		        nickName: self.getDeviceList()[value].nickName	
            }
        });
    }
    //tap 生成绑定二维码
    else if(buttonValue == '1'){
        iot.navigator.openWindow({
            url: './qrcode.html',
            id: 'qrcode',
            extras: {
            	uuid: self.getDeviceList()[value].uuid	
            }
        });
    }
    //tap ID-姓名绑定
    else if(buttonValue == '2'){
        iot.navigator.openWindow({
            url: '../bindUser/',
            id: 'bindUser'
        });
    }
    //tap 删除门锁
    else if(buttonValue == '3'){
        uComponents.openConfirm(self, Vue.t('doorlockManage.deleteDialogTip', ['门锁-001']),
           {text: Vue.t('dialog.cancel'), callback: function () {
           		
           }},
           {text: Vue.t('dialog.confirm'), callback: function () {
           		deleteDoorlook(self, value);
           }}
        );
    }
}

//tap 退出系统
function logoutButtonTap(self){
    uComponents.openConfirm(self, Vue.t('doorlockManage.logoutDialogTip'), 
       {text: Vue.t('dialog.cancel'), callback: function () {}}, 
       {text: Vue.t('dialog.confirm'), callback: function () {
       		iot.business.user.logout({
			    data: {
			        sds: true
			    },
			    success: (response) => {
			    	iot.navigator.openWindow({
				        url: '../login/',
				        id: 'login'
				    });
				    let wvs = plus.webview.all();
				    for (var i = 0; i < wvs.length-1; i++) {
                        plus.webview.close(wvs[i]);
                    }
			    },
			    error: (error) => {},
			    complete: () => {
			    	console.log("complete");
			    }
			});                    
       }}
    );  
}
//17621209360
//yyl111

function deleteDoorlook(self, index){
	// 显示loading
	let uuId  = self.getDeviceList()[index].id;
	uComponents.showLoading(self);
    iot.business.device.unbind({
    	data: {
    		sds: true,
    		uuid: self.getDeviceList()[index].uuid
    	},
    	success: function (response){
    		let data = uPublic.checkResponseData(response.data);
    		if(data){
	            //删除成功
    			self.getDeviceList().splice(index, 1);
	            self.getShowDeviceList().splice(index, 1);
	            rojectMethods.changeGridList(self, self.getDeviceList());
	    		uComponents.openAlert(self, Vue.t('doorlockManage.deleteSuccess'), {
		        text: Vue.t('btn.confirm'), callback: function () {
		        		console.log("删除成功");
			            projectMethods.changeGridList(self, self.getShowDeviceList());
			            uComponents.hideLoading(self);
			        }
		    	});
    		}else{
    			//删除失败
    			uComponents.openAlert(self, Vue.t('doorlockManage.editNameFailue'), {
	                text: Vue.t('btn.confirm'), callback: function () {
	                  	console.log("删除失败");
	                    uComponents.hideLoading(self);
	                }
	            });
    		}
    	},
    	error: function (err){
    		console.log(err);
    		//请求失败
    		uPublic.openRequestErrorAlert(self);
    	},
    	complete: function (){
    		console.log("complete");
    		uComponents.hideLoading(self);
    	}
    });
}
