import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
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 _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, { Fragment, useState, useMemo } from 'react';
import { observer } from 'mobx-react-lite';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Permission, Choerodon } from '@choerodon/boot';
import { withRouter } from 'react-router-dom';
import pick from 'lodash/pick';
import map from 'lodash/map';
import UserInfo from "../../../../components/userInfo";
import DetailTitle from "./components/detailTitle";
import DetailCard from "./components/detailCard";
import PendingCheckModal from "../../components/pendingCheckModal";
import { TRIGGER_TYPE_MANUAL } from "./components/Constants";
import { handlePromptError } from "../../../../utils";
import "./index.less";

var modalKey = _Modal.key();

export default withRouter(injectIntl(observer(function (_ref) {
  var dataSet = _ref.dataSet,
      PipelineStore = _ref.PipelineStore,
      projectId = _ref.projectId,
      id = _ref.id,
      intlPrefix = _ref.intlPrefix,
      formatMessage = _ref.intl.formatMessage,
      modal = _ref.modal,
      freshTable = _ref.refresh,
      _ref$location = _ref.location,
      search = _ref$location.search,
      pathname = _ref$location.pathname;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      showPendingCheck = _useState2[0],
      setShowPendingCheck = _useState2[1];

  var _useState3 = useState({}),
      _useState4 = _slicedToArray(_useState3, 2),
      checkData = _useState4[0],
      setCheckData = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      isChange = _useState6[0],
      setIsChange = _useState6[1];

  var data = useMemo(function () {
    return dataSet.current.toData();
  }, [dataSet.current]);

  function refresh() {
    dataSet.query();
    setIsChange(true);
  }

  modal.handleOk(function () {
    var param = search.match(/(^|&)pipelineRecordId=([^&]*)(&|$)/);

    if (param) {
      var newSearch = search.replace(param[0], '');
      window.location.hash = "".concat(pathname).concat(newSearch);
    } else if (isChange) {
      freshTable();
    }
  });

  function openModal(type) {
    _Modal.open({
      key: modalKey,
      title: formatMessage({
        id: "pipeline.".concat(type, ".title")
      }),
      children: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "pipeline.".concat(type, ".des")
      }),
      onOk: function onOk() {
        return handleSubmit(type);
      }
    });
  }
  /**
   * 处理强制失败或重试
   */


  function handleSubmit(_x) {
    return _handleSubmit.apply(this, arguments);
  }
  /**
   * 关闭人工审核弹窗
   * @param flag 是否重新加载列表数据
   */


  function _handleSubmit() {
    _handleSubmit = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(type) {
      var result;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              result = null;

              if (!(type === 'stop')) {
                _context.next = 8;
                break;
              }

              _context.next = 5;
              return PipelineStore.manualStop(projectId, id);

            case 5:
              result = _context.sent;
              _context.next = 12;
              break;

            case 8:
              if (!(type === 'retry')) {
                _context.next = 12;
                break;
              }

              _context.next = 11;
              return PipelineStore.retry(projectId, id);

            case 11:
              result = _context.sent;

            case 12:
              if (!handlePromptError(result, false)) {
                _context.next = 16;
                break;
              }

              refresh();
              _context.next = 17;
              break;

            case 16:
              return _context.abrupt("return", false);

            case 17:
              _context.next = 23;
              break;

            case 19:
              _context.prev = 19;
              _context.t0 = _context["catch"](0);
              Choerodon.handleResponseError(_context.t0);
              return _context.abrupt("return", false);

            case 23:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[0, 19]]);
    }));
    return _handleSubmit.apply(this, arguments);
  }

  function closePendingCheck(flag) {
    flag && refresh();
    setShowPendingCheck(false);
    setCheckData({});
  }
  /**
   * 打开人工审核弹窗
   */


  function openPendingCheck() {
    setShowPendingCheck(true);
    setCheckData(pick(data, ['type', 'stageRecordId', 'taskRecordId', 'stageName']));
  }
  /**
   * 获取右侧按钮
   */


  function renderButton() {
    var status = data.status,
        execute = data.execute;
    var dom = null;

    switch (status) {
      case 'running':
        dom = /*#__PURE__*/React.createElement(Permission, {
          service: ['choerodon.code.project.deploy.app-deployment.deployment-operation.ps.failed']
        }, /*#__PURE__*/React.createElement(_Button, {
          onClick: function onClick() {
            return openModal('stop');
          },
          icon: "power_settings_new",
          type: "primary",
          className: "c7ncd-pipeline-manual-stop"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "pipeline.flow.failed"
        })));
        break;

      case 'failed':
        execute && (dom = /*#__PURE__*/React.createElement(Permission, {
          service: ['choerodon.code.project.deploy.app-deployment.deployment-operation.ps.retry-detail']
        }, /*#__PURE__*/React.createElement(_Button, {
          onClick: function onClick() {
            return openModal('retry');
          },
          icon: "replay",
          type: "primary",
          className: "c7ncd-pipeline-manual-stop"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "pipelineRecord.retry"
        }))));
        break;

      case 'pendingcheck':
        execute && (dom = /*#__PURE__*/React.createElement(Permission, {
          service: ['choerodon.code.project.deploy.app-deployment.deployment-operation.ps.auto']
        }, /*#__PURE__*/React.createElement(_Button, {
          onClick: openPendingCheck,
          icon: "authorize",
          type: "primary",
          className: "c7ncd-pipeline-manual-stop"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "pipelineRecord.check.manual"
        }))));
        break;

      default:
        break;
    }

    return dom;
  }

  function renderPipeline() {
    var stageRecordDTOS = data.stageRecordDTOS,
        pipelineStatus = data.status;
    var isPipelineCadence = pipelineStatus === 'stop';
    return map(stageRecordDTOS, function (_ref2, stageIndex) {
      var dtoId = _ref2.id,
          index = _ref2.index,
          status = _ref2.status,
          stageName = _ref2.stageName,
          executionTime = _ref2.executionTime,
          userDTOS = _ref2.userDTOS,
          triggerType = _ref2.triggerType,
          isParallel = _ref2.isParallel,
          taskRecordDTOS = _ref2.taskRecordDTOS;
      return /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-pipeline-detail-stage",
        key: dtoId
      }, /*#__PURE__*/React.createElement(DetailTitle, {
        isCadence: isPipelineCadence,
        checking: index,
        name: stageName,
        time: executionTime,
        type: triggerType,
        user: userDTOS,
        status: status,
        head: stageIndex === 0,
        tail: stageIndex === stageRecordDTOS.length - 1,
        onlyOne: stageRecordDTOS.length === 1
      }), /*#__PURE__*/React.createElement(DetailCard, {
        isParallel: isParallel,
        tasks: taskRecordDTOS ? taskRecordDTOS.slice() : []
      }));
    });
  }

  function renderUserInfo() {
    var triggerType = data.triggerType,
        userDTO = data.userDTO;

    var _ref3 = userDTO || {},
        loginName = _ref3.loginName,
        realName = _ref3.realName,
        imageUrl = _ref3.imageUrl;

    return triggerType === TRIGGER_TYPE_MANUAL && /*#__PURE__*/React.createElement("div", {
      className: "c7ncd-pipeline-detail-item"
    }, /*#__PURE__*/React.createElement("span", {
      className: "c7ncd-pipeline-detail-label"
    }, formatMessage({
      id: 'pipeline.trigger.people'
    })), /*#__PURE__*/React.createElement(UserInfo, {
      avatar: imageUrl,
      name: realName || '',
      id: loginName
    }));
  }

  return /*#__PURE__*/React.createElement("div", {
    className: "c7n-region c7n-pipeline-detail"
  }, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-pipeline-detail-msg"
  }, /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-pipeline-detail-item"
  }, /*#__PURE__*/React.createElement("span", {
    className: "c7ncd-pipeline-detail-label"
  }, formatMessage({
    id: 'pipeline.trigger.type'
  })), data.triggerType && /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "pipeline.trigger.".concat(data.triggerType)
  })), renderUserInfo(), /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-pipeline-detail-item"
  }, /*#__PURE__*/React.createElement("span", {
    className: "c7ncd-pipeline-detail-label"
  }, formatMessage({
    id: "".concat(intlPrefix, ".result")
  })), data.status && /*#__PURE__*/React.createElement("span", {
    className: "c7ncd-pipeline-status-tag c7ncd-pipeline-status-tag_".concat(data.status)
  }, /*#__PURE__*/React.createElement(FormattedMessage, {
    id: "pipelineRecord.status.".concat(data.status)
  }))), renderButton()), /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-pipeline-main"
  }, /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-pipeline-scroll"
  }, renderPipeline()))), showPendingCheck && /*#__PURE__*/React.createElement(PendingCheckModal, {
    id: id,
    name: data.pipelineName,
    checkData: checkData,
    onClose: closePendingCheck,
    PipelineRecordStore: PipelineStore
  }));
})));