import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/lib/input/style";
import _Input from "choerodon-ui/lib/input";
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 _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 max-len */
import React, { useMemo } from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Action, Choerodon } from '@choerodon/boot';
import { useClusterStore } from "../../../stores";
import { useClusterMainStore } from "../../stores";
import StatusDot from "../../../../../components/status-dot";
import ActivateCluster from "../../contents/cluster-content/modals/activate-cluster";
import { useTreeStore } from "./stores";
import { handlePromptError } from "../../../../../utils";
import EditCluster from "../../contents/cluster-content/modals/create-cluster";
import CustomConfirm from "../../../../../components/custom-confirm";

var ActivateClusterModalKey = _Modal.key();

var EditClusterModalKey = _Modal.key();

var deleteModalKey = _Modal.key();

function ClusterItem(_ref) {
  var record = _ref.record,
      name = _ref.name,
      intlPrefix = _ref.intlPrefix,
      prefixCls = _ref.prefixCls,
      formatMessage = _ref.intl.formatMessage;

  var _useClusterStore = useClusterStore(),
      treeDs = _useClusterStore.treeDs;

  var _useClusterMainStore = useClusterMainStore(),
      mainStore = _useClusterMainStore.mainStore,
      ClusterDetailDs = _useClusterMainStore.ClusterDetailDs;

  var _useTreeStore = useTreeStore(),
      projectId = _useTreeStore.projectId,
      treeItemStore = _useTreeStore.treeItemStore;

  var customConfirm = useMemo(function () {
    return new CustomConfirm({
      formatMessage: formatMessage
    });
  }, []);

  function getStatus() {
    var tempStatus = record.get('status');

    switch (tempStatus) {
      case 'running':
        return ['running', 'connect'];

      case 'failed':
        return ['failed', 'failed'];

      case 'operating':
        return ['operating', 'operating'];

      default:
        break;
    }

    return ['disconnect'];
  }

  function freshMenu() {
    treeDs.query();
  }

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


  function _deleteItem() {
    _deleteItem = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var code, clusterName, deleteModal, res, message, modalContent;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              code = record.get('code');
              clusterName = record.get('name');
              deleteModal = _Modal.open({
                key: deleteModalKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".action.delete.title")
                }, {
                  name: clusterName
                }),
                children: /*#__PURE__*/React.createElement(_Spin, null),
                movable: false,
                footer: null
              });
              _context3.next = 5;
              return mainStore.deleteCheck(projectId, record.get('id'));

            case 5:
              res = _context3.sent;

              if (res && (res.checkEnv || res.checkPV)) {
                message = '';

                if (res.checkPV) {
                  message = formatMessage({
                    id: 'c7ncd.cluster.action.can\'t.delete.pv'
                  });
                }

                if (res.checkEnv) {
                  message = formatMessage({
                    id: 'c7ncd.cluster.action.can\'t.delete.env'
                  });
                }

                deleteModal.update({
                  title: formatMessage({
                    id: 'c7ncd.cluster.action.can\'t.delete'
                  }),
                  children: message,
                  okText: formatMessage({
                    id: 'iknow'
                  }),
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(React.Fragment, null, okBtn);
                  }
                });
              } else {
                modalContent = /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(FormattedMessage, {
                  id: "cluster.delDes_1"
                }), /*#__PURE__*/React.createElement("div", {
                  className: "".concat(prefixCls, "-delete-input")
                }, /*#__PURE__*/React.createElement(_Input, {
                  value: "helm uninstall choerodon-cluster-agent-".concat(code || '', " -n choerodon"),
                  readOnly: true,
                  copy: true
                })), /*#__PURE__*/React.createElement("div", {
                  className: "".concat(prefixCls, "-delete-notice")
                }, /*#__PURE__*/React.createElement(_Icon, {
                  type: "error"
                }), /*#__PURE__*/React.createElement(FormattedMessage, {
                  id: "cluster.delDes_2"
                })));
                deleteModal.update({
                  children: modalContent,
                  onOk: handleDelete,
                  okCancel: true,
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(React.Fragment, null, okBtn, cancelBtn);
                  },
                  okText: formatMessage({
                    id: 'cluster.del.confirm'
                  }),
                  okProps: {
                    color: 'red'
                  }
                });
              }

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

  function handleDelete() {
    return _handleDelete.apply(this, arguments);
  }

  function _handleDelete() {
    _handleDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      var res;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.prev = 0;
              _context4.next = 3;
              return mainStore.deleteCluster({
                projectId: projectId,
                clusterId: record.get('id')
              });

            case 3:
              res = _context4.sent;

              if (!handlePromptError(res, false)) {
                _context4.next = 9;
                break;
              }

              freshMenu();
              mainStore.checkCreate(projectId);
              _context4.next = 10;
              break;

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

            case 10:
              _context4.next = 16;
              break;

            case 12:
              _context4.prev = 12;
              _context4.t0 = _context4["catch"](0);
              Choerodon.handleResponseError(_context4.t0);
              return _context4.abrupt("return", false);

            case 16:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4, null, [[0, 12]]);
    }));
    return _handleDelete.apply(this, arguments);
  }

  function openEdit(res) {
    _Modal.open({
      key: EditClusterModalKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".modal.edit")
      }),
      children: /*#__PURE__*/React.createElement(EditCluster, {
        isEdit: true,
        clusterId: record.data.id,
        mainStore: mainStore,
        afterOk: freshMenu,
        intlPrefix: intlPrefix,
        formatMessage: formatMessage,
        treeItemStore: treeItemStore,
        projectId: projectId
      }),
      drawer: true,
      style: {
        width: 380
      },
      okText: formatMessage({
        id: 'save'
      })
    });
  }

  function editItem() {
    return _editItem.apply(this, arguments);
  }

  function _editItem() {
    _editItem = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              openEdit();

            case 1:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    }));
    return _editItem.apply(this, arguments);
  }

  function activateItem() {
    return _activateItem.apply(this, arguments);
  }

  function _activateItem() {
    _activateItem = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() {
      var res;
      return regeneratorRuntime.wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              _context6.next = 2;
              return treeItemStore.queryActivateClusterShell(projectId, record.get('id'));

            case 2:
              res = _context6.sent;

              if (handlePromptError(res)) {
                _Modal.open({
                  key: ActivateClusterModalKey,
                  title: formatMessage({
                    id: "".concat(intlPrefix, ".activate.header")
                  }),
                  children: /*#__PURE__*/React.createElement(ActivateCluster, {
                    cmd: res,
                    intlPrefix: intlPrefix,
                    formatMessage: formatMessage
                  }),
                  drawer: true,
                  style: {
                    width: 380
                  },
                  okCancel: false,
                  okText: formatMessage({
                    id: 'close'
                  })
                });
              }

            case 4:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6);
    }));
    return _activateItem.apply(this, arguments);
  }

  var getPrefix = useMemo(function () {
    return /*#__PURE__*/React.createElement(StatusDot, {
      size: "small",
      getStatus: getStatus
    });
  }, [record]);

  var deleteFailedItem = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return mainStore.deleteCluster({
                projectId: projectId,
                clusterId: record.get('id')
              });

            case 3:
              res = _context.sent;

              if (!handlePromptError(res, false)) {
                _context.next = 8;
                break;
              }

              freshMenu();
              _context.next = 9;
              break;

            case 8:
              return _context.abrupt("return", false);

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

            case 12:
              _context.prev = 12;
              _context.t0 = _context["catch"](0);
              throw new Error(_context.t0);

            case 15:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 12]]);
    }));

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

  var handleClusterRetry = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              _context2.next = 3;
              return treeItemStore.retryCluster(projectId, record.get('id'));

            case 3:
              res = _context2.sent;

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

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

            case 6:
              freshMenu();
              return _context2.abrupt("return", true);

            case 10:
              _context2.prev = 10;
              _context2.t0 = _context2["catch"](0);
              throw new Error(_context2.t0);

            case 13:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[0, 10]]);
    }));

    return function handleClusterRetry() {
      return _ref3.apply(this, arguments);
    };
  }();

  var getSuffix = useMemo(function () {
    var _getStatus = getStatus(),
        _getStatus2 = _slicedToArray(_getStatus, 1),
        status = _getStatus2[0];

    if (status === 'operating') {
      return null;
    }

    if (status === 'failed') {
      var tempData = [{
        service: ['choerodon.code.project.deploy.cluster.cluster-management.ps.retryCluster'],
        text: formatMessage({
          id: "".concat(intlPrefix, ".action.retry")
        }),
        action: handleClusterRetry
      }, {
        service: ['choerodon.code.project.deploy.cluster.cluster-management.ps.delete'],
        text: formatMessage({
          id: "".concat(intlPrefix, ".action.delete")
        }),
        action: deleteFailedItem
      }];
      return /*#__PURE__*/React.createElement(Action, {
        placement: "bottomRight",
        data: tempData
      });
    }

    var Data = [{
      service: ['choerodon.code.project.deploy.cluster.cluster-management.ps.edit'],
      text: formatMessage({
        id: "".concat(intlPrefix, ".action.edit")
      }),
      action: editItem
    }];

    if (status === 'disconnect') {
      Data.unshift({
        service: ['choerodon.code.project.deploy.cluster.cluster-management.ps.active'],
        text: formatMessage({
          id: "".concat(intlPrefix, ".activate.header")
        }),
        action: activateItem
      });
      Data.push({
        service: ['choerodon.code.project.deploy.cluster.cluster-management.ps.delete'],
        text: formatMessage({
          id: "".concat(intlPrefix, ".action.delete")
        }),
        action: deleteItem
      });
    }

    return /*#__PURE__*/React.createElement(Action, {
      placement: "bottomRight",
      data: Data
    });
  }, [record]);

  var clearClick = function clearClick(e) {
    e.stopPropagation();
  };

  return /*#__PURE__*/React.createElement(React.Fragment, null, getPrefix, /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-clusterNode-type ").concat(prefixCls, "-clusterNode-type-").concat(record.get('type'))
  }, record.get('type') === 'created' ? '平台' : '导入'), name, /*#__PURE__*/React.createElement("div", {
    onClick: clearClick,
    role: "none"
  }, getSuffix));
}

export default injectIntl(ClusterItem);