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

/* eslint-disable import/no-anonymous-default-export */
import { handlePromptError } from "../../../../../../../../utils";
var clusterName;
export default (function (_ref) {
  var projectId = _ref.projectId,
      formatMessage = _ref.formatMessage,
      intlPrefix = _ref.intlPrefix,
      modal = _ref.modal,
      isEdit = _ref.isEdit,
      afterOk = _ref.afterOk,
      mainStore = _ref.mainStore,
      clusterId = _ref.clusterId;

  function checkClusterName(_x) {
    return _checkClusterName.apply(this, arguments);
  }

  function _checkClusterName() {
    _checkClusterName = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value) {
      var messageName;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              messageName = true;

              if (!(value === clusterName && isEdit)) {
                _context.next = 3;
                break;
              }

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

            case 3:
              _context.next = 5;
              return mainStore.checkClusterName({
                projectId: projectId,
                clusterName: window.encodeURIComponent(value)
              }).then(function (res) {
                if (res && res.failed || !res) {
                  messageName = formatMessage({
                    id: 'checkNameExist'
                  });
                }
              })["catch"](function (e) {
                messageName = "".concat(formatMessage({
                  id: "".concat(intlPrefix, ".check.error")
                }));
              });

            case 5:
              return _context.abrupt("return", messageName);

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

  function checkClusterCode(_x2) {
    return _checkClusterCode.apply(this, arguments);
  }

  function _checkClusterCode() {
    _checkClusterCode = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(value) {
      var messageCode, pa;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              messageCode = true;

              if (!isEdit) {
                _context2.next = 3;
                break;
              }

              return _context2.abrupt("return", messageCode);

            case 3:
              pa = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;

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

              messageCode = "\u7F16\u7801".concat(formatMessage({
                id: "".concat(intlPrefix, ".check.failed")
              }));
              _context2.next = 10;
              break;

            case 8:
              _context2.next = 10;
              return mainStore.checkClusterCode({
                projectId: projectId,
                clusterCode: value
              }).then(function (res) {
                if (res && res.failed || !res) {
                  messageCode = formatMessage({
                    id: 'checkCodeExist'
                  });
                }
              })["catch"](function (e) {
                messageCode = formatMessage({
                  id: 'checkCodeFailed'
                });
              });

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

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

  return {
    autoCreate: false,
    autoQuery: false,
    selection: false,
    paging: false,
    dataKey: null,
    fields: [{
      name: 'name',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".name")
      }),
      required: true,
      maxLength: 30,
      validator: checkClusterName
    }, {
      name: 'code',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".code")
      }),
      required: true,
      maxLength: 30,
      validator: checkClusterCode
    }, {
      maxLength: 100,
      name: 'description',
      type: 'string',
      rows: 3,
      label: formatMessage({
        id: "".concat(intlPrefix, ".dec")
      })
    }],
    transport: {
      read: clusterId ? {
        url: "devops/v1/projects/".concat(projectId, "/clusters/").concat(clusterId),
        method: 'get'
      } : undefined,
      create: function create(_ref2) {
        var _ref2$data = _slicedToArray(_ref2.data, 1),
            data = _ref2$data[0];

        return {
          url: "/devops/v1/projects/".concat(projectId, "/clusters/activate"),
          method: 'post',
          data: JSON.stringify(data),
          transformResponse: function transformResponse(res) {
            try {
              var result = JSON.parse(res);
              return result;
            } catch (e) {
              if (handlePromptError(res)) {
                mainStore.setResponseData(res); // afterOk();
                // modal.close();
              }

              return res;
            }
          }
        };
      },
      update: function update(_ref3) {
        var _ref3$data = _slicedToArray(_ref3.data, 1),
            data = _ref3$data[0];

        return {
          url: "/devops/v1/projects/".concat(projectId, "/clusters/").concat(data.id, "?"),
          method: 'put',
          data: data
        };
      }
    },
    events: {
      load: function load(_ref4) {
        var dataSet = _ref4.dataSet;
        clusterName = dataSet.current.get('name');
      }
    }
  };
});