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;
  dataSet.forEach(function (record) {
    record.getField('path').checkValidity();
  });
}

export default (function (_ref2) {
  var formatMessage = _ref2.formatMessage,
      projectId = _ref2.projectId,
      envId = _ref2.envId,
      ingressId = _ref2.ingressId,
      serviceDs = _ref2.serviceDs;

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

  function _checkPath() {
    _checkPath = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value, name, record) {
      var p, domain, dataSet, repeatRecord, res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              p = /^\/(\S)*$/;
              domain = record.cascadeParent.get('domain');

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

              return _context.abrupt("return");

            case 4:
              if (value) {
                _context.next = 6;
                break;
              }

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

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

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

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

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

            case 13:
              _context.prev = 13;
              _context.next = 16;
              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 16:
              res = _context.sent;

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

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

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

            case 22:
              _context.next = 27;
              break;

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

            case 27:
              _context.next = 30;
              break;

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

            case 30:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[13, 24]]);
    }));
    return _checkPath.apply(this, arguments);
  }

  function checkService(value) {
    if (!value) return;
    var service = serviceDs.find(function (serviceRecord) {
      return serviceRecord.get('id') === value;
    });

    if (service && service.get('status') && service.get('status') !== 'running') {
      return formatMessage({
        id: 'domain.network.check.failed'
      });
    }
  }

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

  function _handleUpdate() {
    _handleUpdate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(_ref3) {
      var value, name, record, dataSet, serviceList, _ref4, serviceName, config;

      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              value = _ref3.value, name = _ref3.name, record = _ref3.record, dataSet = _ref3.dataSet;

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

              if (name === 'serviceId') {
                if (value) {
                  serviceList = serviceDs.toData();
                  _ref4 = find(serviceList || [], function (_ref5) {
                    var id = _ref5.id;
                    return value === id;
                  }) || {}, serviceName = _ref4.name, config = _ref4.config;
                  record.set('serviceName', serviceName);
                  record.set('ports', config ? config.ports : []);
                } else {
                  record.set('serviceName', null);
                  record.set('ports', []);
                }

                if (record.get('servicePort') && !some(record.get('ports'), function (_ref6) {
                  var port = _ref6.port;
                  return port === record.get('servicePort');
                })) {
                  record.set('servicePort', null);
                }
              }

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

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