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); }); }; }

/* eslint-disable max-len */
import React, { useRef, Suspense } from 'react';
import { observer } from 'mobx-react-lite';
import { Page, Header, Breadcrumb, Content, HeaderButtons } from '@choerodon/boot';
import PipelineTree from "./components/PipelineTree";
import PipelineFlow from "./components/PipelineFlow";
import DragBar from "../../components/drag-bar";
import PipelineCreate from "./components/PipelineCreate";
import RecordDetail from "./components/record-detail";
import EmptyPage from "../../components/empty-page";
import { usePipelineManageStore } from "./stores";
import VariableSettings from "./components/variable-settings";
import AuditModal from "./components/audit-modal";
import GitlabRunner from "./components/gitlab-runner";
import MouserOverWrapper from "../../components/MouseOverWrapper";
import "./index.less";

var recordDetailKey = _Modal.key();

var settingsKey = _Modal.key();

var auditKey = _Modal.key();

var runnerKey = _Modal.key();

var modalStyle = {
  width: 380
};
var settingsModalStyle = {
  width: 740
};
var PipelineManage = observer(function () {
  var _usePipelineManageSto = usePipelineManageStore(),
      formatMessage = _usePipelineManageSto.intl.formatMessage,
      intlPrefix = _usePipelineManageSto.intlPrefix,
      prefixCls = _usePipelineManageSto.prefixCls,
      permissions = _usePipelineManageSto.permissions,
      mainStore = _usePipelineManageSto.mainStore,
      editBlockStore = _usePipelineManageSto.editBlockStore,
      detailStore = _usePipelineManageSto.detailStore,
      treeDs = _usePipelineManageSto.treeDs,
      projectId = _usePipelineManageSto.projectId;

  var getMainData = editBlockStore.getMainData,
      loadData = editBlockStore.loadData;
  var loadDetailData = detailStore.loadDetailData,
      getDetailData = detailStore.getDetailData;

  var handleCreatePipeline = function handleCreatePipeline() {
    _Modal.open({
      key: _Modal.key(),
      title: '创建流水线',
      style: {
        width: 'calc(100vw - 3.52rem)'
      },
      drawer: true,
      children: /*#__PURE__*/React.createElement(PipelineCreate, {
        mathRandom: Math.random(),
        refreshTree: handleRefresh,
        editBlockStore: editBlockStore,
        mainStore: mainStore
      }),
      okText: '创建'
    });
  };

  var rootRef = useRef(null);
  var getSelectedMenu = mainStore.getSelectedMenu;

  function handleRefresh() {
    return _handleRefresh.apply(this, arguments);
  }

  function _handleRefresh() {
    _handleRefresh = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var id, parentId, devopsPipelineRecordRelId;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              mainStore.setLoadedKeys([]);
              mainStore.setTreeDataPage(1);
              _context.next = 4;
              return treeDs.query();

            case 4:
              id = getMainData.id;
              parentId = getSelectedMenu.parentId;
              devopsPipelineRecordRelId = getDetailData.devopsPipelineRecordRelId;

              if (!parentId) {
                id && loadData(projectId, id);
              } else {
                devopsPipelineRecordRelId && loadDetailData(projectId, devopsPipelineRecordRelId);
              }

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

  function openEditModal() {
    _Modal.open({
      key: _Modal.key(),
      title: '修改流水线',
      style: {
        width: 'calc(100vw - 3.52rem)'
      },
      drawer: true,
      children: /*#__PURE__*/React.createElement(PipelineCreate, {
        dataSource: editBlockStore.getMainData,
        refreshTree: handleRefresh,
        editBlockStore: editBlockStore,
        isEdit: true
      }),
      okText: formatMessage({
        id: 'save'
      })
    });
  }

  function openRecordDetail() {
    var devopsPipelineRecordRelId = getSelectedMenu.devopsPipelineRecordRelId;
    var detailDevopsPipelineRecordRelId = getDetailData.devopsPipelineRecordRelId,
        viewId = getDetailData.viewId;
    var newDevopsPipelineRecordRelId = devopsPipelineRecordRelId || detailDevopsPipelineRecordRelId;

    _Modal.open({
      key: recordDetailKey,
      style: modalStyle,
      title: /*#__PURE__*/React.createElement("span", {
        className: "".concat(prefixCls, "-detail-modal-title")
      }, "\u6D41\u6C34\u7EBF\u8BB0\u5F55\u201C", /*#__PURE__*/React.createElement(MouserOverWrapper, {
        width: "100px",
        text: "#".concat(viewId)
      }, /*#__PURE__*/React.createElement("span", null, "#".concat(viewId))), "\u201D\u7684\u8BE6\u60C5"),
      children: /*#__PURE__*/React.createElement(RecordDetail, {
        pipelineRecordId: newDevopsPipelineRecordRelId,
        intlPrefix: intlPrefix,
        refresh: handleRefresh,
        store: mainStore
      }),
      drawer: true,
      okCancel: false,
      okText: formatMessage({
        id: 'close'
      })
    });
  }

  function changeRecordExecute(_x) {
    return _changeRecordExecute.apply(this, arguments);
  }

  function _changeRecordExecute() {
    _changeRecordExecute = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(type) {
      var gitlabProjectId, gitlabPipelineId, devopsPipelineRecordRelId, detailGitlabProjectId, detailGitlabPipelineId, detailDevopsPipelineRecordRelId, res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              gitlabProjectId = getSelectedMenu.gitlabProjectId, gitlabPipelineId = getSelectedMenu.gitlabPipelineId, devopsPipelineRecordRelId = getSelectedMenu.devopsPipelineRecordRelId;
              detailGitlabProjectId = getDetailData.gitlabProjectId, detailGitlabPipelineId = getDetailData.gitlabPipelineId, detailDevopsPipelineRecordRelId = getDetailData.devopsPipelineRecordRelId;
              _context2.next = 4;
              return mainStore.changeRecordExecute({
                projectId: projectId,
                gitlabProjectId: gitlabProjectId || detailGitlabProjectId,
                recordId: gitlabPipelineId || detailGitlabPipelineId,
                type: type,
                devopsPipelineRecordRelId: devopsPipelineRecordRelId || detailDevopsPipelineRecordRelId
              });

            case 4:
              res = _context2.sent;

              if (res) {
                handleRefresh();
              }

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

  function openAuditModal() {
    var devopsCdPipelineDeatilVO = getSelectedMenu.devopsCdPipelineDeatilVO;
    var cdRecordId = getDetailData.cdRecordId,
        detailDevopsCdPipelineDeatilVO = getDetailData.devopsCdPipelineDeatilVO,
        pipelineName = getDetailData.pipelineName;

    _Modal.open({
      key: auditKey,
      title: formatMessage({
        id: "".concat(intlPrefix, ".execute.audit")
      }),
      children: /*#__PURE__*/React.createElement(AuditModal, {
        cdRecordId: cdRecordId,
        name: pipelineName,
        mainStore: mainStore,
        onClose: handleRefresh,
        checkData: devopsCdPipelineDeatilVO || detailDevopsCdPipelineDeatilVO
      }),
      movable: false
    });
  }

  function openSettingsModal(type) {
    var appServiceId = getSelectedMenu.appServiceId,
        appServiceName = getSelectedMenu.appServiceName;

    _Modal.open({
      key: settingsKey,
      style: settingsModalStyle,
      title: formatMessage({
        id: "".concat(intlPrefix, ".settings.").concat(type)
      }),
      children: /*#__PURE__*/React.createElement(VariableSettings, {
        intlPrefix: intlPrefix,
        appServiceId: type === 'global' ? null : appServiceId,
        appServiceName: type === 'global' ? null : appServiceName,
        store: mainStore,
        refresh: handleRefresh
      }),
      drawer: true,
      okText: formatMessage({
        id: 'save'
      })
    });
  }

  function openRunnerModal() {
    _Modal.open({
      key: runnerKey,
      style: settingsModalStyle,
      title: formatMessage({
        id: "".concat(intlPrefix, ".gitlab.runner")
      }),
      children: /*#__PURE__*/React.createElement(GitlabRunner, null),
      drawer: true,
      okCancel: false,
      okText: formatMessage({
        id: 'close'
      })
    });
  }

  function getHeaderButtons() {
    var parentId = getSelectedMenu.parentId,
        status = getSelectedMenu.status,
        devopsCdPipelineDeatilVO = getSelectedMenu.devopsCdPipelineDeatilVO;
    var detailStatus = getDetailData.status,
        detailDevopsCdPipelineDeatilVO = getDetailData.devopsCdPipelineDeatilVO;
    var buttons = [{
      permissions: ['choerodon.code.project.develop.ci-pipeline.ps.create'],
      name: formatMessage({
        id: "".concat(intlPrefix, ".create")
      }),
      icon: 'playlist_add',
      handler: handleCreatePipeline,
      display: true
    }, {
      permissions: ['choerodon.code.project.develop.ci-pipeline.ps.variable.project'],
      name: formatMessage({
        id: "".concat(intlPrefix, ".settings.global")
      }),
      icon: 'settings-o',
      handler: function handler() {
        return openSettingsModal('global');
      },
      display: true
    }, {
      name: '更多操作',
      groupBtnItems: [{
        name: formatMessage({
          id: "".concat(intlPrefix, ".gitlab.runner")
        }),
        service: ['choerodon.code.project.develop.ci-pipeline.ps.runner'],
        handler: openRunnerModal
      }]
    }];

    if (treeDs.length && treeDs.status === 'ready') {
      if (!parentId) {
        buttons.push({
          permissions: ['choerodon.code.project.develop.ci-pipeline.ps.update'],
          name: formatMessage({
            id: 'edit'
          }),
          icon: 'edit-o',
          handler: openEditModal,
          display: true
        }, {
          permissions: ['choerodon.code.project.develop.ci-pipeline.ps.variable.app'],
          name: formatMessage({
            id: "".concat(intlPrefix, ".settings.local")
          }),
          icon: 'settings-o',
          handler: function handler() {
            return openSettingsModal('local');
          },
          display: true
        });
      } else {
        var newStatus = status || detailStatus;
        var newDevopsCdPipelineDeatilVO = devopsCdPipelineDeatilVO || detailDevopsCdPipelineDeatilVO;
        buttons.push({
          name: formatMessage({
            id: "".concat(intlPrefix, ".record.detail")
          }),
          icon: 'find_in_page-o',
          handler: openRecordDetail,
          display: true
        }, {
          permissions: ['choerodon.code.project.develop.ci-pipeline.ps.cancel'],
          name: formatMessage({
            id: "".concat(intlPrefix, ".execute.cancel")
          }),
          icon: 'power_settings_new',
          handler: function handler() {
            return changeRecordExecute('cancel');
          },
          display: newStatus === 'pending' || newStatus === 'running'
        }, {
          permissions: ['choerodon.code.project.develop.ci-pipeline.ps.retry'],
          name: formatMessage({
            id: "".concat(intlPrefix, ".execute.retry")
          }),
          icon: 'refresh',
          handler: function handler() {
            return changeRecordExecute('retry');
          },
          display: newStatus === 'failed' || newStatus === 'canceled'
        }, {
          permissions: ['choerodon.code.project.develop.ci-pipeline.ps.audit'],
          name: formatMessage({
            id: "".concat(intlPrefix, ".execute.audit")
          }),
          icon: 'authorize',
          handler: openAuditModal,
          display: newStatus === 'not_audit' && newDevopsCdPipelineDeatilVO && newDevopsCdPipelineDeatilVO.execute
        });
      }
    }

    buttons.push({
      icon: 'refresh',
      handler: handleRefresh,
      display: true
    });
    return buttons;
  }

  return /*#__PURE__*/React.createElement(Page, {
    service: permissions,
    className: "pipelineManage_page"
  }, /*#__PURE__*/React.createElement(Header, {
    title: "\u6D41\u6C34\u7EBF"
  }, /*#__PURE__*/React.createElement(HeaderButtons, {
    items: getHeaderButtons(),
    showClassName: false
  })), /*#__PURE__*/React.createElement(Breadcrumb, null), /*#__PURE__*/React.createElement(Content, {
    className: "".concat(prefixCls, "-content")
  }, !treeDs.length && treeDs.status === 'ready' && !mainStore.getSearchValue ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-wrap")
  }, /*#__PURE__*/React.createElement(Suspense, {
    fallback: /*#__PURE__*/React.createElement("span", null)
  }, /*#__PURE__*/React.createElement(EmptyPage, {
    title: formatMessage({
      id: 'empty.title.pipeline'
    }),
    describe: formatMessage({
      id: 'empty.tips.pipeline.owner'
    }),
    btnText: formatMessage({
      id: "".concat(intlPrefix, ".create")
    }),
    onClick: handleCreatePipeline,
    access: true
  }))) : /*#__PURE__*/React.createElement("div", {
    ref: rootRef,
    className: "".concat(prefixCls, "-wrap")
  }, /*#__PURE__*/React.createElement(DragBar, {
    parentRef: rootRef,
    store: mainStore
  }), /*#__PURE__*/React.createElement(PipelineTree, {
    handleRefresh: handleRefresh
  }), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-main ").concat(prefixCls, "-animate")
  }, /*#__PURE__*/React.createElement(PipelineFlow, {
    handleRefresh: handleRefresh
  })))));
});
export default PipelineManage;