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 { axios } from '@choerodon/boot';
import find from 'lodash/find';
import some from 'lodash/some';

function handleCreate(_ref) {
  var dataSet = _ref.dataSet;
  var hasNameRecord = dataSet.find(function (record) {
    return record.get('serviceName');
  });
  dataSet.forEach(function (record) {
    hasNameRecord && record.init('serviceName', hasNameRecord.get('serviceName'));
    hasNameRecord && record.init('ports', hasNameRecord.get('ports'));
    record.getField('path').checkValidity();
  });
}

function handleUpdate(_x) {
  return _handleUpdate.apply(this, arguments);
}

function _handleUpdate() {
  _handleUpdate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(_ref2) {
    var value, name, record, dataSet;
    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            value = _ref2.value, name = _ref2.name, record = _ref2.record, dataSet = _ref2.dataSet;

            if (name === 'path' && value) {
              dataSet.forEach(function (eachRecord) {
                if (record.id !== eachRecord.id) {
                  eachRecord.getField('path').checkValidity();
                }
              });
            }

          case 2:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _handleUpdate.apply(this, arguments);
}

export default (function (_ref3) {
  var formatMessage = _ref3.formatMessage,
      projectId = _ref3.projectId,
      ingressId = _ref3.ingressId;

  function checkPath(_x2, _x3, _x4) {
    return _checkPath.apply(this, arguments);
  }

  function _checkPath() {
    _checkPath = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value, name, record) {
      var envId, p, domain, dataSet, repeatRecord, res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (record.cascadeParent) {
                _context.next = 2;
                break;
              }

              return _context.abrupt("return");

            case 2:
              envId = record.cascadeParent.cascadeParent.get('environmentId');
              p = /^\/(\S)*$/;
              domain = record.cascadeParent.get('domain');

              if (domain) {
                _context.next = 7;
                break;
              }

              return _context.abrupt("return");

            case 7:
              if (value) {
                _context.next = 9;
                break;
              }

              return _context.abrupt("return", formatMessage({
                id: 'domain.path.check.notSet'
              }));

            case 9:
              if (!p.test(value)) {
                _context.next = 32;
                break;
              }

              dataSet = record.dataSet;
              repeatRecord = dataSet.find(function (pathRecord) {
                return pathRecord.id !== record.id && pathRecord.get('path') === value;
              });

              if (!repeatRecord) {
                _context.next = 16;
                break;
              }

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

            case 16:
              _context.prev = 16;
              _context.next = 19;
              return axios.get("/devops/v1/projects/".concat(projectId, "/ingress/check_domain?domain=").concat(domain, "&env_id=").concat(envId, "&path=").concat(value, "&id=").concat(ingressId || ''));

            case 19:
              res = _context.sent;

              if (!(res && !res.failed)) {
                _context.next = 24;
                break;
              }

              return _context.abrupt("return", true);

            case 24:
              return _context.abrupt("return", formatMessage({
                id: 'domain.path.check.exist'
              }));

            case 25:
              _context.next = 30;
              break;

            case 27:
              _context.prev = 27;
              _context.t0 = _context["catch"](16);
              return _context.abrupt("return", formatMessage({
                id: 'domain.path.check.failed'
              }));

            case 30:
              _context.next = 33;
              break;

            case 32:
              return _context.abrupt("return", formatMessage({
                id: 'domain.path.check.failed'
              }));

            case 33:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[16, 27]]);
    }));
    return _checkPath.apply(this, arguments);
  }

  function isRequired(_ref4) {
    var dataSet = _ref4.dataSet,
        record = _ref4.record;
    var parentRecord = record.cascadeParent;
    var hasValue = parentRecord.get('name') || parentRecord.get('domain') || parentRecord.get('certId');
    var dirty = dataSet.some(function (pathRecord) {
      return pathRecord.dirty;
    });
    return dirty || !!hasValue;
  }

  return {
    autoCreate: true,
    autoQuery: false,
    selection: false,
    paging: false,
    fields: [{
      name: 'path',
      type: 'string',
      defaultValue: '/',
      label: formatMessage({
        id: 'path'
      }),
      validator: checkPath,
      maxLength: 30
    }, {
      name: 'serviceName',
      type: 'string',
      label: formatMessage({
        id: 'network'
      }),
      dynamicProps: {
        required: isRequired
      }
    }, {
      name: 'servicePort',
      type: 'number',
      label: formatMessage({
        id: 'port'
      }),
      dynamicProps: {
        required: isRequired
      }
    }, {
      name: 'ports',
      type: 'object',
      ignore: 'always'
    }],
    events: {
      create: handleCreate,
      update: handleUpdate,
      remove: handleCreate
    }
  };
});