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

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 max-len */
import React, { useCallback, useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import map from 'lodash/map';
import NewTips from "../../../../../../../components/new-tips";
import YamlEditor from "../../../../../../../components/yamlEditor";
import { useFormStore } from "./stores";
var Option = _Select.Option;

function CreateNodesForm() {
  // const [nodeStore.getSelectedRecord, nodeStore.setSelectedRecord] = useState(null);
  var _useFormStore = useFormStore(),
      nodesDs = _useFormStore.nodesDs,
      afterOk = _useFormStore.afterOk,
      formatMessage = _useFormStore.formatMessage,
      intlPrefix = _useFormStore.intlPrefix,
      isEdit = _useFormStore.isEdit,
      nodesTypeDs = _useFormStore.nodesTypeDs,
      prefixCls = _useFormStore.prefixCls,
      modal = _useFormStore.modal,
      parentModal = _useFormStore.parentModal,
      nodeStore = _useFormStore.nodeStore,
      projectId = _useFormStore.projectId,
      createHostClusterMainStore = _useFormStore.createHostClusterMainStore,
      clusterId = _useFormStore.clusterId; // nodeStore.setSelectedRecord设置选中的record用来渲染用


  useEffect(function () {
    // 刚开始默认选中第一条数据
    nodesDs && nodesDs.data && nodeStore.setSelectedRecord(nodesDs.data[0]);
  }, [nodesDs]);

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

  function _handleSubmit() {
    _handleSubmit = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var result, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              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);
                };
              }());
              _context2.next = 3;
              return nodesDs.validate();

            case 3:
              result = _context2.sent;

              if (result) {
                _context2.next = 7;
                break;
              }

              // createHostClusterMainStore.setModalErrorMes('请完善节点信息');
              _message.error('请完善节点信息');

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

            case 7:
              _context2.prev = 7;
              _context2.next = 10;
              return nodesDs.submit();

            case 10:
              res = _context2.sent;

              if (!res) {
                _context2.next = 15;
                break;
              }

              modal.close();
              afterOk();
              return _context2.abrupt("return", true);

            case 15:
              return _context2.abrupt("return", false);

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

            case 21:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[7, 18]]);
    }));
    return _handleSubmit.apply(this, arguments);
  }

  function handleAddNewNode() {
    return _handleAddNewNode.apply(this, arguments);
  }

  function _handleAddNewNode() {
    _handleAddNewNode = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var record;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.next = 2;
              return nodesDs.create();

            case 2:
              record = _context3.sent;
              nodeStore.setSelectedRecord(record);
              document.querySelector("#node".concat(record.index)) && document.querySelector("#node".concat(record.index)).scrollIntoView({
                block: 'start',
                inline: 'nearest',
                behavior: 'smooth'
              });

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

  function handleRemove(record, index) {
    var _nodesDs$data;

    nodesDs.remove(record);

    if (((_nodesDs$data = nodesDs.data) === null || _nodesDs$data === void 0 ? void 0 : _nodesDs$data.length) && (record === null || record === void 0 ? void 0 : record.id) === nodeStore.getSelectedRecord.id) {
      var tempIndex = index > nodesDs.data.length - 1 ? index - 1 : index;
      nodeStore.setSelectedRecord(nodesDs.data[tempIndex]);
    }
  }

  var renderNodetypeOpts = useCallback(function (_ref) {
    var value = _ref.value,
        text = _ref.text;

    if (value === 'etcd') {
      return /*#__PURE__*/React.createElement("span", null, text);
    }

    return /*#__PURE__*/React.createElement("span", null, text);
  }, []);
  var renderRoleOpts = useCallback(function () {
    return map(nodesTypeDs && nodesTypeDs.toData(), function (item, index) {
      var value = item.value,
          text = item.text;

      if (value === 'etcd') {
        if (modal) return null;
        return /*#__PURE__*/React.createElement(Option, {
          value: value,
          key: "".concat(index, "-").concat(text)
        }, /*#__PURE__*/React.createElement("div", {
          style: {
            display: 'inline-flex',
            alignItems: 'center'
          }
        }, /*#__PURE__*/React.createElement("span", {
          style: {
            marginRight: '2px'
          }
        }, text), /*#__PURE__*/React.createElement(NewTips, {
          showHelp: true,
          helpText: "etcd\u7C7B\u578B\u7684\u8282\u70B9\u5EFA\u8BAE\u4E3A\u5355\u6570\uFF0C \u4EE5\u907F\u514D\u8111\u88C2"
        })));
      }

      return /*#__PURE__*/React.createElement(Option, {
        value: value,
        key: "".concat(index, "-").concat(text)
      }, /*#__PURE__*/React.createElement("span", null, text));
    });
  }, [nodesTypeDs]);
  modal && modal.handleOk(handleSubmit);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-nodesCreate"),
    style: {
      width: "".concat(modal ? '90%' : '100%')
    }
  }, !modal && /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-nodesCreate-left")
  }, /*#__PURE__*/React.createElement("main", null, map(nodesDs.data, function (nodesRecord, index) {
    var _nodeStore$getSelecte;

    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-nodesCreate-left-item \n                   ").concat((nodesRecord === null || nodesRecord === void 0 ? void 0 : nodesRecord.id) === ((_nodeStore$getSelecte = nodeStore.getSelectedRecord) === null || _nodeStore$getSelecte === void 0 ? void 0 : _nodeStore$getSelecte.id) && "".concat(prefixCls, "-nodesCreate-left-item-selected")),
      onClick: function onClick() {
        return nodeStore.setSelectedRecord(nodesRecord);
      },
      role: "none",
      id: "node".concat(index)
    }, /*#__PURE__*/React.createElement(_Form, {
      columns: 10,
      record: nodesRecord,
      key: nodesRecord.id
    }, /*#__PURE__*/React.createElement(_TextField, {
      name: "name",
      colSpan: nodesDs.data.length > 1 ? 7 : 9
    }), nodesDs.data.length > 1 && /*#__PURE__*/React.createElement(_Button, {
      funcType: "flat",
      icon: "delete",
      shape: "circle",
      colSpan: 2,
      style: {
        marginTop: '8px'
      },
      className: "".concat(prefixCls, "-nodesCreate-left-item-selected-btn"),
      onClick: function onClick(e) {
        e.stopPropagation();
        handleRemove(nodesRecord, index);
      }
    })), nodesRecord.get('hasError') && /*#__PURE__*/React.createElement(_Icon, {
      type: "info",
      className: "".concat(prefixCls, "-nodesCreate-left-item-errorIcon")
    }));
  })), /*#__PURE__*/React.createElement(_Button, {
    funcType: "flat",
    icon: "add",
    shape: "circle",
    color: "primary",
    onClick: handleAddNewNode,
    style: {
      marginLeft: '20px',
      marginTop: '10px'
    }
  }, "\u6DFB\u52A0\u8282\u70B9")), nodesDs.data.length && nodeStore.getSelectedRecord ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-nodesCreate-right"),
    style: {
      padding: modal ? 0 : '11px 20px'
    }
  }, /*#__PURE__*/React.createElement(_Form, {
    columns: 6,
    record: nodeStore.getSelectedRecord
  }, modal && /*#__PURE__*/React.createElement(_TextField, {
    name: "name",
    colSpan: 3
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "hostIp",
    colSpan: 3
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "hostPort",
    colSpan: 3
  }), /*#__PURE__*/React.createElement(_SelectBox, {
    name: "authType",
    colSpan: 6,
    className: "".concat(prefixCls, "-nodesCreate-right-authType"),
    newLine: !!modal
  }), /*#__PURE__*/React.createElement(_TextField, {
    name: "username",
    colSpan: 3
  }), nodeStore.getSelectedRecord && nodeStore.getSelectedRecord.get('authType') !== 'publickey' && /*#__PURE__*/React.createElement(_Password, {
    name: "password",
    reveal: false,
    colSpan: 3
  })), nodeStore.getSelectedRecord.get('authType') && nodeStore.getSelectedRecord.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: nodeStore.getSelectedRecord.get('password'),
    onValueChange: function onValueChange(valueYaml) {
      return nodeStore.getSelectedRecord.set('password', valueYaml);
    },
    modeChange: false,
    showError: false
  })), /*#__PURE__*/React.createElement(_Form, {
    columns: 6,
    record: nodeStore.getSelectedRecord
  }, /*#__PURE__*/React.createElement(_SelectBox, {
    name: "role",
    colSpan: 6,
    multiple: !modal,
    className: "".concat(prefixCls, "-nodesCreate-right-nodeType"),
    optionRenderer: renderNodetypeOpts
  }, renderRoleOpts()))) : ''));
}

export default observer(CreateNodesForm);