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); }); }; }

/* eslint-disable */
import omit from 'lodash/omit';
import forEach from 'lodash/forEach';
import map from 'lodash/map';
import uuidV1 from 'uuid/v1';
import { axios } from '@choerodon/boot';
import isEmpty from 'lodash/isEmpty';

function getRandomName() {
  var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var randomString = uuidV1();
  var realPrefix = prefix.split('_')[1] || prefix.split('_')[0];
  return realPrefix ? "".concat(realPrefix.substring(0, 24), "-").concat(randomString.substring(0, 5)) : randomString.substring(0, 30);
}

function formatAnnotation(postData) {
  var oldAnnotation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var annotations = {};
  forEach(oldAnnotation, function (_ref) {
    var domain = _ref.domain,
        key = _ref.key,
        value = _ref.value;

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

export default (function (_ref2) {
  var intlPrefix = _ref2.intlPrefix,
      formatMessage = _ref2.formatMessage,
      projectId = _ref2.projectId,
      envOptionsDs = _ref2.envOptionsDs,
      deployStore = _ref2.deployStore,
      networkDs = _ref2.networkDs,
      domainDs = _ref2.domainDs;

  function handleCreate(_ref3) {
    var dataSet = _ref3.dataSet,
        record = _ref3.record;
    var defaultEnvId = dataSet.records[0].get('environmentId');
    defaultEnvId && record.set('environmentId', defaultEnvId);
  }

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

  function _handleUpdate() {
    _handleUpdate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref4) {
      var dataSet, record, name, value, networkRecord, domainRecord, values, _values, _values2;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              dataSet = _ref4.dataSet, record = _ref4.record, name = _ref4.name, value = _ref4.value;
              networkRecord = record.getCascadeRecords('devopsServiceReqVO')[0];
              domainRecord = record.getCascadeRecords('devopsIngressVO')[0];
              _context.t0 = name;
              _context.next = _context.t0 === 'environmentId' ? 6 : _context.t0 === 'appServiceId' ? 15 : _context.t0 === 'appServiceVersionId' ? 20 : _context.t0 === 'valueId' ? 27 : 40;
              break;

            case 6:
              dataSet.forEach(function (eachRecord) {
                return eachRecord !== record && eachRecord.set('environmentId', value);
              });
              record.get('instanceName') && record.getField('instanceName').checkValidity();
              record.set('valueId', null);
              networkRecord.getField('name').checkValidity();
              domainRecord.getField('name').checkValidity();
              forEach(domainRecord.getCascadeRecords('pathList'), function (pathRecord) {
                pathRecord.getField('path').checkValidity();
              });
              domainRecord.get('certId') && domainRecord.set('certId', null);
              domainRecord.getField('certId').fetchLookup();
              return _context.abrupt("break", 41);

            case 15:
              record.get('appServiceVersionId') && record.set('appServiceVersionId', null);
              record.getField('appServiceVersionId').reset();

              if (value) {
                record.getField('appServiceVersionId').set('lookupAxiosConfig', {
                  url: "/devops/v1/projects/".concat(projectId, "/app_service_versions/page_by_options?app_service_id=").concat(value.split('**')[0], "&deploy_only=true&do_page=true&page=1&size=40"),
                  method: 'post'
                });
                record.set('instanceName', getRandomName(value.split('**')[1]));
              }

              record.set('valueId', null);
              return _context.abrupt("break", 41);

            case 20:
              if (record.get('valueId')) {
                _context.next = 26;
                break;
              }

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

              _context.next = 24;
              return deployStore.loadDeployValue(projectId, value);

            case 24:
              values = _context.sent;
              record.set('values', values);

            case 26:
              return _context.abrupt("break", 41);

            case 27:
              if (!value) {
                _context.next = 34;
                break;
              }

              _context.next = 30;
              return deployStore.loadConfigValue(projectId, value);

            case 30:
              _values = _context.sent;
              record.set('values', _values);
              _context.next = 39;
              break;

            case 34:
              if (!record.get('appServiceVersionId')) {
                _context.next = 39;
                break;
              }

              _context.next = 37;
              return deployStore.loadDeployValue(projectId, record.get('appServiceVersionId'));

            case 37:
              _values2 = _context.sent;
              record.set('values', _values2);

            case 39:
              return _context.abrupt("break", 41);

            case 40:
              return _context.abrupt("break", 41);

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

  function getValueIdLookUp(_ref5) {
    var record = _ref5.record;

    if (record.get('environmentId') && record.get('appServiceId')) {
      return {
        url: "/devops/v1/projects/".concat(projectId, "/deploy_value/list_by_env_and_app?env_id=").concat(record.get('environmentId'), "&app_service_id=").concat(record.get('appServiceId').split('**')[0]),
        method: 'get'
      };
    }
  }

  function checkName(_x2, _x3, _x4) {
    return _checkName.apply(this, arguments);
  }

  function _checkName() {
    _checkName = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(value, name, record) {
      var pa, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              pa = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;

              if (!(value && pa.test(value))) {
                _context2.next = 18;
                break;
              }

              if (record.get('environmentId')) {
                _context2.next = 4;
                break;
              }

              return _context2.abrupt("return");

            case 4:
              _context2.prev = 4;
              _context2.next = 7;
              return axios.get("/devops/v1/projects/".concat(projectId, "/app_service_instances/check_name?instance_name=").concat(value, "&env_id=").concat(record.get('environmentId')));

            case 7:
              res = _context2.sent;

              if (!(res && res.failed || !res)) {
                _context2.next = 10;
                break;
              }

              return _context2.abrupt("return", formatMessage({
                id: 'checkNameExist'
              }));

            case 10:
              return _context2.abrupt("return", true);

            case 13:
              _context2.prev = 13;
              _context2.t0 = _context2["catch"](4);
              return _context2.abrupt("return", formatMessage({
                id: 'checkNameFailed'
              }));

            case 16:
              _context2.next = 19;
              break;

            case 18:
              return _context2.abrupt("return", formatMessage({
                id: 'checkNameReg'
              }));

            case 19:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[4, 13]]);
    }));
    return _checkName.apply(this, arguments);
  }

  return {
    autoCreate: true,
    autoQuery: false,
    paging: false,
    children: {
      devopsServiceReqVO: networkDs,
      devopsIngressVO: domainDs
    },
    transport: {
      create: function create(_ref6) {
        var data = _ref6.data;
        var newData = [];
        forEach(data, function (item) {
          var res = omit(item, ['__id', '__status', 'appServiceSource', 'devopsServiceReqVO', 'devopsIngressVO']);
          var appServiceId = item.appServiceId.split('**')[0];
          var devopsServiceReqVO = item.devopsServiceReqVO ? omit(item.devopsServiceReqVO[0], ['__id', '__status']) : null;
          var devopsIngressVO = item.devopsIngressVO ? omit(item.devopsIngressVO[0], ['__id', '__status']) : null;
          res.appServiceId = appServiceId;

          if (devopsServiceReqVO && devopsServiceReqVO.name) {
            var newPorts = map(devopsServiceReqVO.ports || [], function (_ref7) {
              var port = _ref7.port,
                  targetPort = _ref7.targetPort,
                  nodePort = _ref7.nodePort,
                  protocol = _ref7.protocol;
              return {
                port: Number(port),
                targetPort: Number(targetPort),
                nodePort: nodePort ? Number(nodePort) : null,
                protocol: devopsServiceReqVO.type === 'NodePort' ? protocol : null
              };
            });
            var externalIp = devopsServiceReqVO.externalIp;
            devopsServiceReqVO.ports = newPorts;
            devopsServiceReqVO.externalIp = externalIp && externalIp.length ? externalIp.join(',') : null;
            devopsServiceReqVO.targetInstanceCode = res.instanceName;
            devopsServiceReqVO.envId = res.environmentId;
            res.devopsServiceReqVO = devopsServiceReqVO;
          }

          if (devopsIngressVO && devopsIngressVO.name) {
            devopsIngressVO.envId = res.environmentId;
            devopsIngressVO.appServiceId = appServiceId;
            res.devopsIngressVO = devopsIngressVO;
            formatAnnotation(res.devopsIngressVO, devopsIngressVO.annotations);
          }

          newData.push(res);
        });
        return {
          url: "/devops/v1/projects/".concat(projectId, "/app_service_instances/batch_deployment"),
          method: 'post',
          data: newData
        };
      }
    },
    fields: [{
      name: 'appServiceId',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".app")
      }),
      required: true
    }, {
      name: 'appServiceVersionId',
      type: 'string',
      textField: 'version',
      valueField: 'id',
      label: formatMessage({
        id: "".concat(intlPrefix, ".app.version")
      }),
      required: true
    }, {
      name: 'environmentId',
      type: 'string',
      textField: 'name',
      valueField: 'id',
      label: formatMessage({
        id: 'environment'
      }),
      required: true,
      options: envOptionsDs
    }, {
      name: 'instanceName',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".instance.name")
      }),
      required: true,
      validator: checkName,
      maxLength: 53
    }, {
      name: 'valueId',
      type: 'string',
      textField: 'name',
      valueField: 'id',
      label: formatMessage({
        id: "".concat(intlPrefix, ".config")
      }),
      dynamicProps: {
        lookupAxiosConfig: getValueIdLookUp
      }
    }, {
      name: 'values',
      type: 'string'
    }, {
      name: 'type',
      type: 'string',
      defaultValue: 'create'
    }, {
      name: 'isNotChange',
      type: 'boolean',
      defaultValue: false
    }, {
      name: 'appServiceSource',
      type: 'string',
      defaultValue: 'normal_service'
    }, {
      name: 'hasError',
      type: 'boolean',
      defaultValue: false,
      ignore: 'always'
    }],
    events: {
      create: handleCreate,
      update: handleUpdate
    }
  };
});