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, { Fragment, useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { injectIntl } from 'react-intl';
import { Action, Choerodon } from '@choerodon/boot';
import { handlePromptError } from "../../../../../utils";
import eventStopProp from "../../../../../utils/eventStopProp";
import TreeItemName from "../../../../../components/treeitem-name";
import EnvItem from "../../../../../components/env-item";
import { statusMappings, getEnvStatus } from "../../../../../components/status-dot";
import EnvModifyForm from "../../modals/env-modify";
import { useEnvironmentStore } from "../../../stores";
import { useMainStore } from "../../stores";

var formKey = _Modal.key();

var effectKey = _Modal.key();

var deleteKey = _Modal.key();

function DetailItem(_ref) {
  var record = _ref.record,
      search = _ref.search,
      formatMessage = _ref.intl.formatMessage,
      intlPrefix = _ref.intlPrefix;
  var modalStyle = useMemo(function () {
    return {
      width: 380
    };
  }, []);

  var _useEnvironmentStore = useEnvironmentStore(),
      treeDs = _useEnvironmentStore.treeDs,
      projectId = _useEnvironmentStore.AppState.currentMenuType.id,
      envStore = _useEnvironmentStore.envStore,
      GROUP_ITEM = _useEnvironmentStore.itemType.GROUP_ITEM;

  var _useMainStore = useMainStore(),
      mainStore = _useMainStore.mainStore;

  var _envStore$getSelected = envStore.getSelectedMenu,
      itemType = _envStore$getSelected.itemType,
      key = _envStore$getSelected.key;

  function refresh() {
    treeDs.query();

    if (itemType === GROUP_ITEM && key === record.get('parentId')) {
      envStore.setUpTarget(key);
    }
  }

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

  function _handleDelete() {
    _handleDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var envId, res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              envId = record.get('id');
              _context.prev = 1;
              _context.next = 4;
              return mainStore.deleteEnv(projectId, envId);

            case 4:
              res = _context.sent;
              handlePromptError(res);
              _context.next = 11;
              break;

            case 8:
              _context.prev = 8;
              _context.t0 = _context["catch"](1);
              Choerodon.handleResponseError(_context.t0);

            case 11:
              _context.prev = 11;
              refresh();
              return _context.finish(11);

            case 14:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[1, 8, 11, 14]]);
    }));
    return _handleDelete.apply(this, arguments);
  }

  function openDelete() {
    return _openDelete.apply(this, arguments);
  }

  function _openDelete() {
    _openDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var name, envId, deleteModal, res, result;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              name = record.get('name');
              envId = record.get('id');
              deleteModal = _Modal.open({
                key: deleteKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".delete.title")
                }, {
                  name: name
                }),
                children: /*#__PURE__*/React.createElement(_Spin, null),
                footer: null,
                movable: false
              });
              _context2.prev = 3;
              _context2.next = 6;
              return checkStatus();

            case 6:
              res = _context2.sent;

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

              _context2.next = 10;
              return mainStore.checkDelete(projectId, envId);

            case 10:
              result = _context2.sent;

              if (result && result.failed) {
                deleteModal.close();
              } else if (result) {
                deleteModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".delete.des.resource.confirm")
                  }),
                  okText: formatMessage({
                    id: 'delete'
                  }),
                  okProps: {
                    color: 'red'
                  },
                  cancelProps: {
                    color: 'dark'
                  },
                  onOk: handleDelete,
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(Fragment, null, cancelBtn, okBtn);
                  }
                });
              } else {
                deleteModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".delete.des.pipeline.confirm")
                  }),
                  okText: formatMessage({
                    id: 'iknow'
                  }),
                  footer: function footer(okBtn) {
                    return /*#__PURE__*/React.createElement(Fragment, null, okBtn);
                  }
                });
              }

              _context2.next = 15;
              break;

            case 14:
              deleteModal.update({
                children: formatMessage({
                  id: "".concat(intlPrefix, ".status.change")
                }),
                okText: formatMessage({
                  id: 'iknow'
                }),
                onOk: refresh,
                footer: function footer(okBtn) {
                  return /*#__PURE__*/React.createElement(Fragment, null, okBtn);
                }
              });

            case 15:
              _context2.next = 21;
              break;

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

            case 21:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[3, 17]]);
    }));
    return _openDelete.apply(this, arguments);
  }

  function checkStatus() {
    var envId = record.get('id');
    var status = getStatusInRecord();
    var oldStatus = getEnvStatus(status);
    return new Promise(function (resolve) {
      mainStore.checkStatus(projectId, envId).then(function (res) {
        if (res && res.id) {
          res.failed = res.fail;
          var newStatus = getEnvStatus(res);
          resolve(newStatus === oldStatus);
        }
      })["catch"](function () {
        return resolve(false);
      });
    });
  }

  function openModifyModal() {
    return _openModifyModal.apply(this, arguments);
  }

  function _openModifyModal() {
    _openModifyModal = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var modifyModal, res;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              modifyModal = _Modal.open({
                key: formKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".modify")
                }),
                style: modalStyle,
                children: /*#__PURE__*/React.createElement(_Spin, null),
                drawer: true,
                okCancel: false,
                okText: formatMessage({
                  id: 'close'
                })
              });
              _context3.prev = 1;
              _context3.next = 4;
              return checkStatus();

            case 4:
              res = _context3.sent;

              if (res) {
                modifyModal.update({
                  okCancel: true,
                  children: /*#__PURE__*/React.createElement(EnvModifyForm, {
                    intlPrefix: intlPrefix,
                    refresh: refresh,
                    record: record,
                    store: envStore
                  }),
                  okText: formatMessage({
                    id: 'save'
                  })
                });
              } else {
                modifyModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".status.change")
                  }),
                  okText: formatMessage({
                    id: 'iknow'
                  }),
                  onOk: refresh
                });
              }

              _context3.next = 12;
              break;

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

            case 12:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[1, 8]]);
    }));
    return _openModifyModal.apply(this, arguments);
  }

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

  function _handleEffect() {
    _handleEffect = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(target) {
      var envId, res;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.prev = 0;
              envId = record.get('id');
              _context4.next = 4;
              return mainStore.effectEnv(projectId, envId, target);

            case 4:
              res = _context4.sent;

              if (handlePromptError(res)) {
                envStore.setUpTarget(envId);
              }

              _context4.next = 11;
              break;

            case 8:
              _context4.prev = 8;
              _context4.t0 = _context4["catch"](0);
              Choerodon.handleResponseError(_context4.t0);

            case 11:
              _context4.prev = 11;
              refresh();
              return _context4.finish(11);

            case 14:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4, null, [[0, 8, 11, 14]]);
    }));
    return _handleEffect.apply(this, arguments);
  }

  function openEffectModal() {
    return _openEffectModal.apply(this, arguments);
  }

  function _openEffectModal() {
    _openEffectModal = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {
      var envId, name, effectModal, res, result;
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              envId = record.get('id');
              name = record.get('name');
              effectModal = _Modal.open({
                key: effectKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".stop.title")
                }, {
                  name: name
                }),
                children: /*#__PURE__*/React.createElement(_Spin, null),
                footer: null,
                movable: false
              });
              _context5.next = 5;
              return checkStatus();

            case 5:
              res = _context5.sent;

              if (!res) {
                _context5.next = 20;
                break;
              }

              _context5.prev = 7;
              _context5.next = 10;
              return mainStore.checkStop(projectId, envId);

            case 10:
              result = _context5.sent;

              if (handlePromptError(result)) {
                effectModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".stop.des")
                  }),
                  okText: formatMessage({
                    id: 'ok'
                  }),
                  okCancel: true,
                  onOk: function onOk() {
                    return handleEffect(false);
                  },
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(Fragment, null, okBtn, cancelBtn);
                  }
                });
              } else if (!result.failed) {
                effectModal.update({
                  children: formatMessage({
                    id: "".concat(intlPrefix, ".no.stop.des")
                  }),
                  okText: formatMessage({
                    id: 'iknow'
                  }),
                  footer: function footer(okBtn, cancelBtn) {
                    return /*#__PURE__*/React.createElement(Fragment, null, okBtn);
                  }
                });
              } else {
                effectModal.close();
              }

              _context5.next = 18;
              break;

            case 14:
              _context5.prev = 14;
              _context5.t0 = _context5["catch"](7);
              Choerodon.handleResponseError(_context5.t0);
              effectModal.close();

            case 18:
              _context5.next = 21;
              break;

            case 20:
              effectModal.update({
                children: formatMessage({
                  id: "".concat(intlPrefix, ".status.change")
                }),
                onOk: refresh,
                footer: function footer(okBtn, cancelBtn) {
                  return /*#__PURE__*/React.createElement(Fragment, null, okBtn);
                }
              });

            case 21:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5, null, [[7, 14]]);
    }));
    return _openEffectModal.apply(this, arguments);
  }

  function getStatusInRecord() {
    var connect = record.get('connect');
    var failed = record.get('failed');
    var synchronize = record.get('synchro');
    var active = record.get('active');
    return {
      connect: connect,
      failed: failed,
      synchronize: synchronize,
      active: active
    };
  }

  function getSuffix() {
    var RUNNING = statusMappings.RUNNING,
        STOPPED = statusMappings.STOPPED,
        OPERATING = statusMappings.OPERATING,
        FAILED = statusMappings.FAILED,
        DISCONNECTED = statusMappings.DISCONNECTED;
    var status = getStatusInRecord();
    var result = getEnvStatus(status);
    if (result === OPERATING) return null;
    var actionData = [];

    switch (result) {
      case RUNNING:
        actionData = [{
          service: ['choerodon.code.project.deploy.environment.ps.modify'],
          text: formatMessage({
            id: "".concat(intlPrefix, ".modal.detail.modify")
          }),
          action: openModifyModal
        }, {
          service: ['choerodon.code.project.deploy.environment.ps.stop'],
          text: formatMessage({
            id: "".concat(intlPrefix, ".modal.detail.stop")
          }),
          action: openEffectModal
        }];
        break;

      case DISCONNECTED:
        actionData = [{
          service: ['choerodon.code.project.deploy.environment.ps.modify'],
          text: formatMessage({
            id: "".concat(intlPrefix, ".modal.detail.modify")
          }),
          action: openModifyModal
        }, {
          service: ['choerodon.code.project.deploy.environment.ps.delete'],
          text: formatMessage({
            id: "".concat(intlPrefix, ".modal.detail.delete")
          }),
          action: openDelete
        }];
        break;

      case STOPPED:
        actionData = [{
          service: ['choerodon.code.project.deploy.environment.ps.stop'],
          text: formatMessage({
            id: "".concat(intlPrefix, ".modal.detail.start")
          }),
          action: function action() {
            return handleEffect(true);
          }
        }, {
          service: ['choerodon.code.project.deploy.environment.ps.delete'],
          text: formatMessage({
            id: "".concat(intlPrefix, ".modal.detail.delete")
          }),
          action: openDelete
        }];
        break;

      case FAILED:
        actionData = [{
          service: ['choerodon.code.project.deploy.environment.ps.delete'],
          text: formatMessage({
            id: "".concat(intlPrefix, ".modal.detail.delete")
          }),
          action: openDelete
        }];
        break;

      default:
    }

    return /*#__PURE__*/React.createElement(Action, {
      placement: "bottomRight",
      data: actionData,
      onClick: eventStopProp
    });
  }

  function getName() {
    var OPERATING = statusMappings.OPERATING,
        FAILED = statusMappings.FAILED;
    var itemName = record.get('name') || '';
    var status = getStatusInRecord();
    var result = getEnvStatus(status);
    var disabled = result === OPERATING || result === FAILED;
    var name = /*#__PURE__*/React.createElement(TreeItemName, {
      disabled: disabled,
      name: itemName,
      search: search
    });
    return /*#__PURE__*/React.createElement(EnvItem, Object.assign({
      name: name
    }, status));
  }

  return /*#__PURE__*/React.createElement(Fragment, null, getName(), getSuffix());
}

export default injectIntl(observer(DetailItem));