/**
* v_unlockInfo.js
* Version: 0.1
* User: wy
* Date: 2017-10-09
* Copyright(c)  2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* 绑定开锁信息页面
*/

import moment from 'moment'; 
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(),
            unlockInfoList: [],
            openLockInfoList: [],
            extras: {},
            role: null,
            lockItems: [],
            selectItem: 0,
            unlockInfoListTip: Vue.t('unlockInfo.unlockInfoListTip'),
            noHistoryTip: Vue.t('unlockInfo.noHistoryTip'),
            tipShowFlag: true,
            infoList: [],
            newUnlockInfo: false
//          list: [],
//          pullup: false,
//          loadText: Vue.t('scroll.clickToLoadMore'),
//          // loading是否显示
//          loadShowFlag: false,
//          // 是否在loading
//          loadFlag: false,
//          tipShowFlag: false
        },
        mounted(){           
        	this.extras = iot.navigator.getExtras();
        	this.role = this.extras.role;
        	console.log(this.extras);
        	let self = this;
			this.lockItems = [{text: Vue.t('unlockInfo.bindSoon')},{text: Vue.t('unlockInfo.bindedLockInfo')}];
			itemChange(this, this.selectItem);
//			this.setLoadShowFlag(this.infoList.length);
//          let ulistDom = this.$refs.infoList;
//          ulistDom.onscroll = function () {
//				//在一些特殊情况下ulistDom.scrollHeight和ulistDom.offsetHeight + ulistDom.scrollTop会相差1px,这里考虑1px的误差
//              console.log(self.loadFlag+'+'+self.pullup+'+'+ulistDom.scrollHeight+'+'+ulistDom.scrollTop);
//              if (!self.loadFlag && self.pullup && (ulistDom.scrollHeight - (ulistDom.offsetHeight + ulistDom.scrollTop)) <= 1) {
//                  self.loadText = Vue.t('scroll.loading');
//                  self.loadFlag = true;
//                  getBindedLockInfo(self);
//              }
//          }
        },
        methods:{
        	getUnlockInfoList(){
        		return this.unlockInfoList;
        	},
        	setUnlockInfoList(list){
        		this.unlockInfoList = list
        	},
        	getOpenLockInfoList(){
        		return this.openLockInfoList;
        	},
        	setOpenLockInfoList(list){
        		this.openLockInfoList = list;
        	},
        	getSelectItem(){
        		return this.selectItem;
        	},
        	setSelectItem(index){
        		this.selectItem = index;
        	},
        	getInfoList(){
        		return this.infoList;
        	},
        	setInfoList(list){
        		this.infoList = list;
        	},
        	getNewUnlockInfo(){
        		return this.newUnlockInfo;
        	},
        	setNewUnlockInfo(info){
        		this.newUnlockInfo = info;
        	},
            //tap <
            onBackTap(){
                backTap();
            },
//          onAddTap(){
//          //tap 添加
//              addTap(this);
//          },
            onItemChange(key){
            	itemChange(this, key);
            },
            onImgButtonTap(index, buttonIndex){
            	imgButtonTap(this, index, buttonIndex);
            },
            setLoadShowFlag(number) {
                this.loadShowFlag = (number >= this.pagesize);
            },
            onTapLoad() {
                tapLoad(this);
            },
            changeList(list) {
                changeList(this, list);
            }
        }   
    }).$mount('#app');
}

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

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

//tap 添加 
function addTap(self){
    iot.navigator.openWindow({
        url: './addUnlockInfo.html',
        id: 'addUnlockInfo',
        extras: {
        	deviceId: self.extras.deviceId,
        	id: self.extras.id
        }
    });
}

//点击加载更多
function tapLoad(){
    if (!self.loadFlag) {
        self.loadText = Vue.t('scroll.loading');
        self.loadFlag = true;
        //再次发送获取用户列表请求
    }
}

