import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";

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 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, { useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { HeaderButtons } from '@choerodon/master';
import EnvDetail from "../../../../../../components/env-detail";
import LinkService from "./link-service";
import PermissionPage from "./permission";
import { useResourceStore } from "../../../../stores";
import { useEnvironmentStore } from "../stores";
import { useModalStore } from "./stores";
import Tips from "../../../../../../components/new-tips";
import DeployConfigForm from "./deploy-config";
import Deploy from "../../../../../deployment/modals/deploy";
import BatchDeploy from "../../../../../deployment/modals/batch-deploy";
import "../../../../../../components/dynamic-select/style/index.less";

var modalKey1 = _Modal.key();

var modalKey2 = _Modal.key();

var modalKey3 = _Modal.key();

var configKey = _Modal.key();

var deployKey = _Modal.key();

var batchDeployKey = _Modal.key();

var EnvModals = observer(function () {
  var modalStyle = useMemo(function () {
    return {
      width: 380
    };
  }, []);
  var configModalStyle = useMemo(function () {
    return {
      width: 'calc(100vw - 3.52rem)',
      minWidth: '2rem'
    };
  }, []);

  var _useResourceStore = useResourceStore(),
      intlPrefix = _useResourceStore.intlPrefix,
      prefixCls = _useResourceStore.prefixCls,
      formatMessage = _useResourceStore.intl.formatMessage,
      id = _useResourceStore.resourceStore.getSelectedMenu.id,
      projectId = _useResourceStore.AppState.currentMenuType.id,
      treeDs = _useResourceStore.treeDs,
      resourceStore = _useResourceStore.resourceStore,
      itemTypes = _useResourceStore.itemTypes;

  var intlPrefixDeploy = 'c7ncd.deploy';

  var _useEnvironmentStore = useEnvironmentStore(),
      envStore = _useEnvironmentStore.envStore,
      _useEnvironmentStore$ = _useEnvironmentStore.tabs,
      SYNC_TAB = _useEnvironmentStore$.SYNC_TAB,
      ASSIGN_TAB = _useEnvironmentStore$.ASSIGN_TAB,
      CONFIG_TAB = _useEnvironmentStore$.CONFIG_TAB,
      POLARIS_TAB = _useEnvironmentStore$.POLARIS_TAB,
      permissionsDs = _useEnvironmentStore.permissionsDs,
      gitopsLogDs = _useEnvironmentStore.gitopsLogDs,
      gitopsSyncDs = _useEnvironmentStore.gitopsSyncDs,
      baseInfoDs = _useEnvironmentStore.baseInfoDs,
      configFormDs = _useEnvironmentStore.configFormDs,
      configDs = _useEnvironmentStore.configDs,
      polarisNumDS = _useEnvironmentStore.polarisNumDS,
      istSummaryDs = _useEnvironmentStore.istSummaryDs;

  var ModalStores = useModalStore();
  var modalStore = ModalStores.modalStore,
      nonePermissionDs = ModalStores.nonePermissionDs,
      deployStore = ModalStores.deployStore;

  function linkServices(data) {
    return modalStore.addService(projectId, id, data);
  }

  function refresh() {
    baseInfoDs.query();
    treeDs.query();
    var tabKey = envStore.getTabKey;

    switch (tabKey) {
      case SYNC_TAB:
        gitopsSyncDs.query();
        gitopsLogDs.query();
        break;

      case ASSIGN_TAB:
        permissionsDs.query();
        break;

      case CONFIG_TAB:
        configDs.query();
        break;

      case POLARIS_TAB:
        loadPolaris();
        break;

      default:
        break;
    }
  }

  function loadPolaris() {
    return _loadPolaris.apply(this, arguments);
  }

  function _loadPolaris() {
    _loadPolaris = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return envStore.checkHasInstance(projectId, id);

            case 2:
              res = _context.sent;

              if (res) {
                polarisNumDS.query();
                istSummaryDs.query();
              }

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

  function deployAfter(_ref) {
    var envId = _ref.envId,
        appServiceId = _ref.appServiceId,
        instanceId = _ref.id;
    treeDs.query();
    var parentId = "".concat(envId, "**").concat(appServiceId);
    resourceStore.setSelectedMenu({
      id: instanceId,
      parentId: parentId,
      key: "".concat(parentId, "**").concat(instanceId),
      itemType: itemTypes.IST_ITEM
    });
    resourceStore.setExpandedKeys(["".concat(envId), "".concat(envId, "**").concat(appServiceId)]);
  }

  function openEnvDetail() {
    var record = baseInfoDs.current;
    var data = record ? _objectSpread(_objectSpread({}, record.toData()), {}, {
      synchronize: true
    }) : null;

    _Modal.open({
      key: modalKey1,
      title: formatMessage({
        id: "".concat(intlPrefix, ".modal.env-detail")
      }),
      children: /*#__PURE__*/React.createElement(EnvDetail, {
        record: data,
        isRecord: false
      }),
      drawer: true,
      style: modalStyle,
      okCancel: false,
      okText: formatMessage({
        id: 'close'
      })
    });
  }

  function openLinkService() {
    _Modal.open({
      key: modalKey2,
      title: /*#__PURE__*/React.createElement(Tips, {
        helpText: formatMessage({
          id: "".concat(intlPrefix, ".service.tips")
        }),
        title: formatMessage({
          id: "".concat(intlPrefix, ".modal.service.link")
        })
      }),
      style: modalStyle,
      drawer: true,
      className: 'c7ncd-modal-wrapper',
      children: /*#__PURE__*/React.createElement(LinkService, {
        store: modalStore,
        tree: treeDs,
        onOk: linkServices,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls,
        modalStores: ModalStores
      })
    });
  }

  function openPermission() {
    var modalPorps = {
      dataSet: permissionsDs,
      nonePermissionDs: nonePermissionDs,
      formatMessage: formatMessage,
      store: modalStore,
      baseDs: baseInfoDs,
      intlPrefix: intlPrefix,
      prefixCls: prefixCls,
      refresh: refresh,
      projectId: projectId
    };

    _Modal.open({
      key: modalKey3,
      title: /*#__PURE__*/React.createElement(Tips, {
        helpText: formatMessage({
          id: "".concat(intlPrefix, ".permission.tips")
        }),
        title: formatMessage({
          id: "".concat(intlPrefix, ".modal.permission")
        })
      }),
      drawer: true,
      style: modalStyle,
      className: 'c7ncd-modal-wrapper',
      children: /*#__PURE__*/React.createElement(PermissionPage, modalPorps)
    });
  }

  function toPermissionTab() {
    var getTabKey = envStore.getTabKey;
    baseInfoDs.query();
    envStore.setTabKey(ASSIGN_TAB);
    getTabKey === ASSIGN_TAB && permissionsDs.query();
  }

  function linkToConfig() {
    var record = baseInfoDs.current;
    var url = record && record.get('gitlabUrl');
    url && window.open(url);
  }

  function openConfigModal() {
    configFormDs.create();

    _Modal.open({
      key: configKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".create.config")
      }),
      children: /*#__PURE__*/React.createElement(DeployConfigForm, {
        store: envStore,
        dataSet: configFormDs,
        refresh: refresh,
        envId: id,
        intlPrefix: intlPrefix,
        prefixCls: prefixCls
      }),
      drawer: true,
      style: configModalStyle,
      afterClose: function afterClose() {
        configFormDs.reset();
        envStore.setValue('');
      },
      okText: formatMessage({
        id: 'create'
      })
    });
  }

  function openDeploy() {
    _Modal.open({
      key: deployKey,
      style: configModalStyle,
      drawer: true,
      title: formatMessage({
        id: "".concat(intlPrefixDeploy, ".manual")
      }),
      children: /*#__PURE__*/React.createElement(Deploy, {
        deployStore: deployStore,
        refresh: deployAfter,
        intlPrefix: intlPrefixDeploy,
        prefixCls: "c7ncd-deploy",
        envId: id
      }),
      afterClose: function afterClose() {
        deployStore.setCertificates([]);
        deployStore.setAppService([]);
        deployStore.setConfigValue('');
      },
      okText: formatMessage({
        id: 'deployment'
      })
    });
  }

  function openBatchDeploy() {
    _Modal.open({
      key: batchDeployKey,
      style: configModalStyle,
      drawer: true,
      title: formatMessage({
        id: "".concat(intlPrefixDeploy, ".batch")
      }),
      children: /*#__PURE__*/React.createElement(BatchDeploy, {
        deployStore: deployStore,
        refresh: deployAfter,
        intlPrefix: intlPrefixDeploy,
        prefixCls: "c7ncd-deploy",
        envId: id
      }),
      afterClose: function afterClose() {
        deployStore.setCertificates([]);
        deployStore.setAppService([]);
        deployStore.setShareAppService([]);
        deployStore.setConfigValue('');
      },
      okText: formatMessage({
        id: 'deployment'
      })
    });
  }

  function getButtons() {
    var record = baseInfoDs.current;
    var notReady = !record;
    var connect = record && record.get('connect');
    var configDisabled = !connect || notReady;
    return [{
      permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.link'],
      name: formatMessage({
        id: "".concat(intlPrefix, ".modal.service.link")
      }),
      icon: 'relate',
      handler: openLinkService,
      display: true,
      disabled: notReady
    }, {
      permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.deploy-config'],
      disabled: notReady,
      name: formatMessage({
        id: "".concat(intlPrefix, ".create.config")
      }),
      icon: 'playlist_add',
      handler: openConfigModal,
      display: true
    }, {
      name: '部署',
      icon: 'cloud_done-o',
      groupBtnItems: [{
        permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.manual'],
        disabled: configDisabled,
        name: formatMessage({
          id: "".concat(intlPrefixDeploy, ".manual")
        }),
        handler: openDeploy
      }, {
        permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.batch'],
        disabled: configDisabled,
        name: formatMessage({
          id: "".concat(intlPrefixDeploy, ".batch")
        }),
        handler: openBatchDeploy
      }]
    }, {
      permissions: ['choerodon.code.project.deploy.app-deployment.resource.ps.permission'],
      name: formatMessage({
        id: "".concat(intlPrefix, ".modal.permission")
      }),
      icon: 'settings-o',
      handler: openPermission,
      display: true,
      disabled: notReady
    }, {
      disabled: notReady,
      name: formatMessage({
        id: "".concat(intlPrefix, ".modal.env-detail")
      }),
      icon: 'find_in_page-o',
      handler: openEnvDetail,
      display: true
    }, {
      disabled: notReady,
      name: formatMessage({
        id: "".concat(intlPrefix, ".environment.config-lab")
      }),
      icon: 'account_balance',
      handler: linkToConfig,
      display: true
    }, {
      icon: 'refresh',
      handler: refresh,
      display: true
    }];
  }

  return /*#__PURE__*/React.createElement(HeaderButtons, {
    items: getButtons(),
    showClassName: true
  });
});
export default EnvModals;