/**
* v_addUnlockInfo.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() {
    //通用 select、开关、按钮、dialog、loading组件
    uPublic.componentsInit(['u-select','u-switch','u-button','u-dialog','u-loading']);
    uPublic.closeSlideBack();
    const app = new Vue({
        data:{     
            recordSelectIndex: 0,
            openId: null,
            mode: 1,
            recordSelectList: [],   
            waysOpenDoor: [],
            selectedMode: 1,
            valueSetHijack: 0,
            guideShowFlag: false,   
            guideStep1ShowFlag: false, 
            guideStep2ShowFlag: false,  
            guideStep3ShowFlag: false,   
            guideStep4ShowFlag: false,  
            guideStep5ShowFlag: false,   
            guideStep6ShowFlag: false,                         
            //配置组件
            componentsConfig: initComponentsConfig(),
            extras: {}
        },
        mounted(){    
        	this.extras = iot.navigator.getExtras();
        	console.log(this.extras);
        	let self = this;
        	for( let i =1 ; config.openDoorWay.hasOwnProperty(i) ;i++){
        		self.waysOpenDoor.push(
	        		{
	        			mode: i,
	        			text: Vue.t('unlockInfo.'+config.openDoorWay[i]+'')
	        		}
        		)
        	}
        	resolve(this);
        },
        methods:{
        	getRecordSelectIndex(){
        		return this.recordSelectIndex;
        	},
        	setRecordSelectIndex(index){
        		this.recordSelectIndex = index;
        	},
        	getOpenId(){
        		return this.openId;
        	},
        	setOpenId(id){
        		this.openId = id;
        	},
        	getMode(){
        		return this.mode;
        	},
        	setMode(mode){
        		this.mode = mode;
        	},
        	getRecordSelectList(){
        		return this.recordSelectList;
        	},
        	setRecordSelectList(list){
        		this.recordSelectList = list;
        	},
        	getSelectedMode(){
        		return this.selectedMode;
        	},
        	setSelectedMode(mode){
        		this.selectedMode = mode
        	},
            getGuideShowFlag(){
                return this.guideShowFlag;
            },
            setGuideShowFlag(boolean){
                this.guideShowFlag = boolean;
            },
            getGuideStep1ShowFlag(){
                return this.guideStep1ShowFlag;
            },
            setGuideStep1ShowFlag(boolean){
                this.guideStep1ShowFlag = boolean;
            },
            getGuideStep2ShowFlag(){
                return this.guideStep2ShowFlag;
            },
            setGuideStep2ShowFlag(boolean){
                this.guideStep2ShowFlag = boolean;
            },
            getGuideStep3ShowFlag(){
                return this.guideStep3ShowFlag;
            },
            setGuideStep3ShowFlag(boolean){
                this.guideStep3ShowFlag = boolean;
            },
            getGuideStep4ShowFlag(){
                return this.guideStep4ShowFlag;
            },
            setGuideStep4ShowFlag(boolean){
                this.guideStep4ShowFlag = boolean;
            },
            getGuideStep5ShowFlag(){
                return this.guideStep5ShowFlag;
            },
            setGuideStep5ShowFlag(boolean){
                this.guideStep5ShowFlag = boolean;
            },
            getGuideStep6ShowFlag(){
                return this.guideStep6ShowFlag;
            },
            setGuideStep6ShowFlag(boolean){
                this.guideStep6ShowFlag = boolean;
            },
            //tap <
            onBackTap(){
                backTap();
            },
            onRecordSelectChange(value) {
                recordSelectChange(this, value);
            },
            //tap 添加
            onAddButtonTap(){
                addButtonTap(this);
            },
            onSelectOpenDoorModeTap(index){
            	selectOpenDoorModeTap(this, index);
            },
            //tap 下一步
            onNextButtonTap(){
                nextButtonTap(this);
            },
            onNextStepButtonTap(){
                nextStepButtonTap(this);
            },
            //tap 我知道了
            onISeeButtonTap(){
                iSeeButtonTap(this);
            },
            onSetHijackTap(value){
            	setHijackTap(this, value);
            }
        }   
    }).$mount('#app');
}

//配置组件参数
function initComponentsConfig() {
    return {
        recordSelect: {
            initParam: {
                class: 'custom-select',
                list: [],
                pagesize: Number.MAX_VALUE,
                tip: Vue.t('addUnlockInfo.noRecordTip')
            }
        },
        //设为劫持指纹
        setHijackSwitch: {
            initParam: {
                class: 'custom-setHijack-switch',
                text: Vue.t('addUnlockInfo.setHijackSwitch')
            }
        },
        //添加 button 参数
        addButton: {   
            initParam: {
                class: 'custom-button',
                text: Vue.t('btn.add')
            }
        }, 
        //下一步 button 参数
        nextButton: {   
            initParam: {
                class: 'custom-dialog-button',
                text: Vue.t('btn.next')
            }
        },
        //我知道了 button 参数
        iSeeButton: {   
            initParam: {
                class: 'custom-dialog-button',
                text: Vue.t('btn.iSee')
            }
        },
        dialog: {
            initParam: {
                class: 'custom-dialog'
            }
        },
        loading: {
            initParam: {
                class: 'custom-loading'
            }
        }               
    }
}


function resolve(self){
	getTodayReccordByMode(self,self.getSelectedMode());
	iot.storage.getMap('isFristAddUnlockInfo', (res) => {
		if(res){
			
		}else{
			showGuide(self);
		}
	}, () => {
		showGuide(self);
	});
}

async function showGuide(self){
	self.setGuideShowFlag(true);
	try{		
		let time = await sleep(500);
        self.setGuideStep1ShowFlag(true);   
		
		time = await sleep(500);
		self.setGuideStep2ShowFlag(true);
	}
	catch (err){
		console.log(err);
	}
}

//tap 下一步
function nextButtonTap(self){
    self.setGuideStep1ShowFlag(false);
    self.setGuideStep2ShowFlag(false);
    nextGuide(self);
}

async function nextGuide(self){
	try{		
		let time = await sleep(500);
        self.setGuideStep3ShowFlag(true); 
		
		time = await sleep(500);
		self.setGuideStep4ShowFlag(true);
	}
	catch (err){
		console.log(err);
	}
}

//tap 下一步
function nextStepButtonTap(self){
    self.setGuideStep3ShowFlag(false);
    self.setGuideStep4ShowFlag(false);
	nextStepGuide(self);
}

async function nextStepGuide(self){
	try{
		let time = await sleep(500);
		self.setGuideStep5ShowFlag(true);
		
		time = await sleep(500);
		self.setGuideStep6ShowFlag(true);
	}
	catch (err){
		console.log(err);
	}
}

//tap 我知道了
function iSeeButtonTap(self){
    self.setGuideShowFlag(false);
    iot.storage.setMap('isFristAddUnlockInfo', true,() => {
    }, () => {});
}

function sleep(time){
	return new Promise(function(resolve, reject){
		setTimeout(()=>{
			resolve(time);
		},time);
	})
}

mui.back = function(){
    iot.navigator.fire(plus.webview.currentWebview().opener(),'returnPage',{});
	iot.navigator.back();
}

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

//
function recordSelectChange(self, value) {
	console.log(value);
    self.recordSelectIndex = value;
    console.log('recordSelectChange:' + self.recordSelectIndex);
    for(let i=0; i< self.getRecordSelectList().length; i++){
    	if(self.recordSelectIndex == self.getRecordSelectList()[i].id){
    		self.setOpenId(parseInt(self.getRecordSelectList()[i].openId));
    	}
    }
}

//tap 添加 
function addButtonTap(self){
	if(self.getOpenId()){
		uComponents.showLoading(self);
		iot.business.api.sendCustom('lock/bindOpenLog',{
			data: {
				device_id: self.extras.deviceId,
				mode: self.getMode(),
				openId: self.getOpenId(),
				rel_id: self.extras.id
			},
			success: (response) => {
				console.log(response);
				if(response.data.success){
					uComponents.openAlert(self, Vue.t('addUnlockInfo.addInfoSuccess'), {
				        text: Vue.t('dialog.confirm'), callback: function () {
				        	iot.navigator.fire(plus.webview.currentWebview().opener(),'returnPage',{ });
				        	iot.navigator.back();
				        }
				    });
				}else{}
			},
			error: (error) => {
				console.log(error);
	//			if(window.iotDebug){
	//              iotDebug.push('end: 绑定开门方式失败'+JSON.stringify(error));
	//         	}
	//	    	if (window.iotDebug) {
	//              iotDebug.upload(iot,'绑定开门方式失败');
	//          }
				uComponents.openAlert(vmObj, Vue.t('addUnlockInfo.addInfoFailue'), {
			        text: Vue.t('dialog.confirm'), callback: function () {
			        }
			    });
			},
			complete: () => {
				uComponents.hideLoading(self);
			}
		});
		setTimeout(function(){
			uComponents.openAlert(vmObj, Vue.t('addUnlockInfo.addInfoFailue'), {
		        text: Vue.t('dialog.confirm'), callback: function () {
		        }
		    });
		    uComponents.hideLoading(self);
		},config.wifi_add_timeout);
	}
}

function selectOpenDoorModeTap(self, index){
	self.setSelectedMode(index);
	self.setMode(index);
	getTodayReccordByMode(self,index);
}

function getTodayReccordByMode(self, mode){
	uComponents.showLoading(self);
	iot.business.api.sendCustom('lock/getUnbindOpen',{
		data: {
			mode: self.getSelectedMode(),
			device_id: self.extras.deviceId
		},
		success: (response) => {
			console.log(response);
			let data = response.data;
			self.setRecordSelectList(data);
				let list = [];
				for(let i = 0; i < data.length; i++){
					list[i] = {
						value: data[i].id,
						title: moment(data[i].time).format("HH:mm"),
						subtitle: 'ID:'+data[i].openId
					}
				}
				if(data.length){
					self.setRecordSelectIndex(data[0].id);
					for(let i=0; i< self.getRecordSelectList().length; i++){
				    	if(self.recordSelectIndex == self.getRecordSelectList()[i].id){
				    		self.setOpenId(parseInt(self.getRecordSelectList()[i].openId));
				    	}
				    }
				}
				uComponents.changeSelectList(self,list);
		},
		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 setHijackTap(self, value){
	if(value){
		self.setMode(20);
	}else{
		self.setMode(2);
	}
	console.log(self.getMode());
}
