//#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 (!id || action==='add') {
      //adding
      if(!modelObject._orgId){
        modelObject._orgId = orgId;
      }
      modelObject._orgIds = [modelObject._orgId].concat(getParentOrgIds(modelObject._orgId));
      modelObject.m = env.m;

      //如果检查不通过，则会抛出异常
      if(roleId!=='internal'  && roleId!='0'){
          checkPermission(modelObject,permissions,orgId,"add");
      }
      modelObject.owl_createUserId = env.loginUserId;
      var newdata = @projectCodeService.add( modelObject,env );
    }
    else {
      modelObject._orgId = oldObj._orgId;
      modelObject._orgIds = [modelObject._orgId].concat(getParentOrgIds(modelObject._orgId));
    
      //修复_orgIds
      var _orgIds = [modelObject._orgId];
      if(modelObject._orgIds){
        modelObject._orgIds.forEach(function(orgId){
          if(typeof orgId === 'string'){
            //过滤重复的orgId
            if(_orgIds.indexOf(orgId)===-1){
              _orgIds.push(orgId);
            }
          }
          else{
            if(_orgIds.indexOf('0')===-1) {
              _orgIds.push('0');
            }
          }
        });
      }
      modelObject._orgIds = _orgIds;
      // diffResult = diff(oldObj,modelObject,"");
      if(roleId!=='internal'  && roleId!='0') {
        checkUpdatePermission(modelObject, diffResult, permissions, orgId);
      }
      if(modelObject._v === -1){
        modelObject._v = oldObj._v;
      }
      var merged = merge(oldObj,modelObject,permissions,orgId);
      merged.owl_lastModifiedUserId = env.loginUserId;
      var newdata = @projectCodeService.update( merged,env);
    }

    var ret = {
      state: 'ok',
      object: newdata,
      diffResult:diffResult
    };
    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);

}



