function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

import { map, forOwn, isEmpty, forEach } from 'lodash';
export default (function (_ref) {
  var formatMessage = _ref.formatMessage,
      portDs = _ref.portDs,
      targetLabelsDs = _ref.targetLabelsDs,
      appInstanceOptionsDs = _ref.appInstanceOptionsDs,
      networkStore = _ref.networkStore,
      projectId = _ref.projectId,
      envId = _ref.envId,
      appId = _ref.appId,
      networkEdit = _ref.networkEdit;
  var networkInfoDs = networkEdit.networkInfoDs,
      networkId = networkEdit.networkId,
      initTargetLabel = networkEdit.initTargetLabel,
      initPorts = networkEdit.initPorts;
  /**
  * 检查名字的唯一性
  * @param value
  * @param name
  * @param record
  */

  function checkName(_x, _x2, _x3) {
    return _checkName.apply(this, arguments);
  }
  /**
   * 验证ip
   * @param value
   * @param name
   * @param record
   */


  function _checkName() {
    _checkName = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value, name, record) {
      var pattern, res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!networkId) {
                _context.next = 2;
                break;
              }

              return _context.abrupt("return");

            case 2:
              pattern = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;

              if (!(value && !pattern.test(value))) {
                _context.next = 7;
                break;
              }

              return _context.abrupt("return", formatMessage({
                id: 'network.name.check.failed'
              }));

            case 7:
              if (!(value && pattern.test(value))) {
                _context.next = 13;
                break;
              }

              _context.next = 10;
              return networkStore.checkNetWorkName(projectId, envId, value);

            case 10:
              res = _context.sent;

              if (res) {
                _context.next = 13;
                break;
              }

              return _context.abrupt("return", formatMessage({
                id: 'network.name.check.exist'
              }));

            case 13:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
    return _checkName.apply(this, arguments);
  }

  function checkIP(value, name, record) {
    var p = /^((\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/;
    var errorMsg;

    if (value) {
      if (!p.test(value)) {
        errorMsg = formatMessage({
          id: 'network.ip.check.failed'
        });
      }

      return errorMsg;
    }
  }

  function checkInstance(value, name, record) {
    if (!networkId) return;
    var msg;

    if (value) {
      var data = value.split(',');
      forEach(data, function (item) {
        var instance = appInstanceOptionsDs.find(function (r) {
          return r.get('code') === item;
        });
        var status = instance.get('status');

        if (instance && status && status !== 'running' && !msg) {
          msg = formatMessage({
            id: 'network.instance.check.failed'
          });
        }
      });

      if (data[1] && !msg) {
        msg = formatMessage({
          id: 'network.instance.check.failed.more'
        });
      }
    }

    if (msg) {
      return msg;
    }
  }

  return {
    autoCreate: true,
    children: {
      portDs: portDs,
      targetLabelsDs: targetLabelsDs
    },
    fields: [{
      name: 'name',
      type: 'string',
      label: formatMessage({
        id: 'network.form.name'
      }),
      required: true,
      validator: checkName
    }, {
      name: 'target',
      type: 'string',
      defaultValue: 'instance'
    }, {
      name: 'type',
      type: 'string',
      defaultValue: 'ClusterIP'
    }, {
      name: 'appInstance',
      type: 'string',
      label: formatMessage({
        id: 'network.target.instance'
      }),
      required: true,
      options: appInstanceOptionsDs,
      textField: 'code',
      valueField: 'code',
      validator: checkInstance,
      dynamicProps: {
        required: function required(_ref2) {
          var dataSet = _ref2.dataSet,
              record = _ref2.record,
              name = _ref2.name;
          return record.get('target') !== 'param';
        }
      }
    }, {
      name: 'externalIps',
      label: formatMessage({
        id: 'network.config.ip'
      }),
      multiple: true,
      validator: checkIP
    }],
    transport: {
      create: function create(_ref3) {
        var _ref3$data = _slicedToArray(_ref3.data, 1),
            data = _ref3$data[0];

        return {
          method: 'post',
          url: "/devops/v1/projects/".concat(projectId, "/service"),
          data: transFormData(data, formatMessage, appId, envId)
        };
      }
    },
    events: {
      update: function update(_ref4) {
        var dataSet = _ref4.dataSet,
            record = _ref4.record,
            name = _ref4.name,
            value = _ref4.value,
            oldValue = _ref4.oldValue;

        switch (name) {
          case 'target':
            networkId ? record.init('instance', initTargetLabel({
              targetLabelsDs: targetLabelsDs,
              type: value,
              record: record,
              networkInfoDs: networkInfoDs,
              formatMessage: formatMessage
            })) : handleTargetChange({
              targetLabelsDs: targetLabelsDs,
              value: value,
              record: record,
              dataSet: dataSet
            });
            break;

          case 'type':
            networkId ? record.init('externalIps', initPorts({
              portDs: portDs,
              type: value,
              networkInfoDs: networkInfoDs
            })) : handleTypeChange({
              portDs: portDs,
              value: value,
              record: record
            });
            break;

          default:
            break;
        }
      }
    }
  };
});

function handleTargetChange(_ref5) {
  var targetLabelsDs = _ref5.targetLabelsDs,
      value = _ref5.value,
      record = _ref5.record;
  var isParam = value === 'param';

  if (isParam) {
    record.set('appInstance', null);
  } else {
    targetLabelsDs.reset();
    targetLabelsDs.create();
  }
}

function handleTypeChange(_ref6) {
  var portDs = _ref6.portDs,
      value = _ref6.value,
      record = _ref6.record;
  portDs.reset();
  portDs.create();

  if (value !== 'ClusterIP') {
    record.set('externalIps', null);
  }
}

export function transFormData(data, formatMessage, appId, envId) {
  var portData = data.portDs,
      targetLabelsData = data.targetLabelsDs,
      target = data.target,
      appInstance = data.appInstance,
      name = data.name,
      type = data.type,
      externalIps = data.externalIps; // NOTE: 转换port的数据，过滤掉不用的数据

  var ports = map(portData, function (value) {
    return {
      port: value.port,
      targetPort: value.targetPort,
      nodePort: value.nodePort,
      protocol: value.protocol
    };
  });
  var targetAppServiceId;
  var targetInstanceCode;
  var selectors = null; // 目标对象是实例还是选择器

  if (target === 'instance') {
    /**
     * NOTE: 处理所有实例和单个实例的问题 
     * 所有实例直接与AppService关联所以此处赋值给targetAppServiceId
     * 单个实例直接与AppInstnace关联所以此处赋值给targetInstanceCode 
     */
    if (appInstance === formatMessage({
      id: 'all_instance'
    })) {
      targetAppServiceId = appId;
    } else {
      targetInstanceCode = appInstance;
    }
  } else {
    // NOTE: 处理selectors,将targetLabels的数组转换成key，value的对象
    selectors = {};
    forOwn(targetLabelsData, function (value, key) {
      if (value) {
        selectors[value.keyword] = value.value;
      }
    });

    if (isEmpty(selectors)) {
      selectors = null;
    }
  }

  var externalIp;

  if (externalIps) {
    var ips = externalIps.join(',');
    externalIp = ips || null;
  }

  return {
    appServiceId: appId,
    envId: envId,
    targetInstanceCode: targetInstanceCode,
    targetAppServiceId: targetAppServiceId,
    name: name,
    externalIp: externalIp,
    type: type,
    ports: ports,
    selectors: selectors,
    endPoints: null
  };
}