import "choerodon-ui/pro/lib/tooltip/style";
import _Tooltip from "choerodon-ui/pro/lib/tooltip";
import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
import "choerodon-ui/pro/lib/select/style";
import _Select from "choerodon-ui/pro/lib/select";
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); }); }; }

/* eslint-disable */
import React, { Fragment, useMemo, useState } from 'react';
import { Action, axios, Choerodon } from '@choerodon/boot';
import { observer } from 'mobx-react-lite';
import map from 'lodash/map';
import forEach from 'lodash/forEach';
import includes from 'lodash/includes';
import PipelineCreate from "../PipelineCreate";
import { usePipelineManageStore } from "../../stores";
import TimePopover from "../../../../components/timePopover";
import eventStopProp from "../../../../utils/eventStopProp";
import PipelineType from "../pipeline-type";
import ExecuteContent from "./execute-content";
import TreeItemName from "../../../../components/treeitem-name";
import { usePipelineTreeStore } from "./stores";
import CopyPipeline from "./components/copy-pipeline";
import StatusTag from "../PipelineFlow/components/StatusTag";
import AuditModal from "../audit-modal";
import { NewTips } from "@choerodon/components";

var executeKey = _Modal.key();

var stopKey = _Modal.key();

var auditKey = _Modal.key();

