//#import session.js
//#import $owl_permission:services/modelService.jsx
//#import $owlPermission:services/RolesService.jsx
//#import $owl_server_token:services/modelService.jsx
//#import $owl_backend_session:services/modelService.jsx
function getPermissions(roleId){
    var searchArgs = {
        roleId: roleId
    }
    var sr = owl_permissionService.search("0",searchArgs,null,0,10000,null);
    // $.log("getPermissions,roleId=" + roleId + ",tableId=" + tableId);
    if(sr.state==='ok'){
        // $.log("getPermissions,roleId=" + roleId + ",tableId=" + tableId + ", length=" + sr.list.length);
        return sr.list;
    }
    return [];

}

function _checkPluginPermission(pluginId, permission) {
    var allowed = true;
    if (permission.plugin_default_mode === 'reject') {
        allowed = false;
    }

    var exception_plugins = permission.exception_plugins;
    if (exception_plugins) {
        var exception_plugin = exception_plugins.find(function(exception_plugin) {return exception_plugin.pluginId === pluginId;});
        if (exception_plugin) {
            allowed = !allowed;
        }

    }
    return allowed;
}

function checkPluginPermission(pluginId, permissions) {
    if (!permissions || permissions.length === 0) {
        return true;
    }
    for (var i = 0; i < permissions.length; i++) {
        var permission = permissions[i];

        if (_checkPluginPermission(pluginId, permission)) {
            return true;
        }
    }
    return false;
}

function checkPluginPermissionByRoleId(pluginId, roleId) {
    var permissions = getPermissions(roleId);
    return checkPluginPermission(pluginId, permissions);
}

function checkUserHasRole(userId, roleId,orgId){
   // 检查用户时候拥有某个角色
    var roles = getRoles(orgId,userId);
    if(isRoleOk(roles,roleId)){
        return true;
    }
    return false;
}

function checklogin() {
    var magic = $.getSystemProperty("magic");
    var magicParams = $.params.ma;
    var m = '0';//默认是 平台
    if (magic === magicParams) {
        //代表是内部操作
        var user = {
            uid: 'internal',
            loginId: "internal",
            name: "系统内部访问",
            allowed_appIds: ["*"]
        }

        var env = {
            now: new Date().getTime(),
            loginUserId: 'internal',
            loginId: 'internal',
            // loginUser:user,
            shopId: m,
            warehouseId: "",
            roleId: 'internal',
            orgId: 'internal',
            orgIds: 'internal',
            m: m
        }
        return env;

    } else {
        var params = JSON.parse($body);
        var token = params._req_token
        if(token){
            var token_user = getUserByToken(token);
            if(token_user){
                var env = {
                    now: new Date().getTime(),
                    loginUserId: token_user.id,
                    loginId: token_user.id,
                    // loginUser:loginUser,
                    shopId: m,
                    warehouseId: "",
                    roleId:  params.rroleId,
                    orgId: params.rorgId,
                    orgIds: null,
                    m: m
                }
                return env;
            }
            else{
                var ret = {
                    state: 'err',
                    code: 'not valid token',
                    msg: "not valid token"
                }
                out.print(JSON.stringify(ret));
                return null;
            }
        }
        var isid = SessionService.getSessionId(request);
        var now = new Date().getTime();
        var sessionId = 'owl_backend_session_' + isid;
        var session = owl_backend_sessionService.get(sessionId);
        if (session && session.lastModified > now - 7 * 24 * 3600 * 1000) {
            var loginUserId = session.userId
            var roleId = params.rroleId || session.roleId;
            var orgId = params.rorgId || session.orgId;
            var orgIds = [orgId].concat(getParentOrgIds(orgId));
            if (loginUserId) {
                // var loginUser = owl_mall_uService.get(loginUserId);
                var env = {
                    now: new Date().getTime(),
                    loginUserId: loginUserId,
                    loginId: loginUserId,
                    // loginUser:loginUser,
                    shopId: m,
                    warehouseId: "",
                    roleId: roleId,
                    orgId: orgId,
                    orgIds: orgIds,
                    m: m
                }
                return env;
            } else {
                var ret = {
                    state: 'err',
                    code: 'no login',
                    msg: "not login!"
                }
                out.print(JSON.stringify(ret));
                return null;
            }
        } else {
            var ret = {
                state: 'err',
                code: 'no login',
                msg: "not login!"
            }
            out.print(JSON.stringify(ret));
            return null;
        }
    }
}

function checkBackendPluginPermission(pluginId){
    var env = checklogin();
    var roleId = env.roleId
    var orgId = env.orgId;
    var loginUserId = env.loginUserId;

    if(!checkUserHasRole(loginUserId, roleId, orgId)){
        throw "用户角色异常";
    }

    if(!checkPluginPermissionByRoleId( pluginId,roleId)){
        throw "没有权限执行此操作";
    }
}
