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 map from 'lodash/map';
import pick from 'lodash/pick';

function getRequestData(appServiceList) {
  var res = map(appServiceList, function (_ref) {
    var id = _ref.id,
        name = _ref.name,
        code = _ref.code,
        type = _ref.type,
        versionId = _ref.versionId;
    return {
      appServiceId: id,
      appName: name,
      appCode: code,
      type: type,
      versionId: versionId
    };
  });
  return res;
}

function getMarketRequestData(appServiceList) {
  var res = map(appServiceList, function (_ref2) {
    var name = _ref2.name,
        code = _ref2.code,
        type = _ref2.type,
        deployObjectId = _ref2.deployObjectId;
    return {
      appName: name,
      appCode: code,
      deployObjectId: deployObjectId
    };
  });
  return res;
}

function isGit(_ref3) {
  var record = _ref3.record;
  var flag = record.get('platformType') === 'github' || record.get('platformType') === 'gitlab';
  return flag;
}

export default (function (_ref4) {
  var intlPrefix = _ref4.intlPrefix,
      formatMessage = _ref4.formatMessage,
      projectId = _ref4.projectId,
      serviceTypeDs = _ref4.serviceTypeDs,
      selectedDs = _ref4.selectedDs,
      importTableDs = _ref4.importTableDs,
      marketSelectedDs = _ref4.marketSelectedDs;

  function checkCode(_x) {
    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) {
                _context.next = 18;
                break;
              }

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

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

            case 6:
              res = _context.sent;

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

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

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

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

            case 15:
              _context.next = 18;
              break;

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

            case 18:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[3, 12]]);
    }));
    return _checkCode.apply(this, arguments);
  }

  function checkName(_x2) {
    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) {
                _context2.next = 18;
                break;
              }

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

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

            case 6:
              res = _context2.sent;

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

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

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

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

            case 15:
              _context2.next = 18;
              break;

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

            case 18:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[3, 12]]);
    }));
    return _checkName.apply(this, arguments);
  }

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

    if (name === 'platformType') {
      selectedDs.removeAll();

      switch (value) {
        case 'share':
          importTableDs.setQueryParameter('share', true);
          break;

        case 'github':
          if (record.get('repositoryUrl') || !record.getField('repositoryUrl').isValid()) {
            record.set('repositoryUrl', null);
          }

          if (record.get('isTemplate')) {
            record.getField('githubTemplate').fetchLookup();
            record.get('githubTemplate') && record.set('repositoryUrl', record.get('githubTemplate'));
          }

          break;

        case 'gitlab':
          if (record.get('repositoryUrl') || !record.getField('repositoryUrl').isValid()) {
            record.set('repositoryUrl', null);
          }

          break;

        default:
          break;
      }
    }

    if (name === 'githubTemplate') {
      record.set('repositoryUrl', value);
    }

    if (name === 'isTemplate') {
      record.get('repositoryUrl') && record.set('repositoryUrl', null);

      if (value && record.get('githubTemplate')) {
        record.set('repositoryUrl', record.get('githubTemplate'));
      }
    }
  }

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

        var platformType = data.platformType;
        var url = 'external';
        var res;

        switch (platformType) {
          case 'gitlab':
            res = pick(data, ['code', 'name', 'type', 'accessToken', 'repositoryUrl']);
            break;

          case 'github':
            url = "".concat(url).concat(data.isTemplate ? '?is_template=true' : '');
            res = pick(data, ['code', 'name', 'type', 'repositoryUrl']);
            break;

          case 'share':
            url = 'internal';
            res = getRequestData(selectedDs.toData());
            break;

          case 'market':
            res = getMarketRequestData(marketSelectedDs.toData());
            break;
        }

        return {
          url: platformType === 'market' ? "/devops/v1/project/".concat(projectId, "/market/app/import") : "/devops/v1/projects/".concat(projectId, "/app_service/import/").concat(url),
          method: 'post',
          data: res
        };
      }
    },
    fields: [{
      name: 'name',
      type: 'string',
      maxLength: 40,
      dynamicProps: {
        required: isGit,
        validator: function validator(_ref7) {
          var record = _ref7.record;
          return isGit({
            record: record
          }) && checkName;
        }
      },
      label: formatMessage({
        id: "".concat(intlPrefix, ".name")
      })
    }, {
      name: 'code',
      type: 'string',
      maxLength: 30,
      dynamicProps: {
        required: isGit,
        validator: function validator(_ref8) {
          var record = _ref8.record;
          return isGit({
            record: record
          }) && checkCode;
        }
      },
      label: formatMessage({
        id: "".concat(intlPrefix, ".code")
      })
    }, {
      name: 'type',
      type: 'string',
      defaultValue: 'normal',
      textField: 'text',
      valueField: 'value',
      options: serviceTypeDs,
      dynamicProps: {
        required: isGit
      },
      label: formatMessage({
        id: "".concat(intlPrefix, ".type")
      })
    }, {
      name: 'platformType',
      type: 'string',
      defaultValue: 'share',
      label: formatMessage({
        id: "".concat(intlPrefix, ".import.type")
      })
    }, {
      name: 'repositoryUrl',
      type: 'url',
      dynamicProps: {
        required: isGit,
        label: function label(_ref9) {
          var record = _ref9.record;

          if (record.get('platformType') === 'gitlab' || record.get('platformType') === 'github') {
            return formatMessage({
              id: "".concat(intlPrefix, ".url.").concat(record.get('platformType'), ".clone")
            });
          }
        }
      }
    }, {
      name: 'accessToken',
      type: 'string',
      dynamicProps: {
        required: function required(_ref10) {
          var record = _ref10.record;
          return record.get('platformType') === 'gitlab';
        }
      },
      label: formatMessage({
        id: "".concat(intlPrefix, ".token")
      })
    }, {
      name: 'isTemplate',
      type: 'bool',
      defaultValue: true,
      label: formatMessage({
        id: "".concat(intlPrefix, ".github.source")
      })
    }, {
      name: 'githubTemplate',
      type: 'string',
      textField: 'name',
      valueField: 'path',
      dynamicProps: {
        lookupUrl: function lookupUrl(_ref11) {
          var record = _ref11.record;
          return record.get('platformType') === 'github' ? "/devops/v1/projects/".concat(projectId, "/app_service/list_service_templates") : '';
        },
        required: function required(_ref12) {
          var record = _ref12.record;
          return record.get('platformType') === 'github' && record.get('isTemplate');
        }
      },
      label: formatMessage({
        id: "".concat(intlPrefix, ".github.template")
      })
    }],
    events: {
      update: handleUpdate
    }
  };
});