var Option = _Select.Option;
var TreeItem = observer(function (_ref) {
  var record = _ref.record,
      search = _ref.search;

  var _usePipelineManageSto = usePipelineManageStore(),
      intlPrefix = _usePipelineManageSto.intlPrefix,
      prefixCls = _usePipelineManageSto.prefixCls,
      projectId = _usePipelineManageSto.AppState.currentMenuType.projectId,
      formatMessage = _usePipelineManageSto.intl.formatMessage,
      treeDs = _usePipelineManageSto.treeDs,
      mainStore = _usePipelineManageSto.mainStore,
      editBlockStore = _usePipelineManageSto.editBlockStore;

  var _usePipelineTreeStore = usePipelineTreeStore(),
      treeStore = _usePipelineTreeStore.treeStore,
      handleRefresh = _usePipelineTreeStore.handleRefresh,
      CopyPipelineDataSet = _usePipelineTreeStore.CopyPipelineDataSet,
      seletDs = _usePipelineTreeStore.seletDs;

  var iconType = useMemo(function () {
    return {
      failed: 'cancel',
      success: 'check_circle',
      running: 'timelapse',
      canceled: 'cancle_b',
      deleted: 'cancel',
      pending: 'pause_circle_filled',
      skipped: 'skipped_b'
    };
  }, []);
  var timePopoverStyle = useMemo(function () {
    return {
      fontSize: '.12rem',
      color: 'rgba(58,52,95,0.65)',
      margin: '0 0 0 auto',
      flexShrink: '0'
    };
  }, []);

  function refresh() {
    mainStore.setTreeDataPage(1);
    mainStore.setLoadedKeys([]);
    treeDs.query();
  }

  function handleExecute() {
    return _handleExecute.apply(this, arguments);
  }

  function _handleExecute() {
    _handleExecute = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return mainStore.checkLinkToGitlab(projectId, record.get('appServiceId'), 'CI_PIPELINE_NEW_PERFORM');

            case 3:
              _Modal.open({
                key: executeKey,
                title: formatMessage({
                  id: "".concat(intlPrefix, ".execute")
                }),
                children: /*#__PURE__*/React.createElement(ExecuteContent, {
                  appServiceId: record.get('appServiceId'),
                  appServiceName: record.get('appServiceName'),
                  gitlabProjectId: record.get('gitlabProjectId'),
                  pipelineId: record.get('id'),
                  record: record,
                  refresh: refresh,
                  prefixCls: prefixCls,
                  mainStore: mainStore
                }),
                okText: formatMessage({
                  id: 'execute'
                }),
                movable: false
              });

              _context.next = 8;
              break;

            case 6:
              _context.prev = 6;
              _context.t0 = _context["catch"](0);

            case 8:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 6]]);
    }));
    return _handleExecute.apply(this, arguments);
  }

  function handleChangeActive() {
    if (record.get('enabled')) {
      _Modal.open({
        key: stopKey,
        title: formatMessage({
          id: "".concat(intlPrefix, ".stop.title")
        }),
        children: formatMessage({
          id: "".concat(intlPrefix, ".stop.des")
        }),
        okText: formatMessage({
          id: 'stop'
        }),
        onOk: function onOk() {
          return changePipelineActive('disable');
        },
        movable: false
      });
    } else {
      changePipelineActive('enable');
    }
  }

  function changePipelineActive(_x) {
    return _changePipelineActive.apply(this, arguments);
  }

  function _changePipelineActive() {
    _changePipelineActive = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(type) {
      var res;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return mainStore.changePipelineActive({
                projectId: projectId,
                pipelineId: record.get('id'),
                type: type
              });

            case 2:
              res = _context2.sent;

              if (res) {
                refresh();
              }

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

  function handleCopy() {
    _Modal.open({
      key: _Modal.key(),
      title: '复制流水线',
      children: /*#__PURE__*/React.createElement(CopyPipeline, {
        ds: CopyPipelineDataSet,
        seletDs: seletDs,
        projectId: projectId,
        editBlockStore: editBlockStore,
        record: record,
        handleRefresh: handleRefresh
      })
    });
  }

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

  function _handleDelete() {
    _handleDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var modalProps, res, _ref3, key;

      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              modalProps = {
                title: formatMessage({
                  id: "".concat(intlPrefix, ".delete.title")
                }),
                children: formatMessage({
                  id: "".concat(intlPrefix, ".delete.des")
                }),
                okText: formatMessage({
                  id: 'delete'
                }),
                okProps: {
                  color: 'red'
                },
                cancelProps: {
                  color: 'dark'
                }
              };
              _context3.next = 3;
              return treeDs["delete"](record, modalProps);

            case 3:
              res = _context3.sent;

              if (res && res.success) {
                _ref3 = mainStore.getSelectedMenu || {}, key = _ref3.key;

                if (key === record.get('key')) {
                  mainStore.setSelectedMenu({});
                }

                refresh();
              }

            case 5:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));
    return _handleDelete.apply(this, arguments);
  }

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

  function _changeRecordExecute() {
    _changeRecordExecute = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(type) {
      var res;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return mainStore.changeRecordExecute({
                projectId: projectId,
                gitlabProjectId: record.get('gitlabProjectId'),
                recordId: record.get('gitlabPipelineId'),
                type: type,
                devopsPipelineRecordRelId: record.get('devopsPipelineRecordRelId')
              });

            case 2:
              res = _context4.sent;

              if (res) {
                handleRefresh();
              }

            case 4:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));
    return _changeRecordExecute.apply(this, arguments);
  }

  function openAuditModal() {
    var pipelineName = record.parent ? record.parent.get('name') : '';

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

  function loadMoreRecord(_x3) {
    return _loadMoreRecord.apply(this, arguments);
  }

  function _loadMoreRecord() {
    _loadMoreRecord = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(deleteRecord) {
      var parentId, getPageList, setPageList, page, recordData;
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              parentId = record.get('parentId');
              deleteRecord.setState('isLoading', true);
              deleteRecord.status = 'add';
              _context5.prev = 3;
              getPageList = mainStore.getPageList, setPageList = mainStore.setPageList;
              page = getPageList[parentId] || 2;
              _context5.next = 8;
              return treeStore.loadRecords(projectId, parentId, page);

            case 8:
              recordData = _context5.sent;

              if (recordData) {
                deleteRecord.setState('isLoading', false);
                treeDs.remove(deleteRecord);
                forEach(recordData.list, function (item) {
                  item.key = "".concat(parentId, "-").concat(item.id || item.ciRecordId || item.cdRecordId);
                  item.parentId = parentId;
                  item.status = item.status || (item.ciStatus === 'success' && item.cdStatus ? item.cdStatus : item.ciStatus);
                  var treeRecord = treeDs.create(item);
                  treeDs.push(treeRecord);
                });

                if (recordData.hasNextPage) {
                  treeDs.push(deleteRecord);
                }

                setPageList(_objectSpread(_objectSpread({}, getPageList), {}, _defineProperty({}, parentId, page + 1)));
              }

              _context5.next = 15;
              break;

            case 12:
              _context5.prev = 12;
              _context5.t0 = _context5["catch"](3);
              Choerodon.handleResponseError(_context5.t0);

            case 15:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5, null, [[3, 12]]);
    }));
    return _loadMoreRecord.apply(this, arguments);
  }

  function getItem() {
    var _record$toData = record.toData(),
        gitlabPipelineId = _record$toData.gitlabPipelineId,
        key = _record$toData.key,
        name = _record$toData.name,
        appServiceName = _record$toData.appServiceName,
        latestExecuteDate = _record$toData.latestExecuteDate,
        createdDate = _record$toData.createdDate,
        status = _record$toData.status,
        _record$toData$enable = _record$toData.enabled,
        enabled = _record$toData$enable === void 0 ? false : _record$toData$enable,
        triggerType = _record$toData.triggerType,
        id = _record$toData.id,
        parentId = _record$toData.parentId,
        stageRecordVOS = _record$toData.stageRecordVOS,
        devopsPipelineRecordRelId = _record$toData.devopsPipelineRecordRelId,
        viewId = _record$toData.viewId;

    if (includes(key, 'more')) {
      if (record.getState('isLoading')) {
        return /*#__PURE__*/React.createElement(_Spin, null);
      }

      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-sidebar-header-node ").concat(prefixCls, "-sidebar-header-node-more"),
        onClick: eventStopProp
      }, /*#__PURE__*/React.createElement("span", {
        className: "".concat(prefixCls, "-sidebar-header-node-more-text"),
        onClick: function onClick() {
          return loadMoreRecord(record);
        }
      }, formatMessage({
        id: "".concat(intlPrefix, ".more")
      })));
    }

    if (parentId) {
      var _actionData;

      switch (status) {
        case 'pending':
        case 'running':
          _actionData = [{
            service: ['choerodon.code.project.develop.ci-pipeline.ps.cancel'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".execute.cancel")
            }),
            action: function action() {
              return changeRecordExecute('cancel');
            }
          }];
          break;

        case 'failed':
        case 'canceled':
          _actionData = [{
            service: ['choerodon.code.project.develop.ci-pipeline.ps.retry'],
            text: formatMessage({
              id: "".concat(intlPrefix, ".execute.retry")
            }),
            action: function action() {
              return changeRecordExecute('retry');
            }
          }];
          break;

        case 'not_audit':
          if (record.get('devopsCdPipelineDeatilVO') && record.get('devopsCdPipelineDeatilVO').execute) {
            _actionData = [{
              service: ['choerodon.code.project.develop.ci-pipeline.ps.audit'],
              text: formatMessage({
                id: "".concat(intlPrefix, ".execute.audit")
              }),
              action: openAuditModal
            }];
          }

          break;

        default:
          break;
      }

      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-sidebar-header-node")
      }, /*#__PURE__*/React.createElement("span", {
        className: "".concat(prefixCls, "-sidebar-header-number")
      }, /*#__PURE__*/React.createElement(TreeItemName, {
        name: "#".concat(viewId),
        search: search,
        headSpace: false
      })), /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-sidebar-header-stage")
      }, map(stageRecordVOS, function (_ref2) {
        var stageStatus = _ref2.status,
            _ref2$triggerType = _ref2.triggerType,
            stageTriggerType = _ref2$triggerType === void 0 ? 'auto' : _ref2$triggerType;
        return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
          className: "".concat(prefixCls, "-sidebar-header-stage-line ").concat(prefixCls, "-sidebar-header-stage-line-").concat(stageTriggerType)
        }), /*#__PURE__*/React.createElement("span", {
          className: "".concat(prefixCls, "-sidebar-header-stage-item ").concat(prefixCls, "-sidebar-header-stage-item-").concat(stageStatus)
        }));
      })), /*#__PURE__*/React.createElement(TimePopover, {
        content: createdDate,
        style: timePopoverStyle
      }), _actionData ? /*#__PURE__*/React.createElement(Action, {
        data: _actionData,
        onClick: eventStopProp
      }) : /*#__PURE__*/React.createElement("span", {
        style: {
          width: 24
        }
      }));
    }

    var actionData = [{
      service: ['choerodon.code.project.develop.ci-pipeline.ps.execute'],
      text: formatMessage({
        id: "".concat(intlPrefix, ".execute")
      }),
      action: handleExecute
    }, {
      service: ["choerodon.code.project.develop.ci-pipeline.ps.".concat(enabled ? 'disable' : 'enable')],
      text: formatMessage({
        id: enabled ? 'stop' : 'active'
      }),
      action: handleChangeActive
    }, {
      service: ['choerodon.code.project.develop.ci-pipeline.ps.create'],
      text: /*#__PURE__*/React.createElement(NewTips, {
        title: "\u590D\u5236",
        helpText: "\u6B64\u64CD\u4F5C\u5C06\u590D\u5236\u51FA\u8BE5\u6D41\u6C34\u7EBF\u4E2D\u7684CI\u9636\u6BB5\u53CA\u5176\u4EFB\u52A1\u81F3\u76EE\u6807\u5E94\u7528\u670D\u52A1"
      }),
      action: handleCopy
    }, {
      service: ['choerodon.code.project.develop.ci-pipeline.ps.delete'],
      text: formatMessage({
        id: 'delete'
      }),
      action: handleDelete
    }];
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-sidebar-header-parent")
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-sidebar-header")
    }, /*#__PURE__*/React.createElement(PipelineType, {
      name: name,
      type: triggerType
    }), /*#__PURE__*/React.createElement(_Tooltip, {
      title: "".concat(name, "(").concat(appServiceName, ")"),
      placement: "top"
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-sidebar-header-name")
    }, /*#__PURE__*/React.createElement(TreeItemName, {
      name: name,
      search: search,
      headSpace: false
    }), /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-sidebar-header-service")
    }, "(", /*#__PURE__*/React.createElement(TreeItemName, {
      name: appServiceName,
      search: search,
      headSpace: false
    }), ")"))), /*#__PURE__*/React.createElement("div", {
      style: {
        flexShrink: '0'
      }
    }, /*#__PURE__*/React.createElement(Action, {
      data: enabled ? actionData.slice(0, 3) : actionData.slice(1, 4),
      onClick: eventStopProp
    }))), /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-sidebar-header")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(prefixCls, "-sidebar-header-active ").concat(prefixCls, "-sidebar-header-active-").concat(enabled)
    }, formatMessage({
      id: enabled ? 'active' : 'stop'
    })), /*#__PURE__*/React.createElement(StatusTag, {
      status: status,
      size: 12,
      className: "".concat(prefixCls, "-sidebar-header-status")
    }), /*#__PURE__*/React.createElement(TimePopover, {
      content: latestExecuteDate,
      style: _objectSpread(_objectSpread({}, timePopoverStyle), {}, {
        marginRight: '0.24rem'
      })
    })));
  }

  return getItem();
});
TreeItem.defaultProps = {
  record: {}
};
export default TreeItem;