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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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, { Fragment, useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { injectIntl } from 'react-intl';
import { Action, Choerodon, axios } from '@choerodon/boot';
import isEmpty from 'lodash/isEmpty';
import eventStopProp from "../../../../../utils/eventStopProp";
import PodCircle from "../../components/pod-circle";
import { useResourceStore } from "../../../stores";
import { useTreeItemStore } from "./stores";
import { handlePromptError } from "../../../../../utils";
import { useMainStore } from "../../stores";
import openWarnModal from "../../../../../utils/openWarnModal";

var stopKey = _Modal.key();

var stopKey2 = _Modal.key();

function InstanceItem(_ref) {
  var record = _ref.record,
      name = _ref.name,
      _ref$podColor = _ref.podColor,
      RUNNING_COLOR = _ref$podColor.RUNNING_COLOR,
      PADDING_COLOR = _ref$podColor.PADDING_COLOR,
      intlPrefix = _ref.intlPrefix,
      formatMessage = _ref.intl.formatMessage;

  var _useResourceStore = useResourceStore(),
      treeDs = _useResourceStore.treeDs,
      resourceStore = _useResourceStore.resourceStore,
      id = _useResourceStore.AppState.currentMenuType.id,
      IST_GROUP = _useResourceStore.itemTypes.IST_GROUP,
      projectId = _useResourceStore.AppState.currentMenuType.projectId;

  var _useTreeItemStore = useTreeItemStore(),
      treeItemStore = _useTreeItemStore.treeItemStore;

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

  var podRunningCount = record.get('podRunningCount');
  var podCount = record.get('podCount');
  var podUnlinkCount = podCount - podRunningCount;
  var podData = useMemo(function () {
    return [{
      name: 'running',
      value: podRunningCount,
      stroke: RUNNING_COLOR
    }, {
      name: 'unlink',
      value: podUnlinkCount,
      stroke: PADDING_COLOR
    }];
  }, [podUnlinkCount, podRunningCount, podCount]);

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

  function freshMenu() {
    freshTree();
    var _resourceStore$getSel = resourceStore.getSelectedMenu,
        itemType = _resourceStore$getSel.itemType,
        parentId = _resourceStore$getSel.parentId;

    var _record$get$split = record.get('parentId').split('**'),
        _record$get$split2 = _slicedToArray(_record$get$split, 1),
        envId = _record$get$split2[0];

    if (itemType === IST_GROUP && envId === parentId) {
      resourceStore.setUpTarget({
        type: IST_GROUP,
        id: parentId
      });
    }
  }

  function checkDataExist() {
    return resourceStore.checkExist({
      projectId: projectId,
      type: 'instance',
      envId: record.get('parentId').split('**')[0],
      id: record.get('id')
    }).then(function (isExist) {
      if (!isExist) {
        openWarnModal(freshTree, formatMessage);
      }

      return isExist;
    });
  }

  function checkPipelineReference() {
    return treeItemStore.checkPipelineReference({
      projectId: projectId,
      instanceId: record.get('id')
    });
  }

  function openPipelineReferenceModal(active, hasPipelineReference) {
    _Modal.open({
      movable: false,
      closable: false,
      key: stopKey2,
      title: formatMessage({
        id: "".concat(intlPrefix, ".instance.action.").concat(active, ".title")
      }, {
        name: record.get('name')
      }),
      children: formatMessage({
        id: "".concat(intlPrefix, ".instance.action.").concat(active, ".no.tips")
      }, _objectSpread({}, hasPipelineReference)),
      okCancel: false,
      okText: formatMessage({
        id: 'iknow'
      })
    });
  }

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

  function _openDelete() {
    _openDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(envId, istId, istName) {
      var hasPipelineReference;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return checkPipelineReference();

            case 2:
              hasPipelineReference = _context.sent;

              if (!isEmpty(hasPipelineReference)) {
                openPipelineReferenceModal('delete', hasPipelineReference);
              } else {
                openDeleteModal(envId, istId, istName, 'instance', freshMenu);
              }

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

  function openChangeActive(_x4) {
    return _openChangeActive.apply(this, arguments);
  }

  function _openChangeActive() {
    _openChangeActive = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(active) {
      var _yield$axios$all, _yield$axios$all2, isExist, hasPipelineReference;

      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return axios.all([checkDataExist(), active === 'stop' ? checkPipelineReference() : null]);

            case 2:
              _yield$axios$all = _context2.sent;
              _yield$axios$all2 = _slicedToArray(_yield$axios$all, 2);
              isExist = _yield$axios$all2[0];
              hasPipelineReference = _yield$axios$all2[1];

              if (isExist) {
                if (!isEmpty(hasPipelineReference)) {
                  openPipelineReferenceModal(active, hasPipelineReference);
                } else {
                  _Modal.open({
                    movable: false,
                    closable: false,
                    key: stopKey,
                    title: formatMessage({
                      id: "".concat(intlPrefix, ".instance.action.").concat(active, ".title")
                    }, {
                      name: record.get('name')
                    }),
                    children: formatMessage({
                      id: "".concat(intlPrefix, ".instance.action.").concat(active, ".tips")
                    }),
                    onOk: function onOk() {
                      return handleChangeActive(active);
                    }
                  });
                }
              }

            case 7:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));
    return _openChangeActive.apply(this, arguments);
  }

  function handleChangeActive(_x5) {
    return _handleChangeActive.apply(this, arguments);
  }

  function _handleChangeActive() {
    _handleChangeActive = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(active) {
      var istId, result;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.prev = 0;
              istId = record.get('id');
              _context3.next = 4;
              return treeItemStore.changeIstActive(id, istId, active);

            case 4:
              result = _context3.sent;

              if (handlePromptError(result, false)) {
                treeDs.query();
                resourceStore.setUpTarget({
                  type: 'instances',
                  id: istId
                });
              }

              _context3.next = 11;
              break;

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

            case 11:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3, null, [[0, 8]]);
    }));
    return _handleChangeActive.apply(this, arguments);
  }

  function getSuffix() {
    var istId = record.get('id');
    var istName = record.get('name');

    var _record$get$split3 = record.get('parentId').split('**'),
        _record$get$split4 = _slicedToArray(_record$get$split3, 1),
        envId = _record$get$split4[0];

    var envRecord = treeDs.find(function (eachRecord) {
      return eachRecord.get('key') === envId;
    });
    var connect = envRecord && envRecord.get('connect');

    if (!connect) {
      return;
    }

    var actionData;
    var actionItems = {
      stop: {
        service: ['choerodon.code.project.deploy.app-deployment.resource.ps.stop'],
        text: formatMessage({
          id: "".concat(intlPrefix, ".instance.action.stop")
        }),
        action: function action() {
          return openChangeActive('stop');
        }
      },
      start: {
        service: ['choerodon.code.project.deploy.app-deployment.resource.ps.start'],
        text: formatMessage({
          id: "".concat(intlPrefix, ".instance.action.start")
        }),
        action: function action() {
          return openChangeActive('start');
        }
      },
      "delete": {
        service: ['choerodon.code.project.deploy.app-deployment.resource.ps.delete'],
        text: formatMessage({
          id: "".concat(intlPrefix, ".instance.action.delete")
        }),
        action: function action() {
          return openDelete(envId, istId, istName);
        }
      }
    };

    switch (record.get('status')) {
      case 'running':
        actionData = [actionItems.stop, actionItems["delete"]];
        break;

      case 'stopped':
        actionData = [actionItems.start, actionItems["delete"]];
        break;

      case 'failed':
        actionData = [actionItems["delete"]];
        break;

      default:
        break;
    }

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

  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(PodCircle, {
    size: "small",
    dataSource: podData
  }), name, getSuffix());
}

export default injectIntl(observer(InstanceItem));