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 { axios } from '@choerodon/boot';
import omit from 'lodash/omit';
import forEach from 'lodash/forEach';
import map from 'lodash/map';
import pick from 'lodash/pick';
import isEmpty from 'lodash/isEmpty';

function formatAnnotation(postData, data, oldAnnotations) {
  var annotations = {};
  forEach(oldAnnotations || data.annotations, function (_ref) {
    var key = _ref.key,
        value = _ref.value;

    if (key && value) {
      annotations[key] = value;
    }
  });
  postData.annotations = isEmpty(annotations) ? null : annotations;
}

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

  function checkName(_x) {
    return _checkName.apply(this, arguments);
  }

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

              return _context.abrupt("return");

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

              if (!value) {
                _context.next = 20;
                break;
              }

              if (!(envId && p.test(value))) {
                _context.next = 19;
                break;
              }

              _context.prev = 5;
              _context.next = 8;
              return axios.get("/devops/v1/projects/".concat(projectId, "/ingress/check_name?env_id=").concat(envId, "&name=").concat(value));

            case 8:
              res = _context.sent;

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

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

            case 11:
              return _context.abrupt("return", formatMessage({
                id: 'checkNameExist'
              }));

            case 14:
              _context.prev = 14;
              _context.t0 = _context["catch"](5);
              return _context.abrupt("return", formatMessage({
                id: 'checkNameFailed'
              }));

            case 17:
              _context.next = 20;
              break;

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

            case 20:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[5, 14]]);
    }));
    return _checkName.apply(this, arguments);
  }

  function checkDomain(value) {
    var pattern = /^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;

    if (!pattern.test(value)) {
      return formatMessage({
        id: 'domain.domain.check.reg.failed'
      });
    }
  }

  function handleUpdate(_ref3) {
    var name = _ref3.name,
        value = _ref3.value,
        record = _ref3.record;

    if (name === 'domain') {
      pathListDs.forEach(function (pathRecord) {
        return pathRecord.getField('path').checkValidity();
      });
    }

    if (name === 'isNormal') {
      if (ingressId && !value && record.get('domain') && record.get('domain') === record.getPristineValue('domain') && record.getPristineValue('certId')) {
        record.set('certId', record.getPristineValue('certId'));
      } else {
        record.get('certId') && record.set('certId', null);
      }
    }
  }

  function handleLoad(_ref4) {
    var dataSet = _ref4.dataSet;
    var record = dataSet.current;
    record.init('isNormal', !record.get('certId'));
    var annotations = map(record.get('annotations') || [], function (value, key) {
      return {
        value: value,
        key: key
      };
    });
    annotationDs.loadData(isEmpty(annotations) ? [{}] : annotations);
  }

  function renderLookupUrl(_ref5) {
    var record = _ref5.record;
    var domain = record.get('domain');

    if (domain && !record.get('isNormal')) {
      return {
        url: "/devops/v1/projects/".concat(projectId, "/certifications/active?env_id=").concat(envId, "&domain=").concat(domain),
        method: 'post'
      };
    }
  }

  return {
    autoCreate: false,
    autoQuery: false,
    selection: false,
    paging: false,
    autoQueryAfterSubmit: false,
    children: {
      pathList: pathListDs,
      annotations: annotationDs
    },
    transport: {
      read: {
        url: "/devops/v1/projects/".concat(projectId, "/ingress/").concat(ingressId),
        method: 'get'
      },
      create: function create(_ref6) {
        var _ref6$data = _slicedToArray(_ref6.data, 1),
            data = _ref6$data[0];

        var postData = omit(data, '__id', '__status', 'annotations');
        formatAnnotation(postData, data);
        return {
          url: "/devops/v1/projects/".concat(projectId, "/ingress"),
          method: 'post',
          data: postData
        };
      },
      update: function update(_ref7) {
        var _ref7$data = _slicedToArray(_ref7.data, 1),
            data = _ref7$data[0];

        var postData = pick(data, 'name', 'domain', 'envId', 'appServiceId', 'certId');
        postData.domainId = ingressId;
        postData.pathList = pathListDs.toData();
        formatAnnotation(postData, data, annotationDs.toData());
        return {
          url: "/devops/v1/projects/".concat(projectId, "/ingress/").concat(ingressId),
          method: 'put',
          data: postData
        };
      }
    },
    fields: [{
      name: 'name',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".application.net.ingress")
      }),
      required: true,
      validator: checkName,
      maxLength: 40
    }, {
      name: 'domain',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".domains")
      }),
      required: true,
      validator: checkDomain,
      maxLength: 50
    }, {
      name: 'isNormal',
      type: 'boolean',
      defaultValue: true,
      required: true,
      ignore: 'always'
    }, {
      name: 'certId',
      type: 'string',
      textField: 'certName',
      valueField: 'id',
      label: formatMessage({
        id: 'domain.form.cert'
      }),
      dynamicProps: {
        required: function required(_ref8) {
          var record = _ref8.record;
          return !record.get('isNormal');
        },
        lookupAxiosConfig: renderLookupUrl
      }
    }, {
      name: 'envId',
      type: 'string',
      defaultValue: envId
    }, {
      name: 'appServiceId',
      type: 'string',
      defaultValue: appServiceId
    }],
    events: {
      load: handleLoad,
      update: handleUpdate
    }
  };
});