//#import Util.js
//#import login.js
//#import user.js
//#import base64.js
//#import HttpUtil.js
//#import session.js
//#import $@projectCode:services/modelService.jsx
//#import @handlers/include/checklogin.jsx

(function() {

    var env = checklogin();
    if (!env) {
        return;
    }

    var nAdded = 0;
    var nUpdated = 0;
    var nExists = 0;
    var nError = 0;

    try {
        var params = JSON.parse( $body );

        //判断是add还是update
        var objs = params.objs;
        var action = params.action;
        var errs = [];
        for(var i=0; i<objs.length; i++){
            try{
                var modelObject = objs[i];
                var id = modelObject.id;
                var oldObj = @projectCodeService.get(id);
                if(action=='add'){
                    if(!oldObj){
                        modelObject.m = env.m;
                        var newdata = @projectCodeService.add( modelObject,env );
                        nAdded = nAdded + 1;
                    }
                    else{
                        nExists = nExists + 1;
                    }
                }
                else if(action==='force'){
                    if(!oldObj){
                        modelObject.m = env.m;
                        var newdata = @projectCodeService.add( modelObject,env );
                        nAdded = nAdded + 1;
                    }
                    else{
                        modelObject._v = oldObj._v;
                        var newdata = @projectCodeService.update( modelObject,env);
                        nUpdated = nUpdated + 1;
                    }
                }
            }
            catch(e){
              errs.push("id=" + id + " " + e.toString() + "");
              nError++;
            }

        }
        var ret = {
            state:'ok',
            added:nAdded,
            updated:nUpdated,
            errored:nError,
            exists:nExists,
            errs:errs
        }
        out.print( JSON.stringify( ret ) );
    } catch ( e ) {
        var ret = {
            state: 'err',
            msg: e.toString() + ""
        };
        out.print( JSON.stringify( ret ) );
    }
})();