//#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 $owlPermission:services/RolesService.jsx

function main(){
    var params = JSON.parse($body);
    var newOrgId = params.orgId;
    var rroleId = params.rroleId;
    var roleId = null;

    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 session = owl_backend_sessionService.get(sessionId);
    var userId = session.userId;
    var orgs = getOrgsOfUser(userId);
    //检查newOrgId是否在orgs里面
    var found = false;
    if(!orgs){
        var ret = {
            state: 'err',
            msg:"没有权限",
            orgs:orgs

        }
        out.print(JSON.stringify(ret));
        return;
    }
    for(var i=0; i<orgs.length; i++){
        var org = orgs[i];
        if(org.id===newOrgId){
            found = true;
        }
    }
    if(!found){
        var ret = {
            state: 'err',
            msg:"没有权限",
            orgs:orgs

        }
        out.print(JSON.stringify(ret));
        return;
    }
    session.orgId = newOrgId;
    session.orgIds = orgs.map(function(o){
        return o.id;
    });

    // session.roleId = null;
    if(isRoleOpened(newOrgId)){
        var roles = getRoles(newOrgId,userId);
        if(!roles || roles.length===0){
            var ret = {
                state: 'err',
                msg:"单位已经启用角色管理，你没有属于任何角色。"
            }
            out.print(JSON.stringify(ret));
            return;
        }
        session.roles = roles;
        if(isRoleOk(roles,rroleId)){
            //如果roleOk, 则保留原来的role
            roleId = rroleId;

        }
        else{
            var role = roles[0];
            roleId = role.id;
        }

    }
    owl_backend_sessionService.update(session);
    var ret = {
        state: 'ok',
        rroleId:roleId,
        rorgId:newOrgId
    }
    out.print(JSON.stringify(ret));
    return;
}

main();