/**
* v_index.js
* Version: 0.1
* User: zjx
* Date: 2017-09-29
* 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';

iot.ready(init);
function init() {
    //通用 图片轮播、跑马灯、开关、按钮、dialog、loading组件
    uPublic.componentsInit(['u-swipe-list','u-dialog','u-loading']);
    uPublic.closeSlideBack();
    const app = new Vue({
        data:{ 
        	//配置组件
            componentsConfig: initComponentsConfig(),
        	//用户列表
        	userList: [],
        	userListIndex: null,
        	loadShowFlag: false,
        	loadFlag: false,
        	loadText: '',
        	pagesize: 10,
        	tip: '无数据',
        	extras: {},
        	userListData: [],
        	startId: 0,
        	role: null,
        },
        mounted(){
        	this.extras = iot.navigator.getExtras();
        	//获取用户列表
        	this.role = this.extras.role;
        	getUserList(this);
        	let self = this;
        	window.addEventListener('returnPage',function(event){
				console.log("returnPage");
				self.setUserList([]);
				getUserList(self);
			});
        },
        methods:{
        	getUserList(){
 				return this.userList;       		
        	},
        	setUserList(list){
        		this.userList = list;
        	},
        	onBackTap(){
        		backTap();
        	},
        	onAddUserTap(){
        		addUserTap(this);
        	},
        	setLoadShowFlag(number){
                this.loadShowFlag = (number >= this.pagesize);
            },
            getUserListData(){
            	return this.userListData;
            },
            setUserListData(data){
            	this.userListData = data;
            },
            getStartId(){
            	return this.startId;
            },
            setStartId(id){
            	this.startId = id;
            },
            getRole(){
            	return this.role;
            },
            setRole(role){
            	this.role = role;
            },
            //
//          onSwipeLeftRow(index){
//              swipeLeftRow(this, index);
//          },
//          onSwipeRightRow(){
//              swipeRightRow(this);
//          },
            //
        	onTapLoad(){
//      		tapLoad();
        	},
        	onTapUserList(index){
        		onTapUserList(this, index);
        	},
        	onTapButton(index){
        		tapButton(this, index);
        	}
		}
          
    }).$mount('#app');
}

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

//获取用户列表
function getUserList(self){
	uComponents.showLoading(self);
	iot.business.api.sendCustom('lock/getLockUser',{
	    data: {
	        device_id: self.extras.deviceId
	    },
	    success: (response) => {
	    	console.log(response);
	    	let data = uPublic.checkResponseData(response.data);
			console.log(data);
	    	if(data){
				sortUsers(self,data);
	    	}
	    },
	    error: (error) => {
	    	console.log(error);
//	    	if(window.iotDebug){
//              iotDebug.push('end: 获取用户列表失败'+JSON.stringify(error));
//         	}
//	    	if (window.iotDebug) {
//              iotDebug.upload(iot,'获取用户列表失败');
//          }
	    	uPublic.openRequestErrorAlert(self);
	    },
	    complete: () => {
			uComponents.hideLoading(self);
	    }
	});
}

//
function sortRule(a,b){
	return a.role - b.role;
}

function getUserInfoMap() {
    return new Promise(function (resolve, reject) {
        iot.business.websql.getMap('userinfo', (res) => {
	        if (res) {
	            resolve(res.id);
	        } else {
	            reject(res);
	        }
		    }, (err) => {
		        console.log(err);
	    });
    })
}

async function sortUsers(self, data){
	let id = [];
	try {
        id = await getUserInfoMap();
    }
    catch (err) {
        console.log(err);
    }
    let users = [];
	let manage = [];
	for(let i=0;i<data.length;i++){
		if(data[i].user_id == null ||data[i].role && data[i].user_id != id){
			users.push(data[i]);
		}else{
			manage.push(data[i]);
		}
	}
	manage = manage.sort(sortRule);
	console.log(manage);
	data = manage.concat(users);
	setUserData(self, data);
}

function setUserData(self, data){
	let list = [];
	for(let i = 0; i < data.length ; i++){
		list[i] = {
			value: data[i].id,
			role: data[i].role,
			image: data[i].role == 0 ? '../../resources/image/green_admin_icon.png' : data[i].user_id == null ? '../../resources/image/gray_unbindHead_icon.png' : '../../resources/image/green_bindHead_icon.png',
			title: data[i].nickname,
			subtitle: data[i].username ? Vue.t('userList.binded'):Vue.t('userList.unbind')
		}
	}
	console.log(data);
    self.setUserListData(data);
	self.setUserList(list);
}

//返回上一页
function backTap(){
   iot.navigator.aback();
}

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

//添加用户
function addUserTap(self){
	iot.navigator.openWindow({
        url: '../doorlockUsers/addUser.html',
        id: 'addUser',
        extras: {
        	deviceId: self.getUserListData()[0].device_id,
        	uuid: self.extras.uuid,
        	lockId: self.extras.lockId,
        	role: self.extras.role
        }
    });
}
//
//// 向左滑动用户列表，修改用户列表下标
//function swipeLeftRow(self, index) {
//	self.userListIndex = index;
//}
//// 向右滑动用户列表，修改用户列表下标
//function swipeRightRow(self) {
//	self.userListIndex = null;
//}
//
// 点击组件列表 通知事件和当前点击列表下标
function onTapUserList(self, listIndex) {
	iot.navigator.openWindow({
        url: './doorlockUser.html',
        id: 'doorlockUser',
        extras: {
        	id: self.getUserListData()[listIndex].id,
        	uuid: self.extras.uuid,
        	account: self.getUserListData()[listIndex].account,
        	lockId: self.extras.lockId,
        	role: self.extras.role
        }
    });
 	if (self.userListIndex != null) {
        self.userListIndex = null;
    }
}

//点击按钮
function tapButton(self, index){
	console.log(index);
	//tap 删除该用户
    uComponents.openConfirm(self, Vue.t('doorlockUser.deleteUserDialogTip'),
       {text: Vue.t('dialog.cancel'), callback: function () {}},
       {text: Vue.t('dialog.delete'), callback: function () {
       		deleteUser(self, index);
       }}
    );
}

//删除用户
function deleteUser(self, index){
	uComponents.showLoading(self);
	iot.business.api.sendCustom('lock/delLockUser',{
    	data: {
    		rel_id: self.getUserListData()[index].id,
    		user_id: self.getUserListData()[index].user_id,
    		device_sn: self.getUserListData()[index].device_id,
    		device_id: self.extras.lockId
    	},
    	success: (response) => {
    		console.log(response);
    		if(response.data.success){
    			uComponents.openAlert(self, Vue.t('doorlockUser.deleteSuccess'), {
		        text: Vue.t('btn.confirm'), callback: function () {
		        		self.setUserList([]);
						getUserList(self);
			        }
		    	});
    		}
    	},
    	error: (error) => {
    		console.log(error);
//  		if(window.iotDebug){
//              iotDebug.push('end: 删除用户失败'+JSON.stringify(error));
//         	}
//	    	if (window.iotDebug) {
//              iotDebug.upload(iot,'删除用户失败');
//          }
    		uComponents.openAlert(self, Vue.t('doorlockUser.deleteFailure'), {
	        text: Vue.t('btn.confirm'), callback: function () {
		        }
	    	});
    	},
    	complete: () => {
			uComponents.hideLoading(self);
    	}
    });
	
}