//#import Util.js
//#import $owlPasswordService:services/consts.jsx
//#import user.js
//#import login.js
//#import session.js
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_backend_session:services/modelService.jsx
//#import $owl_orgs:services/modelService.jsx
//#import $owl_roles:services/modelService.jsx
//#import DigestUtil.js
//#import $owl_org_admin_groups:services/modelService.jsx
//#import $owl_platform_admin_groups:services/modelService.jsx
//#import $owlPermission:services/RolesService.jsx
//#import $commonService:services/BackendSessionUtil.jsx
//#import $owl_user_login_log:services/modelService.jsx
//#import $owl_user_login_error_log:services/modelService.jsx
//#import $owl_api_limit_setting:services/modelService.jsx


;(function () {
    var body = $body;
    var params = JSON.parse(body);
    var loginId = params.userName;
    var password = params.password;
    // $.log("loginId=" + loginId + ",password=" + password);
    // var role = params.role;
    // var orgId = params.organization;

    if (!loginId || !password) {
        out.print(JSON.stringify({state: "err", msg: "参数错误"}));
        return;
    }

    var ip = $.getClientIp() + "";
    var ua = request.getHeader("user-agent") + "";
    var limitCount = getLoginLogs(ip);
    var jLimitArgs = getLimitCountArgs();
    if (limitCount >= jLimitArgs.ip_login_minute_count_60) {
        out.print(JSON.stringify({state: "err", msg: "请求超过限制，请稍后再试"}));
        return;
    }

    var error_code = "";
    var error_msg = "";
    var state = "0";
    var admin = null;
    var stockuser = null;
    try {
        for (var i = 0; i < stockusers.length; i++) {
            var su = stockusers[i];
            if (su.loginId === loginId && su.password === password) {
                stockuser = su;
                // $.log("found stockuser=" + JSON.stringify(stockuser));
                break;
            }
        }
        if (!stockuser) {
            // $.log("no stockuser found, loginId=" + loginId + ",password=" + password);
        }

        var isid = null;
        if (typeof _isid === 'undefined') {
            //通过cookie获得isid
            isid = SessionService.getSessionId(request);
        } else {
            isid = _isid;
        }

        var now = new Date().getTime();
        var sessionId = 'owl_backend_session_' + isid;
        var success = false;

        if (stockuser) {
            var times = 0;
            var roles = [];

            $.log("owlShell...login...stockuser.uid=" + stockuser.uid);
            roles = getRoles('0', stockuser.uid);
            if (!roles || roles.length === 0) {
                $.log("owlShell...login...本单位已经启动了角色功能，用户需要属于某个角色才能登录");
                out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
                return;
            }
            while (times < 5) {
                try {
                    times += 1;
                    var session = owl_backend_sessionService.get(sessionId);
                    $.log("owlShell...login...11111--sessionId=" + sessionId);
                    var isnew = false;
                    if (!session) {
                        session = {
                            createTime: now,
                            sessionObjs: {}
                        };
                        isnew = true;
                    }
                    var sessionObjs = session.sessionObjs;
                    if (!sessionObjs) {
                        sessionObjs = {};
                        session.sessionObjs = sessionObjs;
                    } else {
                        if (typeof sessionObjs == 'string') {
                            sessionObjs = JSON.parse(sessionObjs);
                        }
                    }
                    if (!isRoleOk(roles, session.roleId)) {
                        if (roles.length > 0) {
                            session.roleId = roles[0].id;
                        } else {
                            session.roleId = null;
                        }
                    }
                    if (stockuser.uid == '0') {
                        session.roles = [{id: '0', name: "管理员"}];
                        session.loginRoles = [{id: '0', name: "管理员"}];
                        session.roleId = '0';
                    }
                    $.log("2222----stockuser.uid=" + stockuser.uid + ",session.roleId=" + session.roleId + ",isNew=" + isnew);
                    sessionObjs.loginUser = stockuser;
                    sessionObjs.loginInfo = {userId: stockuser.uid};
                    session.sessionObjs = JSON.stringify(sessionObjs);
                    session.lastModified = now;
                    session.loginTime = now;
                    session.isid = isid;
                    session.isLogin = 'y';
                    session.userId = stockuser.uid;
                    session.userName = stockuser.name;
                    session.orgId = '0';
                    session.orgIds = ['0'];
                    session.orgs = [{id: '0', name: '平台'}]
                    session.roles = roles;
                    session.loginRoles = roles;
                    if (isnew) {
                        owl_backend_sessionService.add(session);
                    } else {
                        owl_backend_sessionService.update(session);
                    }
                    success = true;
                    break;
                } catch (e) {
                    $.log("owlShell...login...error=" + e.toString());
                }
            }

            $.log("owlShell...login...33333333333333---------login success=" + success);
            if (success) {
                state = "1";
                $.log("owlShell...login...successed...uid=" + stockuser.uid);

                delete stockuser.password;
                var ret = {
                    state: "ok",
                    name: stockuser.name,
                    stockuser: JSON.stringify(stockuser),
                    isid: isid
                };
                // $.log("4444444---------login ret=" + JSON.stringify(ret));
                out.print(JSON.stringify(ret));
            } else {
                out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
            }

        } else {
            //不是stockUser用户
            admin = owl_mall_uService.getUniqueObj('mobile', loginId);
            if (!admin) {
                admin = owl_mall_uService.getUniqueObj('loginId', loginId);
            }
            if (!admin) {
                error_code = "111";
                error_msg = "账号不存在";
                out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
            } else {
                if (admin.isEnable != "1") {
                    error_code = "112";
                    error_msg = "账号未激活";
                    // $.log("owlShell...login...555555---------login code=8");
                    out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
                    return;
                }
                var passwordHash;
                if (admin.pwdV == "v1") {
                    passwordHash = DigestUtil.digestString(password + admin.random, "SHA");
                } else {
                    passwordHash = DigestUtil.sha1(password + admin.random);
                }
                if (admin.disabled_temporary === 'true') {
                    if (admin.disabled_temporary_time && now - admin.disabled_temporary_time < 30 * 60 * 1000) {
                        $.log("owlShell...login...---------login code=9...账号已被锁定30分钟...id=" + admin.id);
                        error_code = "113";
                        error_msg = "账号已被锁定30分钟";
                        out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
                        return;
                    }
                }
                var admin_passwordhash = admin.passwordhash;
                delete admin.passwordhash;
                delete admin.random;
                if (passwordHash === admin_passwordhash) {
                    //密码正确
                    if (admin.disabled_temporary === 'true' || admin.passwrongtimes > 0) {
                        admin = owl_mall_uService.get(admin.id);
                        admin.disabled_temporary = 'false';
                        admin.passwrongtimes = 0;
                        owl_mall_uService.update(admin);
                    }
                    //判断组织结构权限
                    var orgs = getOrgsOfUser(admin.id);
                    var foundOrg = null;
                    if (orgs.length) {
                        foundOrg = orgs[0];
                    }
                    if (!foundOrg) {
                        // $.log("555555---------login code=11");
                        error_code = "114";
                        error_msg = "没有权限";
                        out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
                        return;
                    }
                    var times = 0;
                    while (times < 5) {
                        times += 1;
                        var session = owl_backend_sessionService.get(sessionId);
                        // $.log("sessionId=" + sessionId);
                        var isnew = false;
                        if (!session) {
                            session = {
                                createTime: now,
                                sessionObjs: {}
                            };
                            isnew = true;
                        }
                        var sessionObjs = session.sessionObjs;
                        if (!sessionObjs) {
                            sessionObjs = {};
                        } else {
                            if (typeof sessionObjs == 'string') {
                                sessionObjs = JSON.parse(sessionObjs);
                            }

                        }

                        sessionObjs.loginUser = admin;
                        sessionObjs.loginInfo = {userId: admin.id};
                        session.sessionObjs = JSON.stringify(sessionObjs);
                        session.lastModified = now;
                        session.loginTime = now;
                        session.isLogin = 'y';
                        session.userId = admin.id;
                        session.userName = admin.name;
                        // session.role = role;
                        if (!session.orgId) {
                            session.orgId = foundOrg.id;
                            session.loginOrgId = foundOrg.id;
                        } else {
                            //检查session.orgId是否在orgs里面
                            var isok = false;
                            for (var i = 0; i < orgs.length; i++) {
                                var org = orgs[i];
                                if (org.id === session.orgId) {
                                    foundOrg = org;
                                    isok = true;
                                    break;
                                }
                            }
                            //如果你已经不在以前登录的orgId里面，则退出以前的orgID，加入新的orgId
                            if (!isok) {
                                session.orgId = foundOrg.id;
                                session.loginOrgId = foundOrg.id;

                            }
                        }
                        session.orgIds = orgs.map(function (org) {
                            return org.id;
                        });
                        session.orgs = orgs;
                        session.isid = isid;
                        session.ip = ip;
                        //现在找到用户的role
                        // var curOrgId = session.orgId;
                        // $.log("login.jsx, curOrgId=" + curOrgId + ",admin.id="+admin.id + ",myOrgs=" + JSON.stringify(orgs));

                        if (isRoleOpened(session.orgId)) {
                            roles = getRoles(session.orgId, admin.id);
                            if (!roles || roles.length === 0) {
                                // $.log("login...已经启动了角色功能，用户需要属于某个角色才能登录,uid=" + admin.id);
                                error_code = "115";
                                error_msg = "没有权限";
                                out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
                                return;
                            }
                            if (!isRoleOk(roles, session.roleId)) {
                                session.roleId = null;
                                if (roles.length > 0) {
                                    session.roleId = roles[0].id;
                                }
                            }
                            session.roles = roles;
                            session.loginRoles = roles;
                        } else {
                            session.roles = [{id: '0', name: "管理员"}];
                            session.loginRoles = [{id: '0', name: "管理员"}];
                            session.roleId = '0';
                        }

                        if (isnew) {
                            owl_backend_sessionService.add(session);
                        } else {
                            owl_backend_sessionService.update(session);
                        }
                        success = true;
                        break;
                    }
                    // $.log("login success!");
                    if (success) {
                        state = "1";
                        var ret = {
                            state: 'ok',
                            msg: '登录成功',
                            name: admin.name,
                            isid: isid,
                        }
                        out.print(JSON.stringify(ret));
                    } else {
                        // $.log("login...服务器太忙，请稍后再试试,uid=" + admin.id);
                        error_code = "116";
                        error_msg = "登录失败";
                        out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
                    }

                } else {
                    //密码错误，需要记录错误次数
                    admin = owl_mall_uService.get(admin.id);
                    admin.passwrongtimes = admin.passwrongtimes || 0;
                    admin.lastwrongtimestamp = new Date().getTime();
                    admin.passwrongtimes = Number(admin.passwrongtimes) + 1;
                    if (admin.passwrongtimes >= 5) {
                        admin.disabled_temporary = 'true'
                        admin.disabled_temporary_time = new Date().getTime();

                        out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
                        return;
                    }
                    owl_mall_uService.update(admin);

                    // $.log("login...密码错误,uid=" + admin.id);
                    error_code = "119";
                    error_msg = "密码错误";
                    out.print(JSON.stringify({state: "err", msg: "抱歉，账号或凭证无效，请联系客服"}));
                }

            }
        }
    } catch (e) {
        $.log("owlShell...login.jsx...e=" + e + "...loginId=" + loginId);
        error_code = "99";
        error_msg = "操作出现异常=" + e;
        out.print(JSON.stringify({state: "err", msg: "操作出现异常，请稍后再试"}));
    } finally {
        if(!stockuser) {
            var jLog = {};
            jLog.api = "shell/login";
            jLog.lid = loginId;
            jLog.uid = admin && admin.id;
            jLog.state = state;
            jLog.ip = ip;
            jLog.ua = ua;
            jLog.code = error_code;
            jLog.msg = error_msg;
            if (state == "0") {
                owl_user_login_error_logService.add(jLog);
            } else {
                owl_user_login_logService.add(jLog);
            }
        }
    }
})();

function getLoginLogs(ip) {
    var curTime = new Date().getTime();
    var searchArgs = {};
    searchArgs.ip = ip;
    searchArgs.owl_createTime = [curTime - 1000 * 60 * 60, curTime];

    return owl_user_login_error_logService.count(null, searchArgs, null);
}


function getLimitCountArgs() {
    var result = {
        ip_login_minute_count_60: 50
    };
    var jArgs = owl_api_limit_settingService.get("owl_api_limit_setting_0");
    if (jArgs) {
        if (jArgs.ip_login_minute_count_60) {
            result.ip_login_minute_count_60 = jArgs.ip_login_minute_count_60;
        }
    }
    return result;
}