//获取已绑定的开锁信息
function getBindedLockInfo(self){
	uComponents.showLoading(self);
	iot.business.api.sendCustom('lock/getBindOpen',{
		data: {
			rel_id: self.extras.id,
			device_id: self.extras.deviceId
		},
		success: (response) => {
			console.log(response);
			let data = uPublic.checkResponseData(response.data);
	    	if(data){
	    		console.log(data);
	    		self.setOpenLockInfoList(data);
				let list = [];
				let j = 1;
				let lastMode = null;
				for(let i=0; i<data.length; i++){
					if(data[i].mode != lastMode){
						j = 1;
					}
					list[i] = {
						title: Vue.t('unlockInfo.'+config.openDoorMode[data[i].mode]+'')+j+'',
						subtitle: 'ID:'+data[i].openId,
//						buttons: self.extras.role ? [] : [{'text': data[i].mode == 20 ?  Vue.t('unlockInfo.cancelHijack') :  data[i].mode == 2 ? Vue.t('unlockInfo.setHijack') : ''},{'text': Vue.t('unlockInfo.cancelAssociated')}]
						buttons: self.extras.role ? [] : (data[i].mode == 20 || data[i].mode == 2) ? [{"imgSrc": data[i].mode == 20 ? "../../resources/image/green_deleteHijack_icon.png" : "../../resources/image/green_setHijack_icon.png"},{"imgSrc": "../../resources/image/green_deleteUnlockInfo_icon.png"}] : [{"imgSrc": null},{"imgSrc": "../../resources/image/green_deleteUnlockInfo_icon.png"}]
					};
					j++;
					lastMode = data[i].mode;
				}
				//更新列表
				self.setInfoList(list);
//				changeList(self, list);
	    	}else{
	    		//当已绑定信息为空时，列表渲染为空
	    		self.setInfoList([]);
	    	}
		},
		error: (error) => {
			console.log(error);
			uPublic.openRequestErrorAlert(self);
		},
		complete: () => {
			uComponents.hideLoading(self);
		}
	});
}
function unlockInfoListButtonTap(self, value, buttonValue) {
    //设为劫持&取消劫持
    if(buttonValue == '0'){
    	if(self.getOpenLockInfoList()[value].mode == 2){
    		uComponents.openConfirm(self, Vue.t('unlockInfo.setHijackTip'), 
	           {text: Vue.t('dialog.cancel'), callback: function () {}},
	           {text: Vue.t('dialog.confirm'), callback: function () {
	           		console.log("设为劫持");
	           		uComponents.showLoading(self);
	           		iot.business.api.sendCustom('lock/updateBindLog',{
						data: {
							mode: 20,
							id: self.getOpenLockInfoList()[value].id,
							rel_id: self.extras.id
						},
						success: (response) => {
							console.log(response);
							uComponents.openAlert(self, Vue.t('unlockInfo.setHijackSuccess'), {
						        text: Vue.t('dialog.confirm'), callback: function () {
						        	getBindedLockInfo(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('unlockInfo.setHijackFailue'), {
						        text: Vue.t('dialog.confirm'), callback: function () {
						        }
						    });
						},
						complete: () => {
							uComponents.hideLoading(self);
						}
					});
	        }});
    	}else{
    		uComponents.openConfirm(self, Vue.t('unlockInfo.cancelHijackTip'), 
	           {text: Vue.t('dialog.cancel'), callback: function () {}},
	           {text: Vue.t('dialog.confirm'), callback: function () {
	           		console.log("取消劫持");
	           		uComponents.showLoading(self);
	           		iot.business.api.sendCustom('lock/updateBindLog',{
						data: {
							mode: 2,
							id: self.getOpenLockInfoList()[value].id,
							rel_id: self.extras.id
						},
						success: (response) => {
							console.log(response);
							uComponents.openAlert(self, Vue.t('unlockInfo.cancelHijackSuccess'), {
						        text: Vue.t('dialog.confirm'), callback: function () {
						        	getBindedLockInfo(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('unlockInfo.cancelHijackFailue'), {
						        text: Vue.t('dialog.confirm'), callback: function () {
						        }
						    });
						},
						complete: () => {
							uComponents.hideLoading(self);
						}
					});
	        }});
    	}
    }
    //取消关联
    else if(buttonValue == '1'){
        console.log(self.getOpenLockInfoList()[value]);
        uComponents.openConfirm(self, Vue.t('unlockInfo.cancelAssociatedTip'), 
           {text: Vue.t('dialog.cancel'), callback: function () {}},
           {text: Vue.t('dialog.confirm'), callback: function () {
           		uComponents.showLoading(self);
           		iot.business.api.sendCustom('lock/unbindOpenLog',{
					data: {
						device_id: self.extras.deviceId,
						mode: self.getOpenLockInfoList()[value].mode,
						openId: self.getOpenLockInfoList()[value].openId,
						rel_id: self.extras.id
					},
					success: (response) => {
						console.log(response);
						uComponents.openAlert(self, Vue.t('unlockInfo.cancelAssociatedSuccess'), {
					        text: Vue.t('dialog.confirm'), callback: function () {
					        	getBindedLockInfo(self);
					        }
					    });
					},
					error: (error) => {
						console.log(error);
						uComponents.openAlert(self, Vue.t('unlockInfo.cancelAssociatedFailue'), {
					        text: Vue.t('dialog.confirm'), callback: function () {
					        }
					    });
					},
					complete: () => {
						uComponents.hideLoading(self);
					}
				});
           }}
        ); 
    }
}

function itemChange(self, key){
	self.setInfoList([]);
	if(key == 0){
		//获取未关联的开门记录
		getTodayReccord(self);
	}else if(key == 1){
		//获取已关联的开门记录
		self.setNewUnlockInfo(false);
		getBindedLockInfo(self);
	}
	self.setSelectItem(key);
}

function imgButtonTap(self, index, buttonIndex){
	if(self.getSelectItem() == 0){
		addButtonTap(self, index);
	}else if(self.getSelectItem() == 1){
		unlockInfoListButtonTap(self, index, buttonIndex);
	}
}

//获取当天未绑定的开门记录
function getTodayReccord(self){
	uComponents.showLoading(self);
	iot.business.api.sendCustom('lock/getUnbindOpen',{
		data: {
			device_id: self.extras.deviceId
		},
		success: (response) => {
			console.log(response);
			let data = response.data;
				self.setUnlockInfoList(data);
				let list = [];
				for(let i = 0; i < data.length; i++){
					list[i] = {
						value: data[i].id,
						title: 'ID:'+data[i].openId,
						subtitle: moment(data[i].time).format("HH:mm")+' '+Vue.t('opendoorRecord.'+config.openDoorMode[data[i].mode]+''),
						buttons: [{"text": Vue.t('unlockInfo.bindUnlockInfo')}]
					}
				}
				self.setInfoList(list);
		},
		error: (error) => {
			console.log(error);
			uPublic.openRequestErrorAlert(self);
		},
		complete: () => {
			uComponents.hideLoading(self);
		}
	});
}

//tap 添加 
function addButtonTap(self, index){
	uComponents.showLoading(self);
	iot.business.api.sendCustom('lock/bindOpenLog',{
		data: {
			device_id: self.extras.deviceId,
			mode: parseInt(self.getUnlockInfoList()[index].mode),
			openId: parseInt(self.getUnlockInfoList()[index].openId),
			rel_id: self.extras.id
		},
		success: (response) => {
			console.log(response);
			if(response.data.success){
			    uComponents.openAlert(self, Vue.t('unlockInfo.addInfoSuccess'), 
		           {text: Vue.t('btn.confirm'), callback: function () {
		           		getTodayReccord(self);
		           		self.setNewUnlockInfo(true);
		           }});
			}else{}
		},
		error: (error) => {
			console.log(error);
			uComponents.openAlert(vmObj, Vue.t('addUnlockInfo.addInfoFailue'), {
		        text: Vue.t('dialog.confirm'), callback: function () {
		        }
		    });
		},
		complete: () => {
			uComponents.hideLoading(self);
		}
	});
}

// // 通知点击加载更多事件
//function tapLoad(self) {
//  // loading
//  if (!self.loadFlag && !self.pullup) {
//     	getBindedLockInfo(self);
//      self.loadText = Vue.t('scroll.loading');
//      self.loadFlag = true;
//  }
//}
//
//// 修改list组件列表
//function changeList(self, list) {
//  let array = Array.isArray(list) ? list : [];
//  self.tipShowFlag = (array.length === 0);
//  self.setLoadShowFlag(array.length - self.list.length);
//  self.list = array;
//  self.$nextTick(function () {
//      self.loadText = Vue.t('scroll.clickToLoadMore');
//      self.loadFlag = false;
//  });
//}