import { map } from 'lodash';
export default (function (_ref) {
  var formatMessage = _ref.formatMessage;

  /**
   * 验证端口号
   * @param value
   * @param type
   * @param record
   */
  function checkPort(value, type, record) {
    var p = /^([1-9]\d*|0)$/;
    var isRepeat = record.dataSet.findIndex(function (r) {
      return record.id !== r.id && r.get(type) === value;
    }) !== -1;
    var data = {
      typeMsg: '',
      min: 0,
      max: 65535,
      failedMsg: 'network.port.check.failed'
    };
    data.typeMsg = 'network.tport.check.repeat';

    if (value) {
      if (p.test(value) && parseInt(value, 10) >= data.min && parseInt(value, 10) <= data.max) {
        if (!isRepeat) {
          return true;
        } else {
          return formatMessage({
            id: data.typeMsg
          });
        }
      } else {
        return formatMessage({
          id: data.failedMsg
        });
      }
    }
  }

  return {
    fields: [{
      name: 'targetPort',
      type: 'string',
      label: formatMessage({
        id: 'network.config.targetPort'
      }),
      dynamicProps: {
        required: function required(_ref2) {
          var dataSet = _ref2.dataSet,
              record = _ref2.record,
              name = _ref2.name;
          if (!dataSet.parent.current) return false;
          return dataSet.parent.current.get('target') === 'endPoints';
        }
      },
      validator: checkPort
    }],
    events: {
      update: updateEventHandler
    }
  };
});

function updateEventHandler(_ref3) {
  var dataSet = _ref3.dataSet,
      record = _ref3.record,
      name = _ref3.name,
      value = _ref3.value,
      oldValue = _ref3.oldValue;
  if (!value) return;
  checkOtherRecords(record, name);
}

function checkOtherRecords(record, type) {
  record.dataSet.forEach(function (r) {
    if (r.id !== record.id) {
      // 此处只对重复性做校验，不对空值做校验
      if (r.get(type)) {
        r.getField(type).checkValidity();
      }
    }
  });
}