//#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 spec = @spec;
    var env = checklogin();
    if(!env){
        return;
    }
    var shopId = env.shopId;
    var warehouseId = env.warehouseId;
    var m = shopId;
    var orgId = env.orgId;
    var orgIds = env.orgIds;


    ///////////////////////////////

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

        //判断是add还是update
        var id = modelObject.id;
        var action = $.params.action;
        var oldObj = @projectCodeService.get(id);
        var roleId = env.roleId
        if(orgId && oldObj && oldObj._orgIds){
            //检查是否有权限修改
            if(roleId!=='internal' && roleId!='0' && orgId!='0' && oldObj._orgIds.indexOf(orgId)===-1){
                var ret = {
                    state:'err',
                    code: 'no permission',
                    msg: '没有权限'
                }
                out.print(JSON.stringify(ret));
                return;
            }
        }
        var diffResult =[];
        var tableId = 'owl_' + spec._t;
        var permissions = getPermissions(roleId,tableId);
        //如果检查不通过，则会抛出异常
        if(roleId!=='internal'  && roleId!='0'){
            checkPermission(modelObject,permissions,orgId,"add");
        }
        var id = @projectCodeService.getId(modelObject);
        var ret = {
            state: 'ok',
            id: id
        };
        out.print( JSON.stringify( ret ) );
    } catch ( e ) {
        var ret = {
            state: 'err',
            msg: getErrorMsg(e)
        };
        out.print( JSON.stringify( ret ) );
    }
})();

function getErrorMsg(e){
    if(typeof e === 'string'){
        return e;
    }
    var msg = e.msg || e.message || e.toString();
    var beginIdx = msg.indexOf(':');
    if(beginIdx===-1){
        return msg;
    }
    var endIdx = msg.indexOf('(',beginIdx);
    if(endIdx===-1){
        return msg;
    }
    return msg.substring(beginIdx+1,endIdx);

}



