/**
* v_opendoorRecord.js
* Version: 0.1
* User: wy
* Date: 2017-09-06
* Copyright(c)  2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* 开门记录页面
*/
import moment from 'moment'; 
const PAGE_SIZE = 10;
import config from '../../public/config.js';
import {iot, uPublic, uComponents} from '../../public/public.js';

iot.ready(init);
function init() {
    //通用 list、dialog、loading组件
    uPublic.componentsInit(['u-list','u-dialog','u-loading']);
    uPublic.closeSlideBack();
    const app = new Vue({
        data:{            
            //配置组件
            componentsConfig: initComponentsConfig(),
            list: [],
            startId: 0,
            deviceId: null,
            userInfo: [],
            flag: true,
            noticeTipShowFlag: false
        },
        mounted(){     
        	uComponents.showLoading(this);
        	this.noticeTipShowFlag = !iot.native.isNotifycationOpen();
        	resolve(this);
        	window.addEventListener('returnPage',() => {
				this.noticeTipShowFlag = !iot.native.isNotifycationOpen();
			});
        },
        methods:{
        	getList(){
        		return this.list;
        	},
        	setList(list){
        		this.list = list;
        	},
        	getStartId(){
        		return this.startId;
        	},
        	setStartId(id){
        		this.startId = id;
        	},
        	getDeviceId(){
        		return this.deviceId;
        	},
        	getUserInfo(){
        		return this.userInfo;
        	},
        	setUserInfo(info){
        		this.userInfo = info;
        	},
        	setDeviceId(id){
        		this.deviceId = id;
        	},
        	onListLoad(){
        		listLoad(this);
        	},
        	onRefreshFresh(){
        		refreshFresh(this);
        	},
        	onNotifycationSetting(){
        		notifycationSetting();
        	},
            //tap <
            onBackTap(){
                backTap();
            }                    
        }   
    }).$mount('#app');
}

//配置组件参数
function initComponentsConfig() {
    return {
        opendoorRecordList:{   
            initParam: {
                class: 'custom-list',
				list: [],
                tip: Vue.t('opendoorRecord.noRecordTip'),
                pagesize: PAGE_SIZE,
                pullup: true
            }
        },
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        }
    }
}

//调用接口获取开门记录
function resolve(self) {
	console.log("in");
//	uComponents.showLoading(self);
	self.setDeviceId(iot.navigator.getExtras().deviceId);
	console.log(iot.navigator.getExtras());
	if(iot.navigator.getExtras().relId){
		getPersonalHistory(self, iot.navigator.getExtras().relId);
	}else{
		getHistoryRecord(self);
	}
}

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

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

//tap 点击加载更多
function listLoad(self) {
	resolve(self);
}

//获取历史记录（整个设备）
function getHistoryRecord(self){
	iot.business.api.sendCustom('lock/getHistoryRecord',
	{
		data: {
			device_id: self.getDeviceId(),
			action: 0,
			start_id: self.getStartId(),
			page_size: PAGE_SIZE
		},
		success: async (response) => {
			setListData(self, response);
			if(self.flag){
				let data = uPublic.checkResponseData(response.data);
				if(data && data.record.length > 0){
					let record = data.record;
					self.flag = await uPublic.upDateRead('open', moment(record[0].time).unix());
				}
			}
		},
		error: (error) => {
	    	console.log(error);
           	uPublic.openRequestErrorAlert(self);
		},
		complete: () => {
			uComponents.hideLoading(self);
		}
	});
}

//获取个人历史记录
function getPersonalHistory(self, id){
	iot.business.api.sendCustom('lock/getPersonalHistory',
	{
		data: {
			device_id: self.getDeviceId(),
			rel_id: id,
			action: 0,
			start_id: self.getStartId(),
			page_size: PAGE_SIZE
		},
		success: (response) => {
			setListData(self, response);
		},
		error: (error) => {
	    	console.log(error);
          	uPublic.openRequestErrorAlert(self);
		},
		complete: () => {
			uComponents.hideLoading(self);
		}
	});
}

//设置历史记录渲染列表
function setListData(self, response){
	let data = uPublic.checkResponseData(response.data);
	if(data){
		console.log(data);
		let list = [];
		let record = data.record;
		if(data.hasOwnProperty('info')){
			self.setUserInfo(data.info);
		}
		for(let i=0; i<record.length; i++){
			list[i] = {
				value: record[i].openId,
				title: ((record[i].mode == 30 ) || (record[i].mode == 5 ))  ? '':"ID:"+record[i].openId,
				leftImage: '../../resources/image/green_opendoor'+record[i].mode+'_icon.png',
				subtitle: Vue.t('opendoorRecord.'+config.openDoorMode[record[i].mode]+''),
				rightText: moment(record[i].time).format("YYYY.MM.DD HH:mm:ss")
			};
			for(let j=0; j<self.getUserInfo().length; j++){
				if(record[i].openId == self.getUserInfo()[j].openId && record[i].mode == self.getUserInfo()[j].mode){
					if(self.getUserInfo()[j].nickname != null){
						list[i].title = self.getUserInfo()[j].nickname;
					}
				}
			}
		}
		self.setList(self.getList().concat(list));
		if(record.length > 0){
			self.setStartId(record[record.length-1].id);
		}
		//更新列表数据
        uComponents.changeList(self, self.getList());
        console.log("in");
	}else{
	}
}

//ios跳转到系统设置页面
//android跳转到通知页面
function notifycationSetting(){
	if(plus.os.name == 'Android'){
		iot.navigator.openWindow({
	        url: './notify.html',
	        id: 'notify',
	        styles: {
	        	popGesture: 'none'
	        }
	    });
	}else{
		iot.native.toNotifycationSetting();
	}
}
