//#import session.js
//#import $owl_backend_session:services/modelService.jsx
//#import $owlPermission:services/permissionService.jsx
//#import $owl_orgs:services/modelService.jsx
//#import $owl_permission:services/modelService.jsx
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_server_token:services/modelService.jsx

function getParentOrgIds(orgId) {
    if (orgId == '0') {
        return ['0'];
    }

    var org = owl_orgsService.get(orgId);
    if (org) {
        return org.parentPathIds;
    }
    return [orgId];
}

function getUserByToken(token){
    if(!owl_server_tokenService){
       return null;
    }
    var server_token = owl_server_tokenService.getUniqueObj("token",token);
    if(!server_token){
        return null;
    }
    var user_id = server_token.user_id;
    if(user_id=='0'){
        return {id:'0'}
    }
    var user = owl_mall_uService.get(user_id);
    return {user:user,server_token:server_token};
}
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_detail = getUserByToken(token);
            var token_user = token_detail.user;
            var server_token = token_detail.server_token;
            if(token_user && server_token){
                var env = {
                    now: new Date().getTime(),
                    loginUserId: token_user.id,
                    loginId: token_user.id,
                    // loginUser:loginUser,
                    shopId: m,
                    warehouseId: "",
                    roleId:  server_token.role_id,
                    orgId: server_token.org_id,
                    orgIds: getParentOrgIds(server_token.org_id),
                    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 getPermissions(roleId, tableId) {
    var searchArgs = {
        roleId: roleId,
        tables:{
            type:"or",
            args:[
                { "tables.tableId": tableId},
                { "tables.tableId": "all"}
            ]
       }
   }
   var sr = owl_permissionService.search("0", searchArgs, null, 0, 10000, null);
   if (sr.state === 'ok') {
        return sr.list;
   }
   return [];
}

function expandTablePermission(permissions) {
    // $.log("expandTablePermission,permissions=" + JSON.stringify(per？missions))
    var same_org = {};

    var sub_org = { };

    for (var i = 0; i < permissions.length; i++) {
        var p = permissions[i];
        if(same_org.read!='denied'  && p.permission_same_org && p.permission_same_org.read && p.permission_same_org.read!='noset'){
            same_org.read = p.permission_same_org.read;
        }
        if(same_org.update!='denied' && p.permission_same_org && p.permission_same_org.update  && p.permission_same_org.update!='noset'){
            same_org.update = p.permission_same_org.update;
        }
        if(same_org.del!='denied' && p.permission_same_org && p.permission_same_org.del && p.permission_same_org.del!='noset'){
            same_org.del = p.permission_same_org.del;
        }
        if(same_org.add!='denied' && p.permission_same_org && p.permission_same_org.add  && p.permission_same_org.add!='noset'){
            same_org.add = p.permission_same_org.add;
        }
        if(same_org.list!='denied' && p.permission_same_org && p.permission_same_org.list && p.permission_same_org.list!='noset'){
            same_org.list = p.permission_same_org.add;
        }
        if(same_org.listall!='denied' && p.permission_same_org && p.permission_same_org.listall && p.permission_same_org.listall!='noset'){
            same_org.listall = p.permission_same_org.listall;
        }

        if(sub_org.read!='denied' && p.permission_sub_org && p.permission_sub_org.read && p.permission_sub_org.read!='noset'){
            sub_org.read = p.permission_sub_org.read;
        }
        if(sub_org.update!='denied' && p.permission_sub_org && p.permission_sub_org.update && p.permission_sub_org.update!='noset'){
            sub_org.update = p.permission_sub_org.update;
        }
        if(sub_org.del!='denied' && p.permission_sub_org && p.permission_sub_org.del && p.permission_sub_org.del!='noset'){
            sub_org.del = p.permission_sub_org.del;
        }
        if(sub_org.add!='denied' && p.permission_sub_org && p.permission_sub_org.add && p.permission_sub_org.add!='noset'){
            sub_org.add = p.permission_sub_org.add;
        }
        if(sub_org.list!='denied' && p.permission_sub_org && p.permission_sub_org.list && p.permission_sub_org.list!='noset'){
            sub_org.list = p.permission_sub_org.list;
        }
        if(sub_org.listall!='denied' && p.permission_sub_org && p.permission_sub_org.listall && p.permission_sub_org.listall!='noset'){
            sub_org.listall = p.permission_sub_org.listall;
        }
    }

    return {
        same_org:same_org,
        sub_org:sub_org
    }

}

function expandSectionPermission(permissions) {
    var same_org = {
        "*": "allowed"
    };
    var sub_org = {
        "*": "allowed"
    };

    for (var i = 0; i < permissions.length; i++) {
        var p = permissions[i];
        var sections_same_org = p.sections_same_org;
        var sections_sub_org = p.sections_sub_org;
        if (sections_same_org) {
            for (var j = 0; j < sections_same_org.length; j++) {
                var sec = sections_same_org[j];
                if (sec.sectionKey) {
                    same_org[sec.sectionKey] = sec;
                }
            }
        }
        if (sections_sub_org) {
            for (var j = 0; j < sections_sub_org.length; j++) {
                var sec = sections_sub_org[j];
                if (sec.sectionKey) {
                    sub_org[sec.sectionKey] = sec;
                }
            }
        }
    }

    return {
        same_org: same_org,
        sub_org: sub_org
    }
}

function expandFieldPermission(permissions) {
    var same_org = {
        "*": {read: "allowed"}
    }
    var sub_org = {
        "*": {read: "allowed"}
    }
    for (var i = 0; i < permissions.length; i++) {
        var p = permissions[i];
        if (p.fields_same_org) {
            for (var j = 0; j < p.fields_same_org.length; j++) {
                var f = p.fields_same_org[j];
                var fieldKey = f.fieldKey;
                if (f.sectionKey && f.sectionKey != 'main') {
                    fieldKey = f.sectionKey + "." + f.fieldKey;
                }
                same_org[fieldKey] = f;
            }
        }
        if (p.fields_sub_org) {
            for (var j = 0; j < p.fields_sub_org.length; j++) {
                var f = p.fields_sub_org[j];
                var fieldKey = f.fieldKey;
                if (f.sectionKey && f.sectionKey != 'main') {
                    fieldKey = f.sectionKey + "." + f.fieldKey;
                }
                sub_org[fieldKey] = f;
            }
        }
    }
    return {
        same_org: same_org,
        sub_org: sub_org
    }
}

function checkObject(obj, ef_field_permissions, parentKey,action){
    for(var k in obj){
        var ek = parentKey + "." + k;
        if(ef_field_permissions && ef_field_permissions[ek] && ef_field_permissions[ek][action]==='denied'){
            throw "没有"+action + "权限，ek=" + ek;
        }

    }
}

function isSubOrg(data, orgId){
    if(orgId == '0'){
        return true;
    }
    var _orgId = data._orgId;
    if(data._t == "owl_orgs" ){
        _orgId = data.id;
    }
    var org = owl_orgsService.get(_orgId);
    if(!org || !org.parentPathIds){
        return false;
    }
    if(org.parentPathIds.indexOf(orgId)>-1){
        return true;
    }
    return false;
}

function checkPermission(data, permissions, orgId, action) {
    var section_permissions = expandSectionPermission(permissions);
    var field_permissions = expandFieldPermission(permissions);
    var table_permissions = expandTablePermission(permissions);

    var ef_section_permissions = null;
    var ef_field_permissions = null;
    var ef_table_permissions = null;
    if(data){
        if (data._orgId === orgId) {
            ef_section_permissions = section_permissions.same_org;
            ef_field_permissions = field_permissions.same_org;
            ef_table_permissions = table_permissions.same_org;
        } else {
            if(isSubOrg(data,orgId)) {
                ef_section_permissions = section_permissions.sub_org;
                ef_field_permissions = field_permissions.sub_org;
                ef_table_permissions = table_permissions.sub_org;
            }
        }
    }
    else{
        ef_section_permissions = section_permissions.same_org;
        ef_field_permissions = field_permissions.same_org;
        ef_table_permissions = table_permissions.same_org;
    }

    if(!ef_table_permissions){
        throw "表没有权限。"
    }
    var valid_fields = ['_orgId', '_orgIds', "_v", "del"];
    if(ef_table_permissions.add !== 'allowed' && action==='add'){
        throw "表没有添加记录权限。"
    }
    if(ef_table_permissions.del !== 'allowed' && action==='del'){
        throw "表没有删除记录权限。"
    }
    if(ef_table_permissions.update !== 'allowed' && action==='update'){
        throw "表没有删除记录权限。"
    }
    if(ef_table_permissions.read !== 'allowed' && action==='read'){
        throw "表没有读取权限。"
    }
    if(ef_table_permissions.list !== 'allowed' && action==='list'){
        throw "表没有列出权限。"
    }
    if(ef_table_permissions.listall !== 'allowed' && action==='listall'){
        throw "表没有列出权限。"
    }
    //检查section_permission
    if(data){
        for (var k in data) {
            if(valid_fields.indexOf(k)>-1){
                continue;
            }
            var v = data[k];
            //if v is section
            if (typeof v === 'object') {
                //ef_field_permissions
                if (ef_section_permissions && ef_section_permissions[k] && ef_section_permissions[k][action] === 'denied') {
                    throw "section没有" + action + "权限,sectionKey=" + k
                }
                if(Array.isArray(v)){
                    for(var i=0; i<v.length; i++){
                        var r = v[i];
                        checkObject(r,ef_field_permissions,k,action);
                    }
                }
                else{
                    checkObject(v,ef_field_permissions,k,action);
                }
            }
            else {
                if(ef_section_permissions && ef_section_permissions[k] && ef_field_permissions[k].add === 'denied'){
                    throw "字段没有" + action + "权限, key=" + k
                }
            }

        }
    }

}

function checkUpdatePermission(data,diffresult,permissions,orgId){
    var section_permissions = expandSectionPermission(permissions);
    var field_permissions = expandFieldPermission(permissions);
    var table_permissions = expandTablePermission(permissions);

    var ef_section_permissions = null;
    var ef_field_permissions = null;
    var ef_table_permissions = null;

    if (data._orgId === orgId) {
        ef_section_permissions = section_permissions.same_org;
        ef_field_permissions = field_permissions.same_org;
        ef_table_permissions = table_permissions.same_org;
    } else {
        if(isSubOrg(data,orgId)) {
            ef_section_permissions = section_permissions.sub_org;
            ef_field_permissions = field_permissions.sub_org;
            ef_table_permissions = table_permissions.sub_org;
        }
    }

    // $.log("ef_table_permissions=" + JSON.stringify(ef_table_permissions))
    if(!ef_table_permissions){
        throw "表没有权限。"
    }
    if(ef_table_permissions.update === 'denied'){
        throw "没有修改的权限。"
    }
    if(diffresult && diffresult.length>0){
        for(var i=0; i<diffresult.length; i++){
            var r = diffresult[i];
            var pk = "main";
            if(r.parentKey && r.parentKey.length>0){
                pk = r.parentKey.substring(1);
                if(ef_section_permissions[pk] && ef_section_permissions[pk].update ==='denied'){
                    throw "没有修改的权限,sectionKey=" + r.parentKey
                }

            }
            var rk = pk + "." + r.fieldKey;
            if(ef_field_permissions[rk] && ef_field_permissions[rk].update ==='denied' ){
                throw "没有修改字段的权限,fieldKey=" + rk;
            }

        }
    }
    //啥都不做代表检查通过
    //TODO:检查用户权限
}

function filterFields(data, permissions, orgId) {
    //根据权限，将没有读权限的字段删除掉
    var section_permissions = expandSectionPermission(permissions);
    var field_permissions = expandFieldPermission(permissions);
    var ef_section_permissions = null;
    var ef_field_permissions = null;
    if (data._orgId === orgId) {
        ef_section_permissions = section_permissions.same_org;
        ef_field_permissions = field_permissions.same_org;
    } else {
        ef_section_permissions = section_permissions.sub_org;
        ef_field_permissions = field_permissions.sub_org;
    }

    var invisibleFields = [];
    data['invisibleFields'] = invisibleFields;

    var valid_fields = ['_orgId', '_orgIds', "_v", "del"];
    var curSectionKey = '';
    for (var k in data) {
        if (valid_fields.indexOf(k) >= 0) {
            continue;
        } else {
            if (typeof data[k] === 'object') {
                if ((ef_section_permissions[k] && ef_section_permissions[k].read === 'denied') ||
                    ((!ef_section_permissions[k] || !ef_section_permissions[k].read) && (ef_section_permissions["*"] && ef_section_permissions["*"].read === 'denied'))) {
                    delete data[k];
                    invisibleFields.push(k);
                }
                var section = data[k];
                if (Array.isArray(section)) {
                    for (var i = 0; i < section.length; i++) {
                        var r = section[i];
                        for (var fk in r) {
                            var rk = k + "." + fk;
                            if ((ef_field_permissions[rk] && ef_field_permissions[rk].read === 'denied') ||
                                ((!ef_field_permissions[rk] || !ef_field_permissions[rk].read) && (ef_field_permissions[k + ".*"] && ef_field_permissions[k + ".*"].read === 'denied'))) {
                                delete r[fk];
                                invisibleFields.push(rk);
                            }
                        }

                    }
                }
            } else {
                if ((ef_field_permissions[k] && ef_field_permissions[k].read === 'denied') || ((!ef_field_permissions[k] || !ef_field_permissions[k].read) && ef_field_permissions["*"].read === 'denied')) {
                    delete data[k];
                    invisibleFields.push(k);
                }
            }
        }
    }
}

function mergeArray(a1, a2,section_permission){
    //a1是旧的,a2是新的
    // $.log("diffArray,parentKey=" + parentKey);

    var temp_matched = [];
    var result = [];
    var merged = [];
    if(!a1){
        a1 = [];
    }
    if(!a2){
        a2 = [];
    }
    var newa2 = [];
    for(var i=0; i<a2.length; i++){
        if(a2[i]!==null){
            if(!isScalar(a2[i])){
                delete a2[i]._matched;
            }
            newa2.push(a2[i]);
        }
    }
    a2 = newa2;
    for(var i=0; i<a1.length; i++){
        var r1 = a1[i];
        var found = false;
        for(var j=0; j<a2.length; j++){
            var r2 = a2[j];
            if(isEqual(r1,r2)){
                found = true;
                if(isScalar(r2)){
                    temp_matched.push(r2);
                }
                else{
                    if(r2!=null){
                        r2._matched = true;
                    }

                }
                merged.push(r1);
                break;
            }
        }
        if(!found){
            //r1不存在于a2中，说明r1被删除了
            if(section_permission && section_permission.del === 'denied'){
                //不允许删除
                merged.push(r1);
            }
        }
    }
    for(var i=0; i<a2.length; i++){
        r2 = a2[i];
        if(isScalar(r2)){
            if(temp_matched.indexOf(r2)==-1){
                if(!section_permission || section_permission.add !== 'denied' ){
                    merged.push(r2);
                }
            }

        }
        else if(!r2._matched){
            if(!section_permission || section_permission.add !== 'denied' ){
                merged.push(r2);
            }
        }
    }
    return merged;
}

function merge(oldObj,newObj,permissions,orgId){
    var section_permissions = expandSectionPermission(permissions);
    var field_permissions = expandFieldPermission(permissions);
    var table_permissions = expandTablePermission(permissions);

    var ef_section_permissions = null;
    var ef_field_permissions = null;
    var ef_table_permissions = null;
    if (oldObj._orgId === orgId) {
        ef_section_permissions = section_permissions.same_org;
        ef_field_permissions = field_permissions.same_org;
        ef_table_permissions = table_permissions.same_org;
    } else {
        ef_section_permissions = section_permissions.sub_org;
        ef_field_permissions = field_permissions.sub_org;
        ef_table_permissions = table_permissions.sub_org;
    }
    if(ef_table_permissions && ef_table_permissions.update==='denied'){
        throw "没有修改权限。"
    }

    for(var k in newObj){
        var vo = oldObj[k];
        var vn = newObj[k];
        if(typeof vo === 'object'){
            if(ef_section_permissions[k] && ef_section_permissions[k].update==='denied' || ef_section_permissions[k] && ef_section_permissions[k].read==='denied'){
                // newObj[k] = vo;
                continue;
            }

            if(Array.isArray(vo) || Array.isArray(vn)){
                //暂时对于Array, 只要对于section有权限，则是对于整行来说的，而不能对于行中的某个字段
                // var vn = newObj[k];
                // var merged = mergeArray(vo,vn,ef_section_permissions[k]);
                // var merged = vn;
                // newObj[k] = merged;
                oldObj[k] = vn; //mergeArray(vo,vn,ef_section_permissions[k]);
            }
            else {
                // var vn = newObj[k];
                for(var sk in vn){
                    var fk = k + "." + sk;
                    if(ef_field_permissions[fk] && ef_field_permissions[fk].update==='denied' || ef_field_permissions[fk] && ef_field_permissions[fk].read==='denied'){
                        // vn[fk] = vo[fk];
                        // vo[sk] = vn[sk]
                        continue;
                    }
                    vo[sk] = vn[sk];
                }
            }
        }
        else if(vo === null ){
            if((ef_section_permissions[k] && (ef_section_permissions[k].update==='denied' || ef_section_permissions[k].read==='denied') )||
                (ef_field_permissions[k] && (ef_field_permissions[k].update==='denied' || ef_field_permissions[k].read==='denied') )
            ){
                // newObj[k] = null;
                continue;
            }
        }
        else{
            if(ef_field_permissions[k] && (ef_field_permissions[k].update==='denied' || ef_field_permissions[k].read==='denied') ){
                continue;
                // newObj[k] = oldObj[k];
            }
            else{
                oldObj[k] = vn;
            }
        }
    }
    return oldObj;
}

function getObjectPermissionFilter(tableId, roleId,orgId,userId){
    var filters = [];
    var excludeFilters = [];

    filters = [
        {
            bool: {
                filter:[
                    {term:{"permissions.orgId.keyword":orgId}},
                    {term:{"permissions.roleId.keyword":roleId}},
                    {term:{"permissions.list.keyword":"allowed"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.orgId.keyword":orgId}},
                    {term:{"permissions.roleId.keyword":"*"}},
                    {term:{"permissions.list.keyword":"allowed"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.orgId.keyword":"*"}},
                    {term:{"permissions.roleId.keyword":roleId}},
                    {term:{"permissions.list.keyword":"allowed"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.orgId.keyword":"*"}},
                    {term:{"permissions.roleId.keyword":"*"}},
                    {term:{"permissions.list.keyword":"allowed"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.userId.keyword":userId}},
                    {term:{"permissions.list.keyword":"allowed"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.userId.keyword":"*"}},
                    {term:{"permissions.list.keyword":"allowed"}}
                ]
            }
        }
    ];
    //获取对象本身的权限

    excludeFilters= [
        {
            bool: {
                filter:[
                    {term:{"permissions.orgId.keyword":orgId}},
                    {term:{"permissions.roleId.keyword":roleId}},
                    {term:{"permissions.list.keyword":"denied"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.orgId.keyword":orgId}},
                    {term:{"permissions.roleId.keyword":"*"}},
                    {term:{"permissions.list.keyword":"denied"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.orgId.keyword":"*"}},
                    {term:{"permissions.roleId.keyword":roleId}},
                    {term:{"permissions.list.keyword":"denied"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.orgId.keyword":"*"}},
                    {term:{"permissions.roleId.keyword":"*"}},
                    {term:{"permissions.list.keyword":"denied"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.userId.keyword":userId}},
                    {term:{"permissions.list.keyword":"denied"}}
                ]
            }
        },
        {
            bool: {
                filter:[
                    {term:{"permissions.userId.keyword":"*"}},
                    {term:{"permissions.list.keyword":"denied"}}
                ]
            }
        }
    ];
    return [filters,excludeFilters]
}
function getListPermissionFilter(tableId, roleId,orgId,userId, permissions){
    if(userId==='0' && orgId==='0' && roleId==='0'){
        return null;
    }

    // $.log("getListPermissionFilter tableId="+tableId+",roleId="+roleId+",orgId="+orgId+",userId="+userId+", permissions="+JSON.stringify(permissions));
    //获得有权限的对象的filter
    var tp = expandTablePermission(permissions);


    //如果有listAll

    if(tp.same_org.listall==='allowed' || tp.sub_org.listall==='allowed' || roleId=='0' || userId=='0') {
        //只能读取本组织的数据
        // var objFilters = getObjectPermissionFilter(tableId, roleId,orgId,userId, permissions);
        var orgFilter = null;
        if(tp.sub_org.listall==='allowed'){
            if(orgId!='0'){
                orgFilter = {
                    "term": {"_orgIds.keyword": orgId}
                }
            }
            else{
                orgFilter = { "match_all": {}};
            }
        }
        else if(tp.same_org.listall==='allowed'){
            if(orgId!='0'){
                orgFilter =  {
                    "term": {"_orgId.keyword": orgId}
                }
            }
            else{
                orgFilter = { "match_all": {}};
            }

        }
        else {
            if(orgId!='0'){
                orgFilter = {
                    "term": {"_orgIds.keyword": orgId}
                }
            }
            else{
                orgFilter = { "match_all": {}};
            }
        }
        var shouldFilters = [];
        if(orgFilter){
            shouldFilters.push(orgFilter);
        }
        //组合对象允许的
        return  {
            bool:{
                should:shouldFilters
            }
        }
    }
    else {
        var objFilters = getObjectPermissionFilter(tableId, roleId,orgId,userId, permissions);
        return {
            bool:{
                should:objFilters[0],
                must_not:objFilters[1]
            }
        }
    }


}





