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 { omit } from 'lodash';
import { Base64 } from 'js-base64';

function nameValidator(dataSet) {
  dataSet.forEach(function (eachRecord) {
    return eachRecord.getField('name').checkValidity();
  });
}

function ipValidator(dataSet) {
  dataSet.forEach(function (eachRecord) {
    return eachRecord.getField('hostIp').checkValidity();
  });
}

function handleRemove(_ref) {
  var dataSet = _ref.dataSet;
  nameValidator(dataSet);
  ipValidator(dataSet);
}

export default (function (_ref2) {
  var accountDs = _ref2.accountDs,
      formatMessage = _ref2.formatMessage,
      intlPrefix = _ref2.intlPrefix,
      isModal = _ref2.isModal,
      createHostClusterStore = _ref2.createHostClusterStore,
      clusterId = _ref2.clusterId,
      projectId = _ref2.projectId;

  // 校验是否有重复的名字以及校验是否通过名字限制
  function checkoutHasParamName(value, name, record) {
    var p = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$/;

    if (value && !p.test(value)) {
      return formatMessage({
        id: "".concat(intlPrefix, ".node.name.failed")
      });
    }

    var ds = record.dataSet;
    var hasRepeatName = ds.some(function (tempRecord) {
      var headerName = tempRecord.get('name');
      var recordName = record.get('name');
      var isEqual = headerName && recordName && headerName === recordName;
      return tempRecord.id !== record.id && isEqual;
    });

    if (hasRepeatName) {
      // record.getField('value').set('disabled', true);
      return '存在重复节点名称';
    } // record.getField('value').set('disabled', false);


    return true;
  }

  function checkPort(_x, _x2, _x3) {
    return _checkPort.apply(this, arguments);
  }

  function _checkPort() {
    _checkPort = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(value, name, record) {
      var p, data;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(value && record.getPristineValue(name) && String(value) === String(record.getPristineValue(name)))) {
                _context.next = 2;
                break;
              }

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

            case 2:
              p = /^([1-9]\d*|0)$/;
              data = {
                typeMsg: '',
                min: 1,
                max: 65535,
                failedMsg: "".concat(intlPrefix, ".port.check.failed")
              };

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

              if (!(p.test(value) && parseInt(value, 10) >= data.min && parseInt(value, 10) <= data.max)) {
                _context.next = 7;
                break;
              }

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

            case 7:
              return _context.abrupt("return", formatMessage({
                id: data.failedMsg
              }));

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

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

  function checkoutHasSameIP(value, name, record) {
    var p = /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/;

    if (value && !p.test(value)) {
      return formatMessage({
        id: 'network.ip.check.failed'
      });
    } // return true;


    var ds = record.dataSet;
    var hasRepeatIP = ds.some(function (tempRecord) {
      var headerName = tempRecord.get('hostIp');
      var recordName = record.get('hostIp');
      var isEqual = headerName && recordName && headerName === recordName;
      return tempRecord.id !== record.id && isEqual;
    });

    if (hasRepeatIP) {
      // record.getField('value').set('disabled', true);
      return '存在重复的节点IP';
    } // record.getField('value').set('disabled', false);


    return true;
  }

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

  function _handleUpdate() {
    _handleUpdate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(_ref3) {
      var dataSet, record, name, value, oldValue, hasWorker, hasMaster, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              dataSet = _ref3.dataSet, record = _ref3.record, name = _ref3.name, value = _ref3.value, oldValue = _ref3.oldValue;

              // 新建的时候是多选框，有这个节点校验规则，但是独立添加node的弹窗就是单选就跳过这个规则
              if (!isModal && name === 'role') {
                if (!(oldValue === null || oldValue === void 0 ? void 0 : oldValue.length) && (value === null || value === void 0 ? void 0 : value.length) === 1 && value[0] === 'etcd') {
                  record.set('role', ['etcd', 'worker']);
                }

                if ((oldValue === null || oldValue === void 0 ? void 0 : oldValue.length) === 2 && (oldValue === null || oldValue === void 0 ? void 0 : oldValue.includes('etcd'))) {
                  hasWorker = (oldValue === null || oldValue === void 0 ? void 0 : oldValue.includes('worker')) && !(value === null || value === void 0 ? void 0 : value.includes('worker'));
                  hasMaster = (oldValue === null || oldValue === void 0 ? void 0 : oldValue.includes('master')) && !(value === null || value === void 0 ? void 0 : value.includes('master'));

                  if (hasWorker || hasMaster) {
                    record.set('role', ['etcd', 'worker']);
                  }
                }
              }

              if (name === 'name') {
                nameValidator(dataSet);
              }

              if (name === 'hostIp') {
                ipValidator(dataSet);
              } // 当已经有错误的时候，更新值重新校验并且去除hasError字段以及清空错误消息


              if (!record.get('hasError')) {
                _context2.next = 9;
                break;
              }

              _context2.next = 7;
              return record.validate();

            case 7:
              res = _context2.sent;

              if (res) {
                record.set('hasError', false);
              }

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

  return {
    autoCreate: true,
    events: {
      update: handleUpdate,
      remove: handleRemove
    },
    transport: {
      create: clusterId ? function (_ref4) {
        var _ref4$data = _slicedToArray(_ref4.data, 1),
            data = _ref4$data[0];

        return {
          url: "devops/v1/projects/".concat(projectId, "/nodes?cluster_id=").concat(clusterId),
          method: 'post',
          transformRequest: function transformRequest(value) {
            var tempObj = value ? value[0] : {};
            tempObj.role = tempObj.role === 'worker' ? 1 : 4;

            if (tempObj.authType === 'publickey') {
              tempObj.password = Base64.encode(tempObj.password);
            }

            return JSON.stringify(omit(tempObj, ['__id', '__status', 'hasError', 'status']));
          }
        };
      } : undefined
    },
    fields: [{
      name: 'name',
      type: 'string',
      label: '节点名称',
      maxLength: 30,
      required: true,
      validator: checkoutHasParamName
    }, {
      name: 'hostIp',
      type: 'string',
      label: '节点IP',
      required: true,
      validator: checkoutHasSameIP
    }, {
      name: 'hostPort',
      type: 'string',
      label: '端口',
      required: true,
      validator: checkPort
    }, {
      name: 'authType',
      type: 'string',
      label: '账号配置',
      textField: 'text',
      valueField: 'value',
      required: true,
      defaultValue: 'accountPassword',
      options: accountDs
    }, {
      name: 'username',
      type: 'string',
      label: '用户名',
      required: true
    }, {
      name: 'password',
      type: 'string',
      required: true,
      dynamicProps: {
        label: function label(_ref5) {
          var record = _ref5.record;
          return formatMessage({
            id: record.get('authType') === 'accountPassword' ? 'password' : "".concat(intlPrefix, ".nodesCreate.token")
          });
        }
      }
    }, {
      name: 'role',
      type: 'string',
      label: '节点类型',
      textField: 'text',
      valueField: 'value',
      defaultValue: isModal ? 'worker' : [],
      required: true
    }, {
      name: 'type',
      type: 'string',
      defaultValue: 'inner'
    }]
  };
});