define(function(require, exports, module) {
    var global = require("./global");
    var gui = window.require('nw.gui');
    var upgradeMgr = window.require("../../common/js/upgradeMgr");

    var _host = global.jsUtil.getPkgInfo().spec.info.cloudUrl.replace('/cloud', '');
    var urgent = null; // 判断是否有必须更新的新版本

	initTool();
	function initTool() {
        setToolTray();	//引用commonlib.js
        
        try {
            console.log('in login, userName::', global.userMgrIns.curUserName);
        } catch (e) {
            console.error('in initTool, error:', e);
        }
		initStatRecord(global.userMgrIns);
//		initUpgrade();
	}
	
	function init() {
        initPageStatistic();

        global.remoteAssistant.init(global.userMgrIns);
        global.userMgrIns.checkNetwork(function (success) {
            if (global.jsUtil.getPkgInfo().needAccount == false) {
                initDom(false);
            } else {
                initDom(success);
            }
            
            initEvent();
            initGlobalEvent();
        });
		
		function initPageStatistic() {
            statRecordEle("login");

            $('#offlineLoginDiv').hide();
		}
		function initDom(success) {
            $('#newVersionModal').modal({
                backdrop: 'static',
                show: false,
                keyboard: false
            });

            var userInfo = global.userMgrIns.getRealUser();
            if (userInfo.isOA) {
                $("#username").val('');
                $("#password").val('');
            } else {
                $("#username").val(userInfo.userName);
                $("#password").val(userInfo.password);
            }
            
            if (!success) {
                $('#offlineLoginDiv').show();

            } else {
                $('#normalLoginDiv').show();
            }

            // iframe的默认链接也要跟着动的
            $('#iframe_id').attr('src', 'https://auth.ruijie.com.cn/login?url=' + _host + '/cloudWeb/login/toolLogin&sysid=rgds');
        }

        function _doNormalLogin() {
            var username = $("#username").val().trim();
            var password = $("#password").val().trim();
            $("#doLogin").modal('show');
            global.userMgrIns.verifyNormal(username, password, function (err, msg, results) {
                if (err == 0) {
                    var curElement = "#mainPage", nextPageUrl = "./menu.html";
                    global.enterPageCallback(curElement, nextPageUrl);
                } else {
                    $("#password").val('');
                    alert(undefined, msg);
                }
                $("#doLogin").modal('hide');
            });
        }

        function _doMaccLogin() {
            var username = $("#username").val().trim();
            var password = $("#password").val().trim();
            $("#doLogin").modal('show');
            global.userMgrIns.verifyMacc(username, password, function (err, user) {
                if (err == null) {
                    var curElement = "#mainPage", nextPageUrl = "./menu.html";
                    global.enterPageCallback(curElement, nextPageUrl);
                } else {
                    $("#password").val('');
                    console.error('err:', err);
                    alert(undefined, err.toString());
                }
                $("#doLogin").modal('hide');
            });
        }

		function initEvent() {			
            $("#logInBtn").click(function (e) {
                // _doNormalLogin();
                _doMaccLogin();

                // var curElement = "#mainPage", nextPageUrl = "./menu.html";
                // global.enterPageCallback(curElement, nextPageUrl);
            });

            $("#password").keydown(function (e) {
                // 输入回车
                if (e.which == 13) {
                    // _doNormalLogin();
                    _doMaccLogin();

                    // var curElement = "#mainPage", nextPageUrl = "./menu.html";
                    // global.enterPageCallback(curElement, nextPageUrl);
                }
            });

            $('#offlineLogInBtn').click(function (e) {
                if (!urgent) {
                    var curElement = "#mainPage", nextPageUrl = "./menu.html";
                    global.enterPageCallback(curElement, nextPageUrl);
                } else {
                    alert(undefined, "当前版本太旧，请下载最新版本使用！", function () {
                        gui.Shell.openExternal($("#downloadNewVersion").attr('data-link'));
                    });
                }
            });

            $("#loadExeModal").modal('hide');
            // 检测是否有新版本
            upgradeMgr.getInfo(function (err, res) {
                urgent = null;
                if (err != null || res == undefined || res.version == undefined || res.version.versionName == undefined || res.version.downloadUrl == undefined) {
                    return;
                }

                $("#versionName").text(res.version.versionName);
                $("#downloadNewVersion").attr('data-link', res.version.downloadUrl);

                if (Array.isArray(res.version.change_log)) {
                    var item = '';
                    for (var i = 0; i < res.version.change_log.length; i++) {
                        item += '<div>' + res.version.change_log[i] + '</div>';
                    }
                    $("#changeLog").html(item);
                }

                if (res.urgent == true) {
                    $("#urgentDesc").text(res.urgentDesc);
                }
                
                
                

                setTimeout(function () {
                    $("#newVersionModal").modal('show');
                }, 300);
            });

            $("#downloadNewVersion").click(function () {
                var link = $(this).attr('data-link');
                if (link) {
                    gui.Shell.openExternal(link);
                }
            });
		}
		function initGlobalEvent() {
			global.exitPageCallback.exitFun = function () {
				return true;
			}
        }

        $('#register').click(function () {
            var gui = window.require('nw.gui');
            gui.Shell.openExternal("http://macc1.ruijie.com.cn");
        });

        $('#oa').click(function () {
            var timeId = 0;
            var success = false;
            // 登陆不上的问题
            var systemFail = false;
			
            // XXX 先硬编码吧
            console.log('host:', _host);
            var userInfo = global.userMgrIns.getRealUser();
            var oaUrl = 'https://auth.ruijie.com.cn/login?url=' + _host + '/cloudWeb/login/toolLogin&sysid=rgds';
            if (userInfo.isOA) {
                oaUrl += '&username=' + userInfo.userName;
            }
            var winOA = $("#iframe_id").attr("src");
            console.log('OA url:', oaUrl);
            $('#myModal').on('hidden.bs.modal', function () {
                if (success == true) {
                    var curElement = "#mainPage", nextPageUrl = "./menu.html";
                    global.enterPageCallback(curElement, nextPageUrl);
                } else {
                    if (systemFail) {
                        alert(undefined, 'OA登录失败,可能原因:1. 您在30秒内未输入用户名密码,或者输入后未点击登录按钮,请再试一次. 2. 公司的OA服务器正在维护中,如果重试后仍无法解决问题，请暂时选用普通用户方式登录系统');
                        // 使用完了需要重置
                        systemFail = false;
                    }
                }

            });
            var tryCnt = 0;
            timeId = setInterval(function () {
//               var verifyUrl = winOA.window.location.href;
				 //var verifyUrl = $("#iframe_id").attr("src");
                try {
                    tryCnt++;
                    var verifyUrl = parent.document.getElementById("iframe_id").contentWindow.location.href;
                    console.log('verifyUrl:', verifyUrl);
                    //               console.log(winOA.window.location.href);
                    // XXX 这里有发现由于OA系统出问题，导致可以访问OA系统页面，但迟迟无法登陆
                    if (verifyUrl.indexOf('username=') != -1 && verifyUrl.indexOf('auth.ruijie.com.cn') == -1) {
                        // xxxxhtml?sessionId=uuuuuu&username=kkkkk
                        var results = verifyUrl.split('username=');
                        var userName = results[1].trim().split('&')[0].trim();

                        results = verifyUrl.match(/sessionId=(.+)&username/);
                        // XXX 与云端协商，sessionId要在此时写入才是准确的
                        if (results != null && Array.isArray(results) && results.length >= 2) {
                            var sessionId = results[1].trim();
                            global.userMgrIns.setSessionId(sessionId);
                        }

                        // XXX 为了解决由于loadOAUser返回太慢，导致被触发两次的问题
                        if (timeId != 0) {
                            clearInterval(timeId);
                            timeId = 0;
                        }
                        console.log('clear interval and begin to load OA: userName=', userName);
                        global.userMgrIns.loadOAUser(userName, function (err, msg, results) {
                            console.log(err);
                            if (err == 0) {
                                success = true;
                                $('#myModal').modal('hide');
                                console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                                //winOA.close(false);


                            } else {
                                $('#myModal').modal('hide');
                                console.log("......................................");
                                //winOA.close(false);
                                alert(undefined, '网络问题导致登录失败,请稍后再试,错误码:' + msg);
                            }
                        });

                    } else {
                        // XXX 迟迟无法登陆的问题，在这里处理
                        if (tryCnt >= 10) {
                            // 说明出问题了
                            // success = false
                            systemFail = true;
                            if (timeId != 0) {
                                clearInterval(timeId);
                                timeId = 0;
                            }
                            $('#myModal').modal('hide');
                        }
                    }
                } catch (e) {
                    console.error('in login OA, error:', e);
                    systemFail = true;
                    if (timeId != 0) {
                        clearInterval(timeId);
                        timeId = 0;
                    }
                    $('#myModal').modal('hide');
                }

            }, 3000);

        });
	}
	exports.init = init;
});