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 _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, { useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Choerodon } from '@choerodon/boot';
import { HeaderButtons } from '@choerodon/master';
import { handlePromptError } from "../../../../../../utils";
import DetailsModal from "./details";
import ValueModalContent from "./values/Config";
import UpgradeModalContent from "./upgrade";
import MarketUpgradeModalContent from "./market-upgrade";
import { useResourceStore } from "../../../../stores";
import { useInstanceStore } from "../stores";

var detailKey = _Modal.key();

var valuesKey = _Modal.key();

var upgradeKey = _Modal.key();

var redeployKey = _Modal.key();

var marketUpgradeKey = _Modal.key();

var IstModals = injectIntl(observer(function () {
  var _useResourceStore = useResourceStore(),
      prefixCls = _useResourceStore.prefixCls,
      intlPrefix = _useResourceStore.intlPrefix,
      formatMessage = _useResourceStore.intl.formatMessage,
      _useResourceStore$res = _useResourceStore.resourceStore.getSelectedMenu,
      id = _useResourceStore$res.id,
      parentId = _useResourceStore$res.parentId,
      treeDs = _useResourceStore.treeDs;

  var _useInstanceStore = useInstanceStore(),
      baseDs = _useInstanceStore.baseDs,
      casesDs = _useInstanceStore.casesDs,
      podsDs = _useInstanceStore.podsDs,
      istStore = _useInstanceStore.istStore,
      detailsStore = _useInstanceStore.detailsStore,
      _useInstanceStore$tab = _useInstanceStore.tabs,
      CASES_TAB = _useInstanceStore$tab.CASES_TAB,
      DETAILS_TAB = _useInstanceStore$tab.DETAILS_TAB,
      PODS_TAB = _useInstanceStore$tab.PODS_TAB,
      checkIstExist = _useInstanceStore.checkIstExist,
      projectId = _useInstanceStore.AppState.currentMenuType.id;

  var modalStyle = useMemo(function () {
    return {
      width: 'calc(100vw - 3.52rem)'
    };
  }, []);

  function openValueModal() {
    var record = baseDs.current;
    if (!record) return;
    var appServiceVersionId = record.get('commandVersionId');
    var appServiceId = record.get('appServiceId');
    var isMarket = record.get('source') === 'market';
    var isMiddleware = record.get('source') === 'middleware';
    istStore.loadValue(projectId, id, appServiceVersionId, isMarket || isMiddleware);
    var deployVo = {
      id: id,
      parentId: parentId,
      projectId: projectId,
      appServiceVersionId: appServiceVersionId,
      appServiceId: appServiceId
    };

    _Modal.open({
      key: valuesKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".modal.values")
      }),
      drawer: true,
      okText: formatMessage({
        id: 'deployment'
      }),
      style: modalStyle,
      children: /*#__PURE__*/React.createElement(ValueModalContent, {
        store: istStore,
        vo: deployVo,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls,
        formatMessage: formatMessage,
        refresh: afterDeploy,
        isMarket: isMarket,
        isMiddleware: isMiddleware
      }),
      afterClose: function afterClose() {
        istStore.setUpgradeValue({});
      }
    });
  }

  function openUpgradeModal() {
    var record = baseDs.current;
    if (!record) return;
    var appServiceVersionId = record.get('appServiceVersionId');
    var appServiceId = record.get('appServiceId');
    var deployVo = {
      id: id,
      parentId: parentId,
      versionId: appServiceVersionId,
      appServiceId: appServiceId
    };

    _Modal.open({
      key: upgradeKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".modal.modify")
      }),
      drawer: true,
      okText: formatMessage({
        id: 'modify'
      }),
      style: modalStyle,
      children: /*#__PURE__*/React.createElement(UpgradeModalContent, {
        store: istStore,
        vo: deployVo,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls,
        refresh: afterDeploy
      }),
      afterClose: function afterClose() {
        istStore.setUpgradeValue({});
      }
    });
  }

  function openDetailModal() {
    _Modal.open({
      key: detailKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".modal.detail")
      }),
      drawer: true,
      okCancel: false,
      okText: formatMessage({
        id: 'close'
      }),
      style: {
        width: 380
      },
      children: /*#__PURE__*/React.createElement(DetailsModal, {
        record: baseDs.current,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls,
        formatMessage: formatMessage
      })
    });
  }

  function openMarketUpgradeModal() {
    var record = baseDs.current;
    if (!record) return;

    var _parentId$split = parentId.split('**'),
        _parentId$split2 = _slicedToArray(_parentId$split, 1),
        environmentId = _parentId$split2[0];

    var defaultData = {
      instanceId: id,
      marketAppServiceId: record.get('appServiceId'),
      marketDeployObjectId: record.get('appServiceVersionId'),
      marketServiceName: record.get('appServiceName'),
      environmentId: environmentId
    };

    _Modal.open({
      key: marketUpgradeKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".modal.upgrade.market")
      }),
      drawer: true,
      okText: formatMessage({
        id: 'upgrade'
      }),
      style: modalStyle,
      children: /*#__PURE__*/React.createElement(MarketUpgradeModalContent, {
        store: istStore,
        defaultData: defaultData,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls,
        refresh: afterDeploy,
        isMiddleware: record.get('source') === 'middleware'
      })
    });
  }

  function getDs(key) {
    var _dsMapping;

    var dsMapping = (_dsMapping = {}, _defineProperty(_dsMapping, CASES_TAB, casesDs), _defineProperty(_dsMapping, PODS_TAB, podsDs), _dsMapping);
    return dsMapping[key];
  }

  function refresh() {
    checkIstExist().then(function (query) {
      if (query) {
        treeDs.query();
        baseDs.query();
        var activeKey = istStore.getTabKey;

        if (activeKey === DETAILS_TAB) {
          detailsStore.loadResource(projectId, id);
        } else {
          var ds = getDs(activeKey);
          ds && ds.query();
        }
      }
    });
  }

  function openRedeploy() {
    var record = baseDs.current;
    if (!record) return;
    var versionName = record.get('commandVersion');

    _Modal.open({
      key: redeployKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".modal.redeploy")
      }),
      children: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "".concat(intlPrefix, ".modal.redeploy.tips"),
        values: {
          versionName: versionName
        }
      }),
      onOk: redeploy
    });
  }

  function redeploy() {
    return _redeploy.apply(this, arguments);
  }

  function _redeploy() {
    _redeploy = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var result;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return istStore.redeploy(projectId, id);

            case 3:
              result = _context.sent;

              if (handlePromptError(result, false)) {
                afterDeploy();
              }

              _context.next = 10;
              break;

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

            case 10:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 7]]);
    }));
    return _redeploy.apply(this, arguments);
  }

  function afterDeploy() {
    detailsStore.setTargetCount({});
    refresh();
  }

  function getHeader() {
    var _parentId$split3 = parentId.split('**'),
        _parentId$split4 = _slicedToArray(_parentId$split3, 1),
        envId = _parentId$split4[0];

    var envRecord = treeDs.find(function (record) {
      return record.get('key') === envId;
    });
    var connect = envRecord && envRecord.get('connect');
    var record = baseDs.current;
    var status = record ? record.get('status') : '';
    var isMarket = record && ['middleware', 'market'].includes(record.get('source'));
    var isMiddleware = (record === null || record === void 0 ? void 0 : record.get('source')) === 'middleware';
    var appAvailable = record && record.get('currentVersionAvailable');
    var upgradeAvailable = record && record.get('upgradeAvailable');
    var btnDisabled = !connect || !status || status !== 'failed' && status !== 'running';
    var marketDisable = isMarket && !appAvailable;
    var buttons = [{
      name: formatMessage({
        id: "".concat(intlPrefix, ".modal.values")
      }),
      icon: 'rate_review1',
      handler: openValueModal,
      display: true,
      permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.values'],
      disabled: btnDisabled || marketDisable,
      tooltipsConfig: {
        placement: 'bottom',
        title: !btnDisabled && marketDisable ? formatMessage({
          id: "".concat(intlPrefix, ".instance.disable.message")
        }) : ''
      },
      disabledMessage: !btnDisabled ? formatMessage({
        id: "".concat(intlPrefix, ".instance.disable.message")
      }) : null
    }, {
      name: formatMessage({
        id: "".concat(intlPrefix, ".modal.modify")
      }),
      icon: 'backup_line',
      handler: openUpgradeModal,
      permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.example'],
      display: !isMarket,
      disabled: btnDisabled
    }, {
      name: formatMessage({
        id: 'upgrade'
      }),
      icon: 'backup_line',
      handler: openMarketUpgradeModal,
      permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.market.upgrade'],
      display: isMarket && !isMiddleware,
      disabled: btnDisabled || marketDisable || !upgradeAvailable,
      tooltipsConfig: {
        placement: 'bottom',
        title: !btnDisabled && (marketDisable || !upgradeAvailable) ? formatMessage({
          id: "".concat(intlPrefix, ".instance.disable.message").concat(appAvailable ? '.upgrade' : '')
        }) : ''
      },
      disabledMessage: !btnDisabled ? formatMessage({
        id: "".concat(intlPrefix, ".instance.disable.message").concat(appAvailable ? '.upgrade' : '')
      }) : null
    }, {
      name: formatMessage({
        id: "".concat(intlPrefix, ".modal.redeploy")
      }),
      icon: 'redeploy_line',
      handler: openRedeploy,
      permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.redeploy'],
      disabled: btnDisabled || marketDisable,
      tooltipsConfig: {
        title: !btnDisabled && marketDisable ? formatMessage({
          id: "".concat(intlPrefix, ".instance.disable.message")
        }) : '',
        placement: 'bottom'
      }
    }, {
      icon: 'refresh',
      handler: refresh,
      display: true
    }];
    return /*#__PURE__*/React.createElement(HeaderButtons, {
      items: buttons,
      showClassName: true
    });
  }

  return getHeader();
}));
export default IstModals;