import "choerodon-ui/pro/lib/form/style";
import _Form from "@hzero-front-ui/c7n-ui/lib/FormPro";
import "choerodon-ui/pro/lib/text-area/style";
import _TextArea from "choerodon-ui/pro/lib/text-area";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/pro/lib/message/style";
import _message from "choerodon-ui/pro/lib/message";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";

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

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import Tips from "../../../../../../../components/new-tips";
import { forEach, toUpper } from 'lodash';
import { useFormStore } from "./stores";
import NodesCreate from "../create-nodes";
import NodePublicCreate from "../create-public-node";
import TestConnectFinal from "./components/test-connect-final";
var confirmModal;
var timer;

function CreateClusterHostForm() {
  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      connectObj = _useState2[0],
      setConnectObj = _useState2[1];

  var _useFormStore = useFormStore(),
      modal = _useFormStore.modal,
      formDs = _useFormStore.formDs,
      nodesDs = _useFormStore.nodesDs,
      nodesTypeDs = _useFormStore.nodesTypeDs,
      formatMessage = _useFormStore.formatMessage,
      intlPrefix = _useFormStore.intlPrefix,
      isEdit = _useFormStore.isEdit,
      prefixCls = _useFormStore.prefixCls,
      clusterByHostStore = _useFormStore.clusterByHostStore,
      projectId = _useFormStore.projectId,
      createHostClusterMainStore = _useFormStore.createHostClusterMainStore,
      publicNodeDs = _useFormStore.publicNodeDs,
      afterOk = _useFormStore.afterOk;

  useEffect(function () {
    return function () {
      timer && clearInterval(timer);
    };
  }, []); // if (isEdit) {
  //   formDs.query();
  // }

  var openNoticeEvenModal = function openNoticeEvenModal() {
    confirmModal = _Modal.open({
      key: _Modal.key(),
      title: '注意',
      children: '您创建的集群中Etcd类型节点为偶数个，Etcd官方建议Etcd集群服务器个数为奇数个（比如1、3、5）以防止脑裂',
      cancelProps: {
        color: 'dark'
      },
      footer: function footer(okbtn, cancelBtn) {
        return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(_Button, {
          color: "dark",
          onClick: function onClick() {
            confirmModal.close();
          }
        }, "\u8FD4\u56DE\u4FEE\u6539"), /*#__PURE__*/React.createElement(_Button, {
          color: "red",
          onClick: function onClick() {
            confirmModal.close();
            postMainData();
          },
          style: {
            marginLeft: '34px'
          }
        }, "\u4ECD\u7136\u521B\u5EFA"));
      }
    });
  };

  function checkHasAllNodeType() {
    var _ref = formDs && formDs.children,
        devopsClusterInnerNodeVOList = _ref.devopsClusterInnerNodeVOList;

    var mainData = devopsClusterInnerNodeVOList && devopsClusterInnerNodeVOList.toData();
    var nodeHasObj = {
      master: false,
      etcd: false,
      worker: false
    };
    forEach(mainData, function (item) {
      var nodeTypesArr = item === null || item === void 0 ? void 0 : item.role;

      if (nodeTypesArr) {
        for (var key in nodeHasObj) {
          if (!nodeHasObj[key] && nodeTypesArr.includes(key)) {
            nodeHasObj[key] = true;
          }
        }
      }
    });
    return nodeHasObj.master && nodeHasObj.etcd && nodeHasObj.worker;
  }

  function checkNodesEtcdIsEven(tempArr) {
    var num = 0;

    if (tempArr && tempArr.length) {
      forEach(tempArr, function (item) {
        if (item === null || item === void 0 ? void 0 : item.role.includes('etcd')) {
          num += 1;
        }
      });
    } // 判断是否为奇数


    return !!(num % 2);
  }

  function checkNodeHasError() {
    nodesDs.forEach( /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(nodeRecord) {
        var res;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return nodeRecord.validate();

              case 2:
                res = _context.sent;

                if (!res) {
                  nodeRecord.set('hasError', true);
                }

              case 4:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

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

  function modalUpDateLoadingFalse() {
    modal.update({
      cancelProps: {
        disabled: false
      },
      okProps: {
        loading: false
      }
    });
  }

  function modalUpDateLoadingTrue() {
    modal.update({
      cancelProps: {
        disabled: true
      },
      okProps: {
        loading: true
      }
    });
  }

  function scrollTimer() {
    document.querySelector('#loadingProgress') && document.querySelector('#loadingProgress').scrollIntoView({
      block: 'start',
      inline: 'nearest',
      behavior: 'smooth'
    });
  } // 所有节点检测连通性


  function goTimerConnect(clusterString) {
    timer = setInterval( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var nodeStatusRes, _nodeStatusRes, status;

      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              _context2.next = 3;
              return clusterByHostStore.checkConnect(projectId, clusterString);

            case 3:
              nodeStatusRes = _context2.sent;

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

              if (timer) clearInterval(timer);
              setConnectObj(null);
              modalUpDateLoadingFalse();
              return _context2.abrupt("return", false);

            case 9:
              _nodeStatusRes = nodeStatusRes, status = _nodeStatusRes.status;
              setConnectObj(nodeStatusRes);
              scrollTimer(); // 如果状态成功,

              if (status === 'success') {
                clearInterval(timer);
                setTimeout(function () {
                  modal.close();
                  afterOk();
                }, 2000);
              } // 如果失败


              if (status === 'failed') {
                clearInterval(timer);

                _message.error('测试节点连通性失败'); // 清除loading和disabled


                modalUpDateLoadingFalse();
              }

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

            case 17:
              _context2.prev = 17;
              _context2.t0 = _context2["catch"](0);
              if (timer) clearInterval(timer);
              scrollTimer();
              setConnectObj(null); // 清除loading和disabled

              modalUpDateLoadingFalse();
              return _context2.abrupt("return", true);

            case 24:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[0, 17]]);
    })), 2000);
  }

  function postMainData() {
    return _postMainData.apply(this, arguments);
  } // eslint-disable-next-line consistent-return


  function _postMainData() {
    _postMainData = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var res;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.prev = 0;
              // 首先让弹窗loading
              modalUpDateLoadingTrue(); // 先把数据发给后端

              _context3.next = 4;
              return formDs.submit();

            case 4:
              res = _context3.sent;

              if (!(typeof res === 'object' && res.failed)) {
                _context3.next = 8;
                break;
              }

              modalUpDateLoadingFalse();
              return _context3.abrupt("return", res);

            case 8:
              if (!res) {
                _context3.next = 12;
                break;
              }

              modalUpDateLoadingTrue(); // 开始检测节点的连通性

              goTimerConnect(res[0].clusterString);
              return _context3.abrupt("return", true);

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

            case 15:
              _context3.prev = 15;
              _context3.t0 = _context3["catch"](0);
              modalUpDateLoadingFalse();
              return _context3.abrupt("return", true);

            case 19:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[0, 15]]);
    }));
    return _postMainData.apply(this, arguments);
  }

  function handleSubmit() {
    return _handleSubmit.apply(this, arguments);
  }

  function _handleSubmit() {
    _handleSubmit = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      var result, mainData, hasAllNodeTypes, isEven;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              // 为了在界面上的后面显示出没有检验通过的record
              checkNodeHasError();
              _context4.next = 3;
              return formDs.validate();

            case 3:
              result = _context4.sent;

              if (!result) {
                _message.error('请检查集群信息'); // createHostClusterMainStore.setModalErrorMes('请检查集群信息');

              }

              if (!result) {
                _context4.next = 16;
                break;
              }

              mainData = formDs.toData()[0];
              hasAllNodeTypes = checkHasAllNodeType(); // 首先需要校验创建集群时，需至少包含1个master+1个etcd+1个worker类型的节点。

              if (hasAllNodeTypes) {
                _context4.next = 11;
                break;
              }

              _message.error('创建集群时，需至少包含1个master+1个etcd+1个worker类型的节点。');

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

            case 11:
              isEven = checkNodesEtcdIsEven((mainData === null || mainData === void 0 ? void 0 : mainData.devopsClusterInnerNodeVOList) || []); // 这个时候检验etcd的节点个数，偶数的话就会弹窗告诉你东西

              if (isEven) {
                _context4.next = 15;
                break;
              }

              openNoticeEvenModal();
              return _context4.abrupt("return", false);

            case 15:
              // 之后去把数据发给后端
              postMainData();

            case 16:
              return _context4.abrupt("return", false);

            case 17:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));
    return _handleSubmit.apply(this, arguments);
  }

  modal.handleOk(handleSubmit);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-createByHost")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-createByHost-headerForm")
  }, /*#__PURE__*/React.createElement(_Form, {
    dataSet: formDs,
    columns: 6
  }, /*#__PURE__*/React.createElement(_TextField, {
    name: "name",
    colSpan: 2
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "code",
    disabled: isEdit,
    colSpan: 2
  }), /*#__PURE__*/React.createElement(_TextArea, {
    newLine: true,
    colSpan: 4,
    className: "".concat(prefixCls, "-createByHost-headerForm-desc"),
    name: "description",
    resize: "vertical"
  }))), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-createByHost-section")
  }, /*#__PURE__*/React.createElement("header", null, /*#__PURE__*/React.createElement("span", null, "\u8282\u70B9\u914D\u7F6E"), /*#__PURE__*/React.createElement(Tips, {
    helpText: "\u96C6\u7FA4\u4E2D\u987B\u81F3\u5C11\u542B\u67091\u4E2Amaster\u8282\u70B9+1\u4E2Aetcd\u8282\u70B9+1\u4E2Aworker\u8282\u70B9"
  })), /*#__PURE__*/React.createElement(NodesCreate, {
    prefixCls: prefixCls,
    formatMessage: formatMessage,
    intlPrefix: intlPrefix,
    nodesTypeDs: nodesTypeDs,
    nodesDs: nodesDs,
    parentModal: modal
  })), /*#__PURE__*/React.createElement(NodePublicCreate, {
    prefixCls: prefixCls,
    formatMessage: formatMessage,
    intlPrefix: intlPrefix,
    parentModal: modal,
    publicNodeDs: publicNodeDs,
    nodesDs: nodesDs,
    createHostClusterMainStore: createHostClusterMainStore,
    projectId: projectId
  }), connectObj && /*#__PURE__*/React.createElement(TestConnectFinal, {
    connectRecord: connectObj
  })));
}

export default observer(CreateClusterHostForm);