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

/* eslint-disable import/no-anonymous-default-export */
import HostConfigApis from "../../../apis";
import omit from 'lodash/omit';

function setStatus(record) {
  var isDefault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

  if (record) {
    var hostStatus = record.get('hostStatus');
    var jmeterStatus = record.get('jmeterStatus');
    var status = record.get('status');

    if (status && status !== 'wait' || isDefault) {
      // eslint-disable-next-line no-nested-ternary
      var newStatus = [hostStatus, jmeterStatus].includes('failed') ? 'failed' : hostStatus === 'success' && jmeterStatus === 'success' ? 'success' : 'operating';
      record.init('status', record.get('type') === 'deploy' ? hostStatus : newStatus);
    }
  }
}

function handleLoad(_ref) {
  var dataSet = _ref.dataSet,
      hostType = _ref.hostType;

  if (dataSet.current) {
    dataSet.current.init('type', hostType);
  }

  setStatus(dataSet.current, true);
}

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

  if (name === 'hostIp') {
    record.get('sshPort') && record.getField('sshPort').checkValidity();

    if (record.get('type') === 'distribute_test' && record.get('jmeterPort')) {
      record.getField('jmeterPort').checkValidity();
    }
  }

  if (name === 'type') {
    setStatus(record);
  }

  if (name === 'authType') {
    record.get('password') && record.set('password', null);
  }
}

