import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
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); }); }; }

import React from 'react';
import map from 'lodash/map';
import { Choerodon } from '@choerodon/boot';
import { observer } from 'mobx-react-lite';
import { useClusterMainStore } from "../../../stores";
import { useClusterContentStore } from "../stores";
import MonitorCreate from "./monitor-create";
import ComponentCard from "./card";
import Progress from "./progress";
import { handlePromptError } from "../../../../../../utils";
import "./index.less";

var monitorInstallKey = _Modal.key();

var monitorUninstallKey = _Modal.key();

var certUninstallKey = _Modal.key();

var modalStyle = {
  width: 380
};
export default observer(function (props) {
  var _useClusterMainStore = useClusterMainStore(),
      intlPrefix = _useClusterMainStore.intlPrefix,
      prefixCls = _useClusterMainStore.prefixCls,
      ClusterDetailDs = _useClusterMainStore.ClusterDetailDs;

  var _useClusterContentSto = useClusterContentStore(),
      formatMessage = _useClusterContentSto.formatMessage,
      contentStore = _useClusterContentSto.contentStore,
      projectId = _useClusterContentSto.projectId,
      clusterId = _useClusterContentSto.clusterId;

  function getClusterConnect() {
    return ClusterDetailDs.current.get('connect');
  }

  function getContent() {
    var getComponentList = contentStore.getComponentList;
    var length = getComponentList.length;
    var content = map(getComponentList, function (_ref, index) {
      var message = _ref.message,
          type = _ref.type,
          status = _ref.status,
          operate = _ref.operate;
      var componentType = type === 'prometheus' ? 'monitor' : 'cert';
      return /*#__PURE__*/React.createElement(ComponentCard, {
        key: type,
        className: index !== length - 1 ? "".concat(prefixCls, "-component-wrap-card") : '',
        name: formatMessage({
          id: "".concat(intlPrefix, ".component.").concat(componentType)
        }),
        describe: formatMessage({
          id: "".concat(intlPrefix, ".component.").concat(componentType, ".des")
        }),
        buttonData: getButtonData(type, status, operate, message),
        status: status,
        errorMessage: message,
        progress: type === 'prometheus' && status === 'processing' && operate !== 'uninstall' ? /*#__PURE__*/React.createElement(Progress, {
          refresh: refresh
        }) : null
      });
    });
    return content;
  }

  function getButtonData(type, status, operate, message) {
    var disabled = !getClusterConnect();
    var buttonData = [];

    if (type === 'prometheus') {
      switch (status) {
        case 'uninstalled':
          buttonData = [{
            text: formatMessage({
              id: 'install'
            }),
            onClick: function onClick() {
              return installMonitor(message ? 'edit' : 'create', true);
            },
            disabled: disabled,
            loading: false
          }];
          break;

        case 'processing':
          if (operate === 'install') {
            buttonData = [{
              text: formatMessage({
                id: 'install'
              }),
              loading: true
            }];
          } else {
            buttonData = [{
              text: formatMessage({
                id: 'edit'
              }),
              loading: operate === 'upgrade',
              onClick: function onClick() {
                return installMonitor('edit');
              },
              disabled: true
            }, {
              text: formatMessage({
                id: 'uninstall'
              }),
              loading: operate !== 'upgrade',
              disabled: true
            }];
          }

          break;

        case 'available':
        case 'disabled':
          buttonData = [{
            text: formatMessage({
              id: 'edit'
            }),
            onClick: function onClick() {
              return installMonitor('edit');
            },
            disabled: disabled,
            loading: false
          }, {
            text: formatMessage({
              id: 'uninstall'
            }),
            onClick: uninstallMonitor,
            disabled: disabled,
            loading: false
          }];
          break;

        default:
      }
    } else {
      switch (status) {
        case 'uninstalled':
          buttonData = [{
            text: formatMessage({
              id: 'install'
            }),
            onClick: handleInstallCert,
            disabled: disabled,
            loading: false
          }];
          break;

        case 'processing':
          if (operate === 'install') {
            buttonData = [{
              text: formatMessage({
                id: 'install'
              }),
              loading: true
            }];
          } else {
            buttonData = [{
              text: formatMessage({
                id: 'uninstall'
              }),
              loading: true
            }];
          }

          break;

        case 'available':
        case 'disabled':
          buttonData = [{
            text: formatMessage({
              id: 'uninstall'
            }),
            onClick: uninstallCert,
            disabled: disabled,
            loading: false
          }];
          break;

        default:
      }
    }

    return buttonData;
  }

  function refresh() {
    contentStore.loadComponentList(projectId, clusterId);
  }

  function handleInstallCert() {
    return _handleInstallCert.apply(this, arguments);
  }

  function _handleInstallCert() {
    _handleInstallCert = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return contentStore.installCertManager(projectId, clusterId);

            case 2:
              if (!_context.sent) {
                _context.next = 4;
                break;
              }

              refresh();

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

  function installMonitor(type) {
    var showPassword = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

    _Modal.open({
      key: monitorInstallKey,
      style: modalStyle,
      drawer: true,
      title: formatMessage({
        id: "".concat(intlPrefix, ".monitor.").concat(type)
      }),
      children: /*#__PURE__*/React.createElement(MonitorCreate, {
        prefixCls: prefixCls,
        intlPrefix: intlPrefix,
        refresh: refresh,
        type: type,
        clusterId: clusterId,
        showPassword: showPassword
      }),
      okText: formatMessage({
        id: type === 'edit' ? 'save' : 'install'
      })
    });
  }

  function uninstallMonitor() {
    _Modal.open({
      key: monitorUninstallKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".monitor.uninstall")
      }),
      children: formatMessage({
        id: "".concat(intlPrefix, ".monitor.uninstall.des")
      }),
      okText: formatMessage({
        id: 'uninstall'
      }),
      onOk: handleUninstallMonitor
    });
  }

  function uninstallCert() {
    return _uninstallCert.apply(this, arguments);
  }

  function _uninstallCert() {
    _uninstallCert = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var deleteModal, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              deleteModal = _Modal.open({
                key: certUninstallKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".cert.uninstall")
                }),
                children: /*#__PURE__*/React.createElement(_Spin, null),
                okCancel: false,
                okText: formatMessage({
                  id: 'iknow'
                }),
                footer: null
              });
              _context2.prev = 1;
              _context2.next = 4;
              return contentStore.checkUninstallCert(projectId, clusterId);

            case 4:
              res = _context2.sent;

              if (handlePromptError(res, false)) {
                if (!res) {
                  deleteModal.update({
                    children: formatMessage({
                      id: "".concat(intlPrefix, ".cert.uninstall.des")
                    }),
                    okText: formatMessage({
                      id: 'uninstall'
                    }),
                    okCancel: true,
                    onOk: handleUninstallCert,
                    okProps: {
                      color: 'red'
                    },
                    cancelProps: {
                      color: 'dark'
                    },
                    footer: function footer(okBtn, cancelBtn) {
                      return /*#__PURE__*/React.createElement("div", null, cancelBtn, okBtn);
                    }
                  });
                } else {
                  deleteModal.update({
                    children: formatMessage({
                      id: "".concat(intlPrefix, ".cert.uninstall.disabled")
                    }),
                    footer: function footer(okBtn) {
                      return okBtn;
                    }
                  });
                }
              } else {
                deleteModal.close(true);
              }

              _context2.next = 12;
              break;

            case 8:
              _context2.prev = 8;
              _context2.t0 = _context2["catch"](1);
              Choerodon.handlePromptError(_context2.t0);
              deleteModal.close();

            case 12:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[1, 8]]);
    }));
    return _uninstallCert.apply(this, arguments);
  }

  function handleUninstallCert() {
    return _handleUninstallCert.apply(this, arguments);
  }

  function _handleUninstallCert() {
    _handleUninstallCert = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.next = 2;
              return contentStore.uninstallCert(projectId, clusterId);

            case 2:
              if (!_context3.sent) {
                _context3.next = 5;
                break;
              }

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

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

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

  function handleUninstallMonitor() {
    return _handleUninstallMonitor.apply(this, arguments);
  }

  function _handleUninstallMonitor() {
    _handleUninstallMonitor = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return contentStore.uninstallMonitor(projectId, clusterId);

            case 2:
              if (!_context4.sent) {
                _context4.next = 5;
                break;
              }

              refresh();
              return _context4.abrupt("return", true);

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

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

  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-component-wrap")
  }, getContent());
});