import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/password/style";
import _Password from "choerodon-ui/pro/lib/password";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/pro/lib/select-box/style";
import _SelectBox from "choerodon-ui/pro/lib/select-box";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(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); }); }; }

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

/* eslint-disable max-len */
import React, { useEffect, useMemo, useState, useCallback } from 'react';
import { observer } from 'mobx-react-lite';
import Tips from "../../../../../../../components/new-tips";
import { map, pick, without } from 'lodash';
import { Base64 } from 'js-base64';
import YamlEditor from "../../../../../../../components/yamlEditor";
import TestConnect from "../test-connect";
import "./index.less";
var Option = _Select.Option;
var PublicNode = observer(function (props) {
  var prefixCls = props.prefixCls,
      publicNodeDs = props.publicNodeDs,
      parentModal = props.parentModal,
      createHostClusterMainStore = props.createHostClusterMainStore,
      projectId = props.projectId,
      nodesDs = props.nodesDs;
  var connectFields = useMemo(function () {
    return ['hostIp', 'hostPort', 'authType', 'username', 'password'];
  }, []);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      expand = _useState2[0],
      changeExpand = _useState2[1];

  useEffect(function () {}, []);

  function checkConnectValidate() {
    return _checkConnectValidate.apply(this, arguments);
  }

  function _checkConnectValidate() {
    _checkConnectValidate = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var hasIp, hasPort, hasAccountType, hasUsername, hasPassword;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.t0 = publicNodeDs.current;

              if (!_context.t0) {
                _context.next = 5;
                break;
              }

              _context.next = 4;
              return publicNodeDs.current.getField('hostIp').checkValidity();

            case 4:
              _context.t0 = _context.sent;

            case 5:
              hasIp = _context.t0;
              _context.t1 = publicNodeDs.current;

              if (!_context.t1) {
                _context.next = 11;
                break;
              }

              _context.next = 10;
              return publicNodeDs.current.getField('hostPort').checkValidity();

            case 10:
              _context.t1 = _context.sent;

            case 11:
              hasPort = _context.t1;
              _context.t2 = publicNodeDs.current;

              if (!_context.t2) {
                _context.next = 17;
                break;
              }

              _context.next = 16;
              return publicNodeDs.current.getField('authType').checkValidity();

            case 16:
              _context.t2 = _context.sent;

            case 17:
              hasAccountType = _context.t2;
              _context.t3 = publicNodeDs.current;

              if (!_context.t3) {
                _context.next = 23;
                break;
              }

              _context.next = 22;
              return publicNodeDs.current.getField('username').checkValidity();

            case 22:
              _context.t3 = _context.sent;

            case 23:
              hasUsername = _context.t3;
              _context.t4 = publicNodeDs.current;

              if (!_context.t4) {
                _context.next = 29;
                break;
              }

              _context.next = 28;
              return publicNodeDs.current.getField('password').checkValidity();

            case 28:
              _context.t4 = _context.sent;

            case 29:
              hasPassword = _context.t4;
              return _context.abrupt("return", hasIp && hasPort && hasAccountType && hasUsername && hasPassword);

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

  function setConnectFieldDisabeld() {
    connectFields.forEach(function (item) {
      publicNodeDs.current.getField(item).set('disabled', true);
    });
  }

  function setConnectFieldEnabled() {
    connectFields.forEach(function (item) {
      publicNodeDs.current.getField(item).set('disabled', false);
    });
  }

  function setParentModalEnabled(value) {
    if (typeof value === 'boolean') {
      parentModal && parentModal.update({
        okProps: {
          loading: value
        },
        cancelProps: {
          disabled: value
        }
      });
    }
  }

  function handleTestConnection() {
    return _handleTestConnection.apply(this, arguments);
  }

  function _handleTestConnection() {
    _handleTestConnection = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var validate, data, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return checkConnectValidate();

            case 2:
              validate = _context2.sent;

              if (!(!validate || !publicNodeDs)) {
                _context2.next = 5;
                break;
              }

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

            case 5:
              publicNodeDs.current.set('status', 'operating'); // 再进行节点的连接测试的时候需要去把父组件传过来的modal给禁用不让他关闭

              setParentModalEnabled(true); // 然后禁用那些框

              setConnectFieldDisabeld();
              data = pick(publicNodeDs.toData()[0], ['hostPort', 'password', 'hostIp', 'username', 'authType']);

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

              _context2.prev = 10;
              _context2.next = 13;
              return createHostClusterMainStore.checkNodeConnect(projectId, data);

            case 13:
              res = _context2.sent;
              setParentModalEnabled(false);

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

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

            case 17:
              publicNodeDs.current.set('status', res ? 'success' : 'failed');
              _context2.next = 25;
              break;

            case 20:
              _context2.prev = 20;
              _context2.t0 = _context2["catch"](10);
              publicNodeDs.current.set('status', 'linkError');
              setConnectFieldEnabled();
              setParentModalEnabled(false);

            case 25:
              // 若请求失败了，则把框警用取消
              setConnectFieldEnabled();
              setParentModalEnabled(false);
              return _context2.abrupt("return", true);

            case 28:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[10, 20]]);
    }));
    return _handleTestConnection.apply(this, arguments);
  }

  var renderLinkStatusMes = useCallback(function () {
    var status = publicNodeDs.current && publicNodeDs.current.get('status');
    var mes;

    switch (status) {
      case 'wait':
        mes = '请进行连接检测。';
        break;

      case 'linkError':
        mes = '连接异常，请重新进行连接检测。';
        break;

      default:
        break;
    }

    return /*#__PURE__*/React.createElement("span", null, mes);
  }, [publicNodeDs.current]);

  function checkHasAllConnectFieldsFilled() {
    var tempObj = publicNodeDs.toData()[0];
    var tempArr;
    var hasInnerNode = publicNodeDs.current.get('isInnerNode');

    if (hasInnerNode) {
      tempArr = ['hostIp', 'hostPort', 'username', 'password', 'authType', 'innerNodeName'];
    } else {
      tempArr = ['hostIp', 'hostPort', 'username', 'password', 'authType'];
    }

    var differArr = without.apply(void 0, [tempArr].concat(_toConsumableArray(Object.keys(tempObj))));

    if (differArr.length === 0) {
      return true;
    }

    return false;
  }

  var renderNodeOpts = useCallback(function () {
    if (!nodesDs.length) {
      return null;
    }

    return map(nodesDs.data, function (record) {
      return record.get('name') && /*#__PURE__*/React.createElement(Option, {
        value: record.get('name')
      }, record.get('name'));
    });
  }, [nodesDs]);
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-clusterPublicNode")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-clusterPublicNode-header")
  }, /*#__PURE__*/React.createElement(_Button, {
    size: "small",
    icon: !expand ? 'expand_more' : 'expand_less',
    onClick: function onClick() {
      return changeExpand(!expand);
    }
  }), /*#__PURE__*/React.createElement("span", null, "\u516C\u7F51\u8282\u70B9\u914D\u7F6E"), /*#__PURE__*/React.createElement(Tips, {
    helpText: "\u82E5\u96C6\u7FA4\u8282\u70B9\u53EF\u4EE5\u901A\u8FC7\u516C\u7F51\u8BBF\u95EE\uFF0C\u8BE5\u914D\u7F6E\u53EF\u4EE5\u4E0D\u586B\u3002\u82E5\u96C6\u7FA4\u8282\u70B9\u5904\u4E8E\u5185\u7F51\u73AF\u5883\u65F6\uFF0Cdevops\u5C06\u901A\u8FC7\u8FDE\u63A5\u516C\u7F51\u8282\u70B9\u95F4\u63A5\u5BF9\u96C6\u7FA4\u8282\u70B9\u8FDB\u884C\u64CD\u4F5C\uFF0C\u6B64\u65F6\u987B\u914D\u7F6E\u516C\u7F51\u8282\u70B9\u3002"
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-clusterPublicNode-form"),
    style: {
      display: expand ? 'block' : 'none'
    }
  }, /*#__PURE__*/React.createElement(_Form, {
    dataSet: publicNodeDs,
    columns: 6
  }, /*#__PURE__*/React.createElement(_SelectBox, {
    name: "isInnerNode",
    colSpan: 6,
    className: "".concat(prefixCls, "-nodesCreate-right-authType")
  }, /*#__PURE__*/React.createElement(Option, {
    value: true
  }, "\u662F"), /*#__PURE__*/React.createElement(Option, {
    value: false
  }, "\u5426")), publicNodeDs.current.get('isInnerNode') && /*#__PURE__*/React.createElement(_Select, {
    name: "innerNodeName",
    colSpan: 2
  }, renderNodeOpts()), /*#__PURE__*/React.createElement(_TextField, {
    name: "hostIp",
    colSpan: publicNodeDs.current.get('isInnerNode') ? 2 : 3
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "hostPort",
    colSpan: publicNodeDs.current.get('isInnerNode') ? 2 : 3
  }), /*#__PURE__*/React.createElement(_SelectBox, {
    name: "authType",
    colSpan: 6,
    className: "".concat(prefixCls, "-nodesCreate-right-authType")
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "username",
    colSpan: 3
  }), publicNodeDs.current && publicNodeDs.current.get('authType') !== 'publickey' && /*#__PURE__*/React.createElement(_Password, {
    name: "password",
    reveal: false,
    colSpan: 3
  })), publicNodeDs.current.get('authType') && publicNodeDs.current.get('authType') === 'publickey' && /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-clusterPublicNode-form-yaml")
  }, /*#__PURE__*/React.createElement("span", null, "\u5BC6\u94A5"), /*#__PURE__*/React.createElement(YamlEditor, {
    readOnly: false,
    newLine: true // value={publicNodeDs.current.get('password')}
    ,
    onValueChange: function onValueChange(valueYaml) {
      publicNodeDs.current.set('password', valueYaml);
    },
    modeChange: false,
    showError: false
  }), /*#__PURE__*/React.createElement("span", null, "\u8BF7\u8F93\u5165\u5BC6\u94A5\u3002")), publicNodeDs && checkHasAllConnectFieldsFilled() && /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-clusterPublicNode-connect ").concat(['wait', 'linkError'].includes(publicNodeDs.current.get('status')) && "".concat(prefixCls, "-clusterPublicNode-connect-uncheck"))
  }, /*#__PURE__*/React.createElement(TestConnect, {
    handleTestConnection: handleTestConnection,
    nodeRecord: publicNodeDs.current
  }), renderLinkStatusMes())));
});
export default PublicNode;