export default (function (_ref3) {
  var formatMessage = _ref3.formatMessage,
      intlPrefix = _ref3.intlPrefix,
      projectId = _ref3.projectId,
      typeDs = _ref3.typeDs,
      accountDs = _ref3.accountDs,
      hostId = _ref3.hostId,
      showTestTab = _ref3.showTestTab,
      hostType = _ref3.hostType;

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

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

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

            case 2:
              if (!(value && value === record.getPristineValue(name))) {
                _context.next = 4;
                break;
              }

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

            case 4:
              if (!value) {
                _context.next = 17;
                break;
              }

              _context.prev = 5;
              _context.next = 8;
              return HostConfigApis.checkName(projectId, value, record.get('type'));

            case 8:
              res = _context.sent;

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

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

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

            case 14:
              _context.prev = 14;
              _context.t0 = _context["catch"](5);
              return _context.abrupt("return", formatMessage({
                id: 'checkNameFail'
              }));

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

            case 18:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[5, 14]]);
    }));
    return _checkName.apply(this, arguments);
  }

  function checkPortUnique(_x4, _x5, _x6, _x7) {
    return _checkPortUnique.apply(this, arguments);
  }

  function _checkPortUnique() {
    _checkPortUnique = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(ip, port, type, currentHostType) {
      var control, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              control = type === 'sshPort' ? HostConfigApis.checkSshPort : HostConfigApis.checkJmeterPort;
              _context2.next = 4;
              return control(projectId, ip, port, currentHostType);

            case 4:
              res = _context2.sent;
              return _context2.abrupt("return", res);

            case 8:
              _context2.prev = 8;
              _context2.t0 = _context2["catch"](0);
              return _context2.abrupt("return", false);

            case 11:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[0, 8]]);
    }));
    return _checkPortUnique.apply(this, arguments);
  }

  function checkIP(value) {
    var p = /^((\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/;

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

    return true;
  }

  function checkPort(_x8, _x9, _x10) {
    return _checkPort.apply(this, arguments);
  }

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

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

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

              if (!value) {
                _context3.next = 14;
                break;
              }

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

              if (!record.get('hostIp')) {
                _context3.next = 12;
                break;
              }

              _context3.next = 9;
              return checkPortUnique(record.get('hostIp'), value, name, record.get('type'));

            case 9:
              _context3.t0 = _context3.sent;

              if (!(_context3.t0 === false)) {
                _context3.next = 12;
                break;
              }

              return _context3.abrupt("return", formatMessage({
                id: "".concat(intlPrefix, ".port.unique.failed.").concat(name)
              }));

            case 12:
              return _context3.abrupt("return", true);

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

            case 14:
              return _context3.abrupt("return", true);

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

  function checkPrivatePort(value, name, record) {
    if (value && record.getPristineValue(name) && String(value) === String(record.getPristineValue(name))) {
      return true;
    }

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

    if (value && (!p.test(value) || parseInt(value, 10) < data.min || parseInt(value, 10) > data.max)) {
      return formatMessage({
        id: data.failedMsg
      });
    }

    return true;
  }

  return {
    autoCreate: false,
    selection: false,
    autoQueryAfterSubmit: false,
    paging: false,
    transport: {
      read: {
        url: HostConfigApis.getHostDetail(projectId, hostId, hostType),
        method: 'get'
      },
      create: function create(_ref4) {
        var _ref4$data = _slicedToArray(_ref4.data, 1),
            data = _ref4$data[0];

        var postData = omit(data, ['__status', '__id', 'status', 'jmeterStatus', 'hostStatus']);
        return {
          url: HostConfigApis.createHost(projectId, data.type),
          method: 'post',
          data: postData
        };
      },
      update: function update(_ref5) {
        var _ref5$data = _slicedToArray(_ref5.data, 1),
            data = _ref5$data[0];

        var postData = omit(data, ['__status', '__id', 'status', 'jmeterStatus', 'hostStatus']);
        return {
          url: HostConfigApis.editHost(projectId, hostId, data.type),
          method: 'put',
          data: postData
        };
      }
    },
    // @ts-ignore
    fields: [{
      name: 'type',
      type: 'string',
      textField: 'text',
      valueField: 'value',
      defaultValue: showTestTab ? 'distribute_test' : 'deploy',
      options: typeDs // label: formatMessage({ id: `${intlPrefix}.type` }),

    }, {
      name: 'name',
      type: 'string',
      maxLength: 15,
      required: true,
      validator: checkName,
      label: '主机名称'
    }, {
      name: 'hostIp',
      type: 'string',
      // @ts-ignore
      validator: checkIP,
      dynamicProps: {
        required: function required(_ref6) {
          var record = _ref6.record;
          return record.get('type') === 'distribute_test' || record.get('sshPort');
        },
        label: function label(_ref7) {
          var record = _ref7.record;
          return formatMessage({
            id: "".concat(intlPrefix, ".ip.").concat(record.get('type'))
          });
        }
      }
    }, {
      name: 'sshPort',
      validator: checkPort,
      label: formatMessage({
        id: "".concat(intlPrefix, ".port")
      }),
      dynamicProps: {
        required: function required(_ref8) {
          var record = _ref8.record;
          return record.get('type') === 'distribute_test' || record.get('hostIp');
        },
        label: function label(_ref9) {
          var record = _ref9.record;
          return formatMessage({
            id: "".concat(intlPrefix, ".port.").concat(record.get('type'))
          });
        }
      }
    }, {
      name: 'username',
      type: 'string',
      required: true,
      label: formatMessage({
        id: 'userName'
      })
    }, {
      name: 'password',
      type: 'string',
      required: true,
      dynamicProps: {
        label: function label(_ref10) {
          var record = _ref10.record;
          return formatMessage({
            id: record.get('authType') === 'accountPassword' ? 'password' : "".concat(intlPrefix, ".token")
          });
        }
      }
    }, {
      name: 'authType',
      type: 'string',
      textField: 'text',
      valueField: 'value',
      required: true,
      defaultValue: 'accountPassword',
      options: accountDs,
      label: formatMessage({
        id: "".concat(intlPrefix, ".account")
      })
    }, {
      name: 'jmeterPort',
      type: 'string',
      dynamicProps: {
        required: function required(_ref11) {
          var record = _ref11.record;
          return record.get('type') === 'distribute_test';
        },
        validator: function validator(_ref12) {
          var record = _ref12.record;
          return record.get('type') === 'distribute_test' && checkPort;
        }
      },
      label: formatMessage({
        id: "".concat(intlPrefix, ".jmeter.port")
      })
    }, {
      name: 'jmeterPath',
      type: 'string',
      pattern: /^(\/[\w\W]+)+$/,
      dynamicProps: {
        required: function required(_ref13) {
          var record = _ref13.record;
          return record.get('type') === 'distribute_test';
        }
      },
      label: formatMessage({
        id: "".concat(intlPrefix, ".jmeter.path")
      })
    }, {
      name: 'privateIp',
      type: 'string',
      label: formatMessage({
        id: "".concat(intlPrefix, ".ip.private")
      }),
      dynamicProps: {
        required: function required(_ref14) {
          var record = _ref14.record;
          return record.get('type') === 'deploy' && record.get('privatePort');
        },
        validator: function validator(_ref15) {
          var record = _ref15.record;
          return record.get('type') === 'deploy' && checkIP;
        }
      }
    }, {
      name: 'privatePort',
      label: formatMessage({
        id: "".concat(intlPrefix, ".port.private")
      }),
      dynamicProps: {
        required: function required(_ref16) {
          var record = _ref16.record;
          return record.get('type') === 'deploy' && record.get('privateIp');
        },
        validator: function validator(_ref17) {
          var record = _ref17.record;
          return record.get('type') === 'deploy' && checkPrivatePort;
        }
      }
    }],
    events: {
      load: function load(loadProps) {
        return handleLoad(_objectSpread(_objectSpread({}, loadProps), {}, {
          hostType: hostType
        }));
      },
      update: handleUpdate
    }
  };
});