//#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 newRoleId = params.roleId;
    var rorgId = params.rorgId;

    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 orgId = rorgId || session.orgId;
    if(!isRoleOpened(orgId)){
        session.roleId = '0';
        var ret = {
            state: 'ok'
        }
        out.print(JSON.stringify(ret));
        return;

    }
    else{
        var roles = getRoles(orgId,userId);
        if(isRoleOk(roles,newRoleId)){
            session.roleId = newRoleId;
            owl_backend_sessionService.update(session);
            var ret = {
                state: 'ok',
                rroleId:newRoleId,
                rorgId:orgId
                }
            out.print(JSON.stringify(ret));
            return;
        }
        else{
            var ret = {
                state: 'err',
                msg : '角色不存在:' + newRoleId
            }
            out.print(JSON.stringify(ret));
            return;
        }
    }
}
main();