

var Login = {

	init: function() {
		//this.initGifPropoerty();
		this.initNode();
		this.showNotice();
		this.initAnimation();
		this.addEvent();

	},

	initNode: function() {	// 初始化节点
		this.$account = $('#j-account');
		this.$pwd = $('#j-secret');
		this.$errorMsg = $('#j-errorMsg');
		this.$loginBtn = $('#j-loginBtn');
		this.$btnLogin = $('#btn_login');
		this.$btnClose = $('#btn_close');
		this.$footer = $('#footer');
		this.$logoutDialog = $('#j-logoutDialog');
		this.$cancelBtn = $('#j-cancelBtn');
		this.$okBtn = $('#j-okBtn');
		this.$closeDialog = $('#j-closeDialog');

		//if(require('electron').remote.getGlobal('isDebug') == true)
		//{
		//	this.$account.val("18626105941");
		//	console.log(this.$account.val("18626105941"));
		//	this.$pwd.val("123456");
		//}
		var that = this;
		var xntalkConfig = new Modal.XNTalkConfig();
		xntalkConfig.loadConfig(function()
		{
			//console.log("#####################xntalkConfig.hasRecentUser()" + xntalkConfig.hasRecentUser());
			that.$pwd.md5Val = "";
			that.$pwd.val("");
			if(xntalkConfig.hasRecentUser())
			{
				console.log(xntalkConfig.getRecentUser());
				that.$account.val(xntalkConfig.getRecentUser());
				var pwd = xntalkConfig.getRecentUserPassword();
				if(pwd != undefined && pwd != null && pwd.length > 0)
				{

					that.$pwd.md5Val = xntalkConfig.getRecentUserPassword();
					that.$pwd.val("md5pwd");
				}
			}

		});



	},

	showDialog: function () {
//		//var BrowserWindow = require('electron');
//	console.log(require('electron').remote);
//// Or in the renderer process.
//		const BrowserWindow = require('electron').remote.BrowserWindow;
//
//		win = new BrowserWindow({width: 800, height: 600});
//		win.on('closed', function(){
//			win = null;
//	});
//
//		win.loadURL('https://github.com');
//		win.show();
		this.$logoutDialog.removeClass('hide');
		//this.$mask.removeClass('hide');
	},
	initAnimation: function() {	// 添加动画
		var $wrapper = $('#j-wrapper'),
			wrapperClass = $wrapper.attr('class');
		$wrapper.addClass('fadeInDown animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
			$(this).removeClass().addClass(wrapperClass);
		});
	},
	hideDialog: function () {
		this.$logoutDialog.addClass('hide');
		//this.$mask.addClass('hide');
	},


	/**
	 * 如果浏览器非IE10,Chrome, FireFox, Safari, Opera的话，显示提示
	 */
	showNotice: function() {
		var browser = this.getBrowser(),
			temp = browser.split(' '),
			appname = temp[0],
			version = temp[1];
		if (['msie', 'firefox', 'opera', 'safari', 'chrome'].contains(appname)) {
			if (appname == 'msie' && version < 10) {
				this.$footer.find('p').removeClass('hide');
			}
		} else {
			this.$footer.find('p').removeClass('hide');
		}
	},

	addEvent: function() {	// 绑定事件
		var that = this;
		this.$pwd.on('input', function(){
			that.$pwd.md5Val = "";
		});
		this.$closeDialog.on('click', this.hideDialog.bind(this));
		this.$btnClose.on('click', function()
		{
			const dialog = require('electron').remote.dialog;
			var dialogOption = {
				type:'question',
				title:'退出',
				buttons:['确定', '取消'],
				defaultId:0,
				message:'确定要退出XNTALK吗？',
				detail:'',
				cancelId:1
			};

			dialog.showMessageBox(dialogOption,function(e){

				// e 是选择的目录
				if(e == 0)
				{
					require('electron').remote.app.quit();
				}
				console.log(e);
			});

		});
		//{
		//	//console.log(require('app'));
		//	require('electron').remote.app.quit();
		//});


		this.$btnLogin.on('click', this.validate.bind(this));
		$(document).on('keydown', function(e) {
			var ev = e || window.event;
			if (ev.keyCode === 13) {
				that.validate();
			}
		});
		this.$cancelBtn.on('click', this.hideDialog.bind(this));
		this.$okBtn.on('click', function(){
			require('electron').remote.app.quit();
		});
	},

	validate: function() {	// 登录验证

		var that = this,
			account = $.trim(that.$account.val()),
			pwd = that.$pwd.val(),
			errorMsg = '';
		pwd = MD5(pwd);
		if(that.$pwd.md5Val != undefined && that.$pwd.md5Val != null && that.$pwd.md5Val.length > 0)
		{
			//alert("that.$pwd.md5Val = xntalkConfig.getRecentUserPassword();");
			pwd = that.$pwd.md5Val;
		}
		if (account.length === 0) {
			errorMsg = '帐号不能为空';
			alert(errorMsg);
		}
		// else if (!pwd || pwd.length < 6) {
		//	errorMsg = '密码长度至少6位';
		//}
		else {
			//that.$btnLogin.html('登录中...').attr('disabled', 'disabled');
			var request = new LoginRequest();

			request.setAccount(account);
			request.setDeviceId('0');
			request.setDeviceType('PC')
			request.setPassword(pwd);
			request.setIp('127.0.0.1');

			xn_http_post(request, function(data){
				var xntalkConfig = new Modal.XNTalkConfig();
				xntalkConfig.loadConfig(function()
				{
					xntalkConfig.setRecentUser(account);
					if(data != "error" && data.union != null &&  data.union.id != null)
					{
						setCookie('xn_session',data.identity.id);//MD5
						xntalkConfig.setRecentUserPassword(pwd);
						xntalkConfig.saveConfig(function(err)
						{
							that.requestLogin.call(that, data.union.id, data.union.id);
						});
					}
					else if(data.errors != null)
					{
						xntalkConfig.setRecentUserPassword("");
						xntalkConfig.saveConfig(function(err)
						{
							that.$pwd.val("");
							that.$pwd.md5Val = "";
							console.log(data.errors);
							alert(data.errors[0].message);
						});

					}
					else {
						xntalkConfig.setRecentUserPassword("");
						xntalkConfig.saveConfig(function(err)
						{
							that.$pwd.val("");
							that.$pwd.md5Val = "";
							alert("登录错误");
						});

					}

				});


			});
			//that.$btnLogin.html('登录').removeAttr('disabled');
		}
		//that.$btnLogin.html(errorMsg).removeClass('hide');  // 显示错误信息
		return false;
	},
	//这里做了个伪登录方式（实际上是把accid，token带到下个页面连SDK在做鉴权）
	//一般应用服务器的应用会有自己的登录接口
	requestLogin: function(account, pwd) {

		setCookie('uid',account.toLocaleLowerCase());
		//自己的appkey就不用加密了
		// setCookie('sdktoken',pwd);
		setCookie('sdktoken',pwd);//MD5
		//alert(	window.location );
		//window.location.href = 'main.html';

		var electron = require('electron'); // 控制应用生命周期的模块。
		var BrowserWindow = electron.remote.BrowserWindow;  // 创建原生浏览器窗口的模块

		mainWindow = new BrowserWindow({frame: false, resizable: false,center:true, useContentSize:true, class:'Main',width:900, height: 600,minWidth:900, webPreferences:
		{webSecurity: false,allowDisplayingInsecureContent:true, allowRunningInsecureContent:true}});

		mainWindow.setMenuBarVisibility(false);

		if(require('electron').remote.getGlobal('isDebug') == true)
		{
			mainWindow.openDevTools();
		}
		mainWindow.class = 'Main';

		// 加载应用的 index.html
		console.log(__dirname);

		if(require('electron').remote.getGlobal('isDebug')  == true)
		{

			mainWindow.loadURL(("http://127.0.0.1:#port#/xntalk/main.html").replace("#port#", require('electron').remote.getGlobal('port')));
			mainWindow.setSize(800, 600);
		}
		else
		{

			mainWindow.loadURL(("http://127.0.0.1:#port#/xntalk/main.html").replace("#port#", require('electron').remote.getGlobal('port')));
		}


		//mainWindow.on('closed', function() {
		//	// 取消引用 window 对象，如果你的应用支持多窗口的话，
		//	// 通常会把多个 window 对象存放在一个数组里面，
		//	// 但这次不是。
		//	mainWindow = null;
        //
		//});
		window.close();
	},

	/**
	 * 获取浏览器的名称和版本号信息
	 */
	getBrowser: function() {
		var browser = {
			msie: false,
			firefox: false,
			opera: false,
			safari: false,
			chrome: false,
			netscape: false,
			appname: 'unknown',
			version: 0
		}, ua = window.navigator.userAgent.toLowerCase();
		if (/(msie|firefox|opera|chrome|netscape)\D+(\d[\d.]*)/.test(ua)) {
			browser[RegExp.$1] = true;
			browser.appname = RegExp.$1;
			browser.version = RegExp.$2;
		} else if (/version\D+(\d[\d.]*).*safari/.test(ua)){ // safari
			browser.safari = true;
			browser.appname = 'safari';
			browser.version = RegExp.$2;
		}
		return browser.appname + ' ' + browser.version;
	},
	//initGifPropoerty:function() {
	//	if ('getContext' in document.createElement('canvas')) {
    //
	//		HTMLImageElement.prototype.play = function() {
	//			if (this.storeCanvas) {
	//				// 移除存储的canvas
	//				this.storeCanvas.parentElement.removeChild(this.storeCanvas);
	//				this.storeCanvas = null;
	//				// 透明度还原
	//				image.style.opacity = '';
	//			}
	//			if (this.storeUrl) {
	//				this.src = this.storeUrl;
	//			}
	//		};
	//		HTMLImageElement.prototype.stop = function() {
	//			var canvas = document.createElement('canvas');
	//			// 尺寸
	//			var width = this.width, height = this.height;
	//			if (width & height) {
	//				// 存储之前的地址
	//				if (!this.storeUrl) {
	//					this.storeUrl = this.src;
	//				}
	//				// canvas大小
	//				canvas.width = width;
	//				canvas.height = height;
	//				// 绘制图片帧（第一帧）
	//				canvas.getContext('2d').drawImage(this, 0, 0, width, height);
	//				// 重置当前图片
	//				try {
	//					this.src = canvas.toDataURL("image/gif");
	//				} catch(e) {
	//					// 跨域
	//					this.removeAttribute('src');
	//					// 载入canvas元素
	//					canvas.style.position = 'absolute';
	//					// 前面插入图片
	//					this.parentElement.insertBefore(canvas, this);
	//					// 隐藏原图
	//					this.style.opacity = '0';
	//					// 存储canvas
	//					this.storeCanvas = canvas;
	//				}
	//			}
	//		};
	//	}
	//}
};
Login.init();

