function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 AppServiceApis from "../../../apis";

function fetchLookup(_x, _x2) {
  return _fetchLookup.apply(this, arguments);
}

function _fetchLookup() {
  _fetchLookup = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(field, record) {
    var data;
    return regeneratorRuntime.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return field.fetchLookup();

          case 2:
            data = _context3.sent;

            if (data && data.length) {
              record.set('templateAppServiceVersionId', data[0].id);
            }

          case 4:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));
  return _fetchLookup.apply(this, arguments);
}

export default (function (_ref) {
  var intlPrefix = _ref.intlPrefix,
      formatMessage = _ref.formatMessage,
      projectId = _ref.projectId,
      sourceDs = _ref.sourceDs,
      store = _ref.store,
      randomString = _ref.randomString;

  function checkCode(_x3) {
    return _checkCode.apply(this, arguments);
  }

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

              if (!(value && pa.test(value))) {
                _context.next = 16;
                break;
              }

              _context.prev = 2;
              _context.next = 5;
              return axios.get("/devops/v1/projects/".concat(projectId, "/app_service/check_code?code=").concat(value));

            case 5:
              res = _context.sent;

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

              return _context.abrupt("return", formatMessage({
                id: 'checkCodeExist'
              }));

            case 8:
              return _context.abrupt("return", true);

            case 11:
              _context.prev = 11;
              _context.t0 = _context["catch"](2);
              return _context.abrupt("return", formatMessage({
                id: 'checkCodeFailed'
              }));

            case 14:
              _context.next = 17;
              break;

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

            case 17:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[2, 11]]);
    }));
    return _checkCode.apply(this, arguments);
  }

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

  function _checkName() {
    _checkName = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(value) {
      var pa, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              pa = /^\S+$/;

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

              _context2.prev = 2;
              _context2.next = 5;
              return axios.get("/devops/v1/projects/".concat(projectId, "/app_service/check_name?name=").concat(encodeURIComponent(value)));

            case 5:
              res = _context2.sent;

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

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

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

            case 11:
              _context2.prev = 11;
              _context2.t0 = _context2["catch"](2);
              return _context2.abrupt("return", formatMessage({
                id: "".concat(intlPrefix, ".name.failed")
              }));

            case 14:
              _context2.next = 17;
              break;

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

            case 17:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[2, 11]]);
    }));
    return _checkName.apply(this, arguments);
  }

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

    if (name === 'templateAppServiceId') {
      record.set('templateAppServiceVersionId', null);
      var field = record.getField('templateAppServiceVersionId');
      field.reset();

      if (value) {
        fetchLookup(field, record);
      }
    }

    if (name === 'appServiceSource') {
      record.set('templateAppServiceId', null);
      record.set('devopsAppTemplateId', null);
      store.setAppService([]);

      if (['normal_service', 'share_service'].includes(value)) {
        store.loadAppService(projectId, value);
      }
    }
  }

  return {
    autoCreate: true,
    autoQuery: false,
    selection: false,
    paging: false,
    transport: {
      create: function create(_ref3) {
        var _ref3$data = _slicedToArray(_ref3.data, 1),
            data = _ref3$data[0];

        var res = omit(data, ['appServiceSource', '__id', '__status']);
        return {
          url: ['organization_template', 'site_template'].includes(data.appServiceSource) && data.devopsAppTemplateId ? AppServiceApis.createAppServiceByTemplate(projectId) : "/devops/v1/projects/".concat(projectId, "/app_service"),
          method: 'post',
          data: _objectSpread(_objectSpread({}, res), {}, {
            isSkipCheckPermission: true
          })
        };
      }
    },
    fields: [{
      name: 'name',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".name")
      }),
      required: true,
      validator: checkName,
      maxLength: 40
    }, {
      name: 'code',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".code")
      }),
      required: true,
      maxLength: 30,
      validator: checkCode
    }, {
      name: 'type',
      type: 'string',
      defaultValue: 'normal',
      label: formatMessage({
        id: "".concat(intlPrefix, ".type")
      }),
      required: true
    }, {
      name: 'imgUrl',
      type: 'string'
    }, {
      name: 'appServiceSource',
      defaultValue: 'normal_service',
      type: 'string',
      textField: 'text',
      valueField: 'value',
      label: formatMessage({
        id: "".concat(intlPrefix, ".service.source")
      }),
      options: sourceDs
    }, {
      name: 'templateAppServiceId',
      type: 'string',
      label: formatMessage({
        id: intlPrefix
      })
    }, {
      name: 'templateAppServiceVersionId',
      type: 'string',
      textField: 'version',
      valueField: 'id',
      label: formatMessage({
        id: "".concat(intlPrefix, ".version")
      }),
      dynamicProps: {
        lookupAxiosConfig: function lookupAxiosConfig(_ref4) {
          var record = _ref4.record;
          return {
            url: record.get('templateAppServiceId') ? "/devops/v1/projects/".concat(projectId, "/app_service_versions/page_by_options?app_service_id=").concat(record.get('templateAppServiceId'), "&deploy_only=false&do_page=true&page=1&size=10&randomString=").concat(randomString) : '',
            method: 'post'
          };
        }
      }
    }, {
      name: 'devopsAppTemplateId',
      label: formatMessage({
        id: "".concat(intlPrefix, ".template.name")
      }),
      textField: 'name',
      valueField: 'id',
      dynamicProps: {
        lookupAxiosConfig: function lookupAxiosConfig(_ref5) {
          var record = _ref5.record;
          return {
            url: ['organization_template', 'site_template'].includes(record.get('appServiceSource')) ? AppServiceApis.getTemplateList(projectId, record.get('appServiceSource') === 'organization_template' ? 'organization' : 'site', randomString) : '',
            method: 'get'
          };
        }
      }
    }],
    events: {
      create: function create() {
        store.loadAppService(projectId, 'normal_service');
      },
      update: handleUpdate
    }
  };
});