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

function main() {
    var params = JSON.parse($body);
    var orgId = params.id;
    var isid = SessionService.getSessionId(request);
    var sessionId = 'owl_backend_session_' + isid;
    var session = owl_backend_sessionService.get(sessionId);

    var userId = session.userId;

    var roles = getRoles(orgId,userId);
    $.log("roles=" + JSON.stringify(roles));
    if(!roles || roles.length==0){
        var ret = {
            state:'err',
            msg:'没有权限'
        }
        out.print(JSON.stringify(ret));
        return;
    }
    var rroleId = params.rroleId;
    var newRoleId = null;
    if(isRoleOk(roles,rroleId)){
        newRoleId = rroleId;
    }
    if(!newRoleId){
        newRoleId = roles[0].id;
    }

    session.orgId = orgId;
    owl_backend_sessionService.update(session);
    var ret = {
        state: 'ok',
        action:'navigate',
        url:'/welcome?rorgId=' + orgId + "&rroleId=" + newRoleId,
        target:'_blank'
    }
    out.print(JSON.stringify(ret));
    return;

}
main();