import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";
import "choerodon-ui/pro/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";

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 from 'react';
import { observer } from 'mobx-react-lite';
import { Action, Page } from '@choerodon/boot';
import { FormattedMessage, injectIntl } from 'react-intl';
import classNames from 'classnames';
import TimeAgo from 'timeago-react';
import MouserOverWrapper from "../../../../components/MouseOverWrapper";
import Loading from "../../../../components/loading";
import handleMapStore from "../../main-view/store/handleMapStore";
import { usePipelineStore } from "./stores";
import { useCodeManagerStore } from "../../stores";
import "../../../main.less";
import "./index.less";
var ICONS = {
  passed: {
    icon: 'icon-check_circle',
    code: 'passed',
    display: 'Passed'
  },
  success: {
    icon: 'icon-check_circle',
    code: 'success',
    display: 'Passed'
  },
  pending: {
    icon: 'icon-pause_circle_outline',
    code: 'pending',
    display: 'Pending'
  },
  running: {
    icon: 'icon-timelapse',
    code: 'running',
    display: 'Running'
  },
  failed: {
    icon: 'icon-cancel',
    code: 'failed',
    display: 'Failed'
  },
  canceled: {
    icon: 'icon-cancle_b',
    code: 'canceled',
    display: 'Canceled'
  },
  skipped: {
    icon: 'icon-skipped_b',
    code: 'skipped',
    display: 'Skipped'
  },
  created: {
    icon: 'icon-radio_button_checked',
    code: 'created',
    display: 'Created'
  },
  manual: {
    icon: 'icon-radio_button_checked',
    code: 'manual',
    display: 'Manual'
  }
};
var Column = _Table.Column;
export default injectIntl(observer(function (props) {
  var _usePipelineStore = usePipelineStore(),
      ciTableDS = _usePipelineStore.ciTableDS,
      _usePipelineStore$pip = _usePipelineStore.pipelineActionStore,
      cancelPipeline = _usePipelineStore$pip.cancelPipeline,
      retryPipeline = _usePipelineStore$pip.retryPipeline,
      organizationId = _usePipelineStore.organizationId,
      formatMessage = _usePipelineStore.intl.formatMessage,
      projectId = _usePipelineStore.AppState.currentMenuType.projectId,
      pipelineActionStore = _usePipelineStore.pipelineActionStore;

  var styles = props.styles;

  var _useCodeManagerStore = useCodeManagerStore(),
      appServiceDs = _useCodeManagerStore.appServiceDs,
      selectAppDs = _useCodeManagerStore.selectAppDs;

  var appServiceId = selectAppDs.current.get('appServiceId');
  handleMapStore.setCodeManagerCiPipelineManage({
    refresh: handleRefresh,
    select: handleChange
  });

  function handleRefresh() {
    ciTableDS.query();
  }

  function handleChange() {
    ciTableDS.query();
  }

  function linkToNewMerge(_x) {
    return _linkToNewMerge.apply(this, arguments);
  }

  function _linkToNewMerge() {
    _linkToNewMerge = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url) {
      var res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return pipelineActionStore.checkLinkToGitlab(projectId, appServiceId);

            case 3:
              res = _context.sent;
              window.open(url);
              _context.next = 9;
              break;

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

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

  function renderStatus(_ref) {
    var value = _ref.value,
        record = _ref.record;
    var gitlabUrl = record && record.get('gitlabUrl');
    var pipelineId = record && record.get('pipelineId');

    if (value) {
      var _ICONS$value;

      return /*#__PURE__*/React.createElement("div", {
        className: "c7n-status"
      }, /*#__PURE__*/React.createElement("span", {
        onClick: function onClick() {
          return linkToNewMerge(gitlabUrl ? "".concat(gitlabUrl.slice(0, -4), "/pipelines/").concat(pipelineId) : null);
        },
        className: "c7n-status-link"
      }, /*#__PURE__*/React.createElement("i", {
        className: "icon ".concat((_ICONS$value = ICONS[value]) === null || _ICONS$value === void 0 ? void 0 : _ICONS$value.icon, " c7n-icon-").concat(value, " c7n-icon-lg")
      }), /*#__PURE__*/React.createElement("span", {
        className: "c7n-text-status black"
      }, ICONS[value].display)));
    } else {
      return 'Null';
    }
  }

  function renderSign(_ref2) {
    var record = _ref2.record;
    var gitlabUrl = record && record.get('gitlabUrl');
    var pipelineId = record && record.get('pipelineId');
    var pipelineUserLoginName = record && record.get('pipelineUserLoginName');
    var pipelineUserName = record && record.get('pipelineUserName');
    var latest = record && record.get('latest');
    var pipelineUserUrl = record && record.get('pipelineUserUrl');
    return /*#__PURE__*/React.createElement("div", {
      className: "c7n-cipip-sign"
    }, /*#__PURE__*/React.createElement("div", {
      className: "c7n-des-sign"
    }, /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement("span", {
      className: "c7n-link-decoration",
      onClick: function onClick() {
        return linkToNewMerge(gitlabUrl ? "".concat(gitlabUrl.slice(0, -4), "/pipelines/").concat(pipelineId) : null);
      }
    }, /*#__PURE__*/React.createElement("span", {
      className: "mr7 black"
    }, "#", pipelineId)), "by"), /*#__PURE__*/React.createElement(_Tooltip, {
      placement: "top",
      title: pipelineUserName ? "".concat(pipelineUserName).concat(pipelineUserLoginName ? "(".concat(pipelineUserLoginName, ")") : '') : '',
      trigger: "hover"
    }, pipelineUserUrl ? /*#__PURE__*/React.createElement("img", {
      className: "c7n-image-avatar m8",
      src: pipelineUserUrl,
      alt: "avatar"
    }) : /*#__PURE__*/React.createElement("span", {
      className: "c7n-avatar m8 mt3"
    }, pipelineUserName ? pipelineUserName.substring(0, 1).toUpperCase() : ''))), latest ? /*#__PURE__*/React.createElement(_Tooltip, {
      placement: "top",
      title: "Latest pipeline for this branch",
      trigger: "hover"
    }, /*#__PURE__*/React.createElement("span", {
      title: "",
      className: "c7n-latest"
    }, "latest")) : null);
  }

  function handleAction(record) {
    var status = record && record.get('status');
    var gitlabProjectId = record && record.get('gitlabProjectId');
    var pipelineId = record && record.get('pipelineId');

    if (status === 'running' || status === 'pending') {
      cancelPipeline(gitlabProjectId, pipelineId, organizationId);
    } else {
      retryPipeline(gitlabProjectId, pipelineId, organizationId);
    }

    ciTableDS.query();
  }

  function renderAction(_ref3) {
    var record = _ref3.record;
    var status = record.get('status');

    if (status && status !== 'passed' && status !== 'success' && status !== 'skipped') {
      var action = [{
        service: [status === 'running' || status === 'pending' ? 'choerodon.code.project.develop.code-management.ps.ci.cancel' : 'choerodon.code.project.develop.code-management.ps.ci.retry'],
        text: formatMessage({
          id: status === 'running' || status === 'pending' ? 'cancel' : 'retry'
        }),
        action: handleAction.bind(this, record)
      }];
      return /*#__PURE__*/React.createElement(Action, {
        data: action
      });
    } else {
      return null;
    }
  }

  function renderCommit(_ref4) {
    var record = _ref4.record;
    var gitlabUrl = record.get('gitlabUrl');
    var ref = record.get('ref');
    var commit = record.get('commit');
    var commitUserName = record.get('commitUserName');
    var commitUserUrl = record.get('commitUserUrl');
    var commitUserLoginName = record.get('commitUserLoginName');
    var commitContent = record.get('commitContent');

    if (!ref && !commit) {
      return null;
    }

    return /*#__PURE__*/React.createElement("div", {
      className: "c7n-commit"
    }, /*#__PURE__*/React.createElement("div", {
      className: "c7n-title-commit"
    }, /*#__PURE__*/React.createElement("i", {
      className: "icon icon-branch mr7"
    }), /*#__PURE__*/React.createElement(MouserOverWrapper, {
      text: ref,
      width: 0.1
    }, /*#__PURE__*/React.createElement("span", {
      className: "c7n-link-decoration",
      onClick: function onClick() {
        return linkToNewMerge(gitlabUrl ? "".concat(gitlabUrl.slice(0, -4), "/commits/").concat(ref) : null);
      }
    }, /*#__PURE__*/React.createElement("span", {
      className: "black"
    }, ref))), /*#__PURE__*/React.createElement("i", {
      className: "icon icon-point m8"
    }), /*#__PURE__*/React.createElement(_Tooltip, {
      placement: "top",
      title: commit,
      trigger: "hover"
    }, /*#__PURE__*/React.createElement("span", {
      className: "c7n-link-decoration",
      onClick: function onClick() {
        return linkToNewMerge(gitlabUrl ? "".concat(gitlabUrl.slice(0, -4), "/commit/").concat(commit) : null);
      }
    }, /*#__PURE__*/React.createElement("span", null, commit ? commit.slice(0, 8) : '')))), /*#__PURE__*/React.createElement("div", {
      className: "c7n-des-commit"
    }, /*#__PURE__*/React.createElement(_Tooltip, {
      placement: "top",
      title: commitUserName ? "".concat(commitUserName).concat(commitUserLoginName ? "(".concat(commitUserLoginName, ")") : '') : '',
      trigger: "hover"
    }, commitUserUrl ? /*#__PURE__*/React.createElement("img", {
      className: "c7n-image-avatar",
      src: commitUserUrl,
      alt: "avatar"
    }) : /*#__PURE__*/React.createElement("span", {
      className: "c7n-avatar mr7"
    }, commitUserName ? commitUserName.substring(0, 1).toUpperCase() : '')), /*#__PURE__*/React.createElement(MouserOverWrapper, {
      text: commitContent,
      width: 0.2
    }, /*#__PURE__*/React.createElement("span", {
      className: "c7n-link-decoration",
      onClick: function onClick() {
        return linkToNewMerge(gitlabUrl ? "".concat(gitlabUrl.slice(0, -4), "/commit/").concat(commit) : null);
      }
    }, /*#__PURE__*/React.createElement("span", {
      className: "gray"
    }, commitContent)))));
  }

  function renderStages(_ref5) {
    var value = _ref5.value,
        record = _ref5.record;
    var gitlabUrl = record.get('gitlabUrl');
    var stages = value.slice();
    var pipeStage = [];

    if (stages && stages.length) {
      var _loop = function _loop(i, l) {
        pipeStage.push( /*#__PURE__*/React.createElement("span", {
          className: "c7n-jobs",
          key: i
        }, i !== 0 ? /*#__PURE__*/React.createElement("span", {
          className: "c7n-split-before"
        }) : null, /*#__PURE__*/React.createElement(_Tooltip, {
          title: stages[i].name === 'sonarqube' && stages[i].status === 'failed' ? "".concat(stages[i].name, " : ").concat(stages[i].description) : "".concat(stages[i].name, " : ").concat(stages[i].status)
        }, stages[i].name === 'sonarqube' ? /*#__PURE__*/React.createElement("i", {
          className: "icon ".concat(ICONS[stages[i].status || 'skipped'].icon || '', "\n                c7n-icon-").concat(stages[i].status, " c7n-icon-lg")
        }) : /*#__PURE__*/React.createElement("span", {
          className: "c7n-link-icon",
          onClick: function onClick() {
            return linkToNewMerge(gitlabUrl ? "".concat(gitlabUrl.slice(0, -4), "/-/jobs/").concat(stages[i].id) : null);
          }
        }, /*#__PURE__*/React.createElement("i", {
          className: "icon ".concat(ICONS[stages[i].status || 'skipped'].icon || '', "\n                c7n-icon-").concat(stages[i].status, " c7n-icon-lg")
        })))));
      };

      for (var i = 0, l = stages.length; i < l; i += 1) {
        _loop(i, l);
      }
    }

    return /*#__PURE__*/React.createElement("div", {
      className: "c7n-jobs"
    }, pipeStage);
  }

  function renderTime(value) {
    var pipelineTime = value;

    if (pipelineTime) {
      if (pipelineTime.split('.')[1] === '00') {
        pipelineTime = "".concat(pipelineTime.toString().split('.')[0]).concat(formatMessage({
          id: 'minutes'
        }));
      } else if (pipelineTime.split('.')[0] === '0') {
        pipelineTime = "".concat((Number(pipelineTime.toString().split('.')[1]) * 0.6).toFixed()).concat(formatMessage({
          id: 'seconds'
        }));
      } else if (pipelineTime.split('.').length === 2) {
        pipelineTime = "".concat(pipelineTime.toString().split('.')[0]).concat(formatMessage({
          id: 'minutes'
        })).concat((Number(pipelineTime.toString().split('.')[1]) * 0.6).toFixed()).concat(formatMessage({
          id: 'seconds'
        }));
      } else {
        pipelineTime = null;
      }

      return pipelineTime;
    } else {
      return '--';
    }
  }

  function renderTimeSpan(_ref6) {
    var value = _ref6.value;
    return /*#__PURE__*/React.createElement("span", null, renderTime(value));
  }

  function renderDateTooltip(_ref7) {
    var value = _ref7.value;
    return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(_Tooltip, {
      title: value
    }, /*#__PURE__*/React.createElement(TimeAgo, {
      datetime: value,
      locale: formatMessage({
        id: 'language'
      })
    })));
  }

  return /*#__PURE__*/React.createElement(Page, {
    className: classNames('c7n-ciPipeline', 'page-container', styles === null || styles === void 0 ? void 0 : styles['c7n-branch-theme4-page']),
    service: []
  }, appServiceDs.status !== 'ready' || !appServiceId ? /*#__PURE__*/React.createElement(Loading, {
    display: true
  }) : /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-tab-table"
  }, /*#__PURE__*/React.createElement(_Table, {
    className: "c7n-pipineline-table",
    queryBar: "none",
    dataSet: ciTableDS,
    size: "small"
  }, /*#__PURE__*/React.createElement(Column, {
    name: "status",
    renderer: renderStatus,
    width: 100
  }), /*#__PURE__*/React.createElement(Column, {
    name: "pipelineId",
    renderer: renderSign
  }), /*#__PURE__*/React.createElement(Column, {
    name: "gitlabProjectId",
    renderer: renderAction,
    width: 60
  }), /*#__PURE__*/React.createElement(Column, {
    name: "commit",
    renderer: renderCommit
  }), /*#__PURE__*/React.createElement(Column, {
    name: "stages",
    renderer: renderStages
  }), /*#__PURE__*/React.createElement(Column, {
    name: "pipelineTime",
    renderer: renderTimeSpan,
    width: 120
  }), /*#__PURE__*/React.createElement(Column, {
    name: "creationDate",
    renderer: renderDateTooltip,
    width: 120
  }))));
}));