import "choerodon-ui/pro/lib/spin/style";
import _Spin from "choerodon-ui/pro/lib/spin";
import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/pro/lib/modal/style";
import _Modal from "choerodon-ui/pro/lib/modal";
import "choerodon-ui/pro/lib/table/style";
import _Table from "@hzero-front-ui/c7n-ui/lib/TablePro";

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

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

/* eslint-disable */
import React, { useEffect, useState, Fragment } from 'react';
import _ from 'lodash';
import { withRouter } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import { FormattedMessage } from 'react-intl';
import { Permission, Content, Header, Page, Action, Breadcrumb, Choerodon, HeaderButtons } from '@choerodon/boot';
import { usePiplineStore } from "./stores";
import { handlePromptError } from "../../utils";
import checkPermission from "../../utils/checkPermission";
import pipelineCreateStore from "./stores/PipelineCreateStore";
import PipelineCreate from "./pipeline-create";
import PipelineEdit from "./pipeline-edit";
import StatusTags from "../../components/status-tag";
import TimePopover from "../../components/timePopover";
import UserInfo from "../../components/userInfo";
import "./index.less";
var Column = _Table.Column;

var modalKey = _Modal.key();

var STATUS_INVALID = 0;
var STATUS_ACTIVE = 1;
var EXECUTE_PASS = 'pass';
var EXECUTE_FAILED = 'failed';
var invalidModal;
var PiplelineTable = withRouter(observer(function (props) {
  var _usePiplineStore = usePiplineStore(),
      _usePiplineStore$AppS = _usePiplineStore.AppState.currentMenuType,
      organizationId = _usePiplineStore$AppS.id,
      projectId = _usePiplineStore$AppS.projectId,
      type = _usePiplineStore$AppS.type,
      projectName = _usePiplineStore$AppS.projectName,
      formatMessage = _usePiplineStore.intl.formatMessage,
      prefixCls = _usePiplineStore.prefixCls,
      piplineDS = _usePiplineStore.piplineDS,
      PiplineStore = _usePiplineStore.PiplineStore,
      history = _usePiplineStore.history,
      search = _usePiplineStore.location.search;

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

  useEffect(function () {
    function init() {
      return _init.apply(this, arguments);
    }

    function _init() {
      _init = _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 checkPermission({
                  projectId: projectId,
                  code: 'choerodon.code.project.deploy.app-deployment.pipeline.ps.pipeline-detail'
                });

              case 2:
                res = _context.sent;
                setCanDetail(res);

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

    init();
  }, []);

  function handleRefresh() {
    piplineDS.query();
  }
  /**
   * 跳转到部署页面
   * @param {*} id
   */


  function linkToRecord(id) {
    history.push({
      pathname: '/devops/deployment-operation',
      search: search
    });
  }

  function makeStatusInvalid(_x) {
    return _makeStatusInvalid.apply(this, arguments);
  }

  function _makeStatusInvalid() {
    _makeStatusInvalid = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(id) {
      var response;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return PiplineStore.changeStatus(projectId, id, STATUS_INVALID)["catch"](function (e) {
                Choerodon.handleResponseError(e);
              });

            case 2:
              response = _context2.sent;

              if (!handlePromptError(response)) {
                _context2.next = 6;
                break;
              }

              handleRefresh();
              return _context2.abrupt("return", true);

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

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

  function _handleDelete() {
    _handleDelete = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(id, itemName) {
      var response;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.next = 2;
              return PiplineStore.deletePipeline(projectId, id)["catch"](function (e) {
                Choerodon.handleResponseError(e);
              });

            case 2:
              response = _context3.sent;

              if (handlePromptError(response, false)) {
                handleRefresh();
              }

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

  function makeStatusActive(_x4) {
    return _makeStatusActive.apply(this, arguments);
  }
  /**
   * 打开删除模态框
   * @param {*} id
   * @param {*} itemName
   */


  function _makeStatusActive() {
    _makeStatusActive = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(id) {
      var response;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return PiplineStore.changeStatus(projectId, id, STATUS_ACTIVE)["catch"](function (e) {
                return Choerodon.handleResponseError(e);
              });

            case 2:
              response = _context4.sent;

              if (handlePromptError(response)) {
                handleRefresh();
              }

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

  function deletePipeline(id, itemName) {
    _Modal.open({
      key: modalKey,
      title: "".concat(formatMessage({
        id: 'pipeline.invalid'
      }), "\u201C").concat(itemName, "\u201D"),
      children: '确认要删除吗？',
      okText: formatMessage({
        id: 'delete'
      }),
      okProps: {
        color: 'red'
      },
      cancelProps: {
        color: 'dark'
      },
      onOk: handleDelete.bind(this, id, itemName)
    });
  }
  /**
   * 打开invalid模态框
   * @param {*} id
   * @param {*} itemName
   */


  function openInvalid(id, itemName) {
    invalidModal = _Modal.open({
      key: modalKey,
      title: "".concat(formatMessage({
        id: 'pipeline.invalid'
      }), "\u201C").concat(itemName, "\u201D"),
      children: [/*#__PURE__*/React.createElement("div", {
        className: "c7n-padding-top_8"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "pipeline.invalid.message"
      }))],
      onOk: makeStatusInvalid.bind(this, id),
      okText: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "submit"
      }),
      cancelText: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "cancel"
      })
    });
  }
  /**
   * 打开编辑页面
   * @param id
   */


  function linkToEdit(_x5) {
    return _linkToEdit.apply(this, arguments);
  }

  function _linkToEdit() {
    _linkToEdit = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5(id) {
      var result;
      return regeneratorRuntime.wrap(function _callee5$(_context5) {
        while (1) {
          switch (_context5.prev = _context5.next) {
            case 0:
              pipelineCreateStore.setEditId(id);
              _context5.next = 3;
              return pipelineCreateStore.loadDetail(projectId, id);

            case 3:
              result = _context5.sent;

              if (result) {
                pipelineCreateStore.loadUser(projectId, 1, '', result.pipelineUserRels);
                pipelineCreateStore.setEditVisible(true);
              }

            case 5:
            case "end":
              return _context5.stop();
          }
        }
      }, _callee5);
    }));
    return _linkToEdit.apply(this, arguments);
  }

  function handleClickName(e, id) {
    e.preventDefault();
    linkToEdit(id);
  }

  function gotoRecord(id, name) {
    if (id) {
      history.push({
        pathname: '/devops/deployment-operation',
        search: search,
        state: {
          pipelineId: id,
          pipelineName: name,
          backPath: "/devops/pipeline".concat(search)
        }
      });
    }
  }
  /**
   * 跳转到创建页面
   */


  function showCreate() {// pipelineCreateStore.loadUser(projectId);
    // pipelineCreateStore.setCreateVisible(true);
  }
  /** ************* 启用、停用 **************** */


  function renderStatus(_ref) {
    var record = _ref.record;
    var id = record && record.get('id');
    var isEnabled = record && record.get('isEnabled');
    var itemName = record && record.get('name');
    return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(StatusTags, {
      name: formatMessage({
        id: isEnabled !== '0' ? 'active' : 'stop'
      }),
      color: isEnabled !== '0' ? '#00bfa5' : '#cecece'
    }), isEnabled !== '0' && canDetail ? /*#__PURE__*/React.createElement("a", {
      className: "".concat(prefixCls, "-status-a"),
      onClick: function onClick(e) {
        handleClickName(e, id);
      }
    }, itemName) : /*#__PURE__*/React.createElement("span", {
      style: {
        marginLeft: '0.08rem'
      }
    }, itemName));
  }

  function renderAction(_ref2) {
    var record = _ref2.record;
    var id = record && record.get('id');
    var isEnabled = record && record.get('isEnabled');
    var itemName = record && record.get('name');
    var itemTriggerType = record.get('triggerType');
    var execute = record && record.get('execute');
    var edit = record && record.get('edit');

    var filterItem = function filterItem(collection, predicate) {
      return _.filter(collection, function (item) {
        return Array.isArray(predicate) ? !_.includes(predicate, item) : item !== predicate;
      });
    };

    var action = {
      execute: {
        service: ['choerodon.code.project.deploy.app-deployment.pipeline.ps.execute'],
        text: formatMessage({
          id: 'pipeline.action.run'
        }),
        action: openExecuteCheck.bind(this, id, itemName)
      },
      disabled: {
        service: ['choerodon.code.project.deploy.app-deployment.pipeline.ps.disable'],
        text: formatMessage({
          id: 'stop'
        }),
        action: openInvalid.bind(this, id, itemName)
      },
      enable: {
        service: ['choerodon.code.project.deploy.app-deployment.pipeline.ps.enable'],
        text: formatMessage({
          id: 'active'
        }),
        action: makeStatusActive.bind(this, id)
      },
      remove: {
        service: ['choerodon.code.project.deploy.app-deployment.pipeline.ps.delete'],
        text: formatMessage({
          id: 'delete'
        }),
        action: deletePipeline.bind(this, id, itemName)
      } // record: {
      //   service: ['choerodon.code.project.deploy.app-deployment.pipeline.ps.record'],
      //   text: formatMessage({ id: 'pipeline.all.record' }),
      //   action: gotoRecord.bind(this, id, itemName),
      // },

    };

    var actionItem = _.keys(action);

    actionItem = filterItem(actionItem, isEnabled !== '0' ? 'enable' : 'disabled');

    if (itemTriggerType === 'auto' || !execute) {
      actionItem = filterItem(actionItem, 'execute');
    }

    if (!edit) {
      actionItem = filterItem(actionItem, ['remove']);
    }

    return /*#__PURE__*/React.createElement(Action, {
      data: _.map(actionItem, function (item) {
        return _objectSpread({}, action[item]);
      })
    });
  }

  function renderTrigger(_ref3) {
    var value = _ref3.value;
    return /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "pipeline.trigger.".concat(value)
    });
  }

  function renderDate(_ref4) {
    var value = _ref4.value;
    return /*#__PURE__*/React.createElement(TimePopover, {
      content: value
    });
  }

  function renderUser(_ref5) {
    var record = _ref5.record;
    var createUserRealName = record && record.get('createUserRealName');
    var createUserName = record && record.get('createUserName');
    var createUserUrl = record && record.get('createUserUrl');
    return /*#__PURE__*/React.createElement(UserInfo, {
      avatar: createUserUrl || '',
      name: createUserRealName || '',
      id: createUserName || ''
    });
  }
  /**
     * 打开execute模态框
     * @param {*} id
     * @param {*} itemName
     */


  function openExecuteCheck(_x6, _x7) {
    return _openExecuteCheck.apply(this, arguments);
  }

  function _openExecuteCheck() {
    _openExecuteCheck = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6(id, itemName) {
      var myModal, response, executeStatus, envName;
      return regeneratorRuntime.wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              myModal = _Modal.open({
                key: modalKey,
                title: "".concat(formatMessage({
                  id: 'pipeline.execute'
                }), "\u201C").concat(itemName, "\u201D"),
                // footer: null,
                okCancel: false,
                onOk: function onOk() {
                  return true;
                },
                okText: /*#__PURE__*/React.createElement(FormattedMessage, {
                  id: "close"
                }),
                children: /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(_Spin, {
                  size: "small"
                }), "\xA0", /*#__PURE__*/React.createElement("span", {
                  className: "".concat(prefixCls, "-execute")
                }, formatMessage({
                  id: 'pipeline.execute.checking'
                })))
              });
              _context6.next = 3;
              return PiplineStore.checkExcecute(projectId, id)["catch"](function (e) {
                return Choerodon.handleResponseError(e);
              });

            case 3:
              response = _context6.sent;

              if (response && response.permission && response.versions) {
                envName = response.envName;
                executeStatus = EXECUTE_PASS;
              } else if (response && response.failed) {
                executeStatus = EXECUTE_FAILED;
              } else {
                executeStatus = EXECUTE_FAILED;
              }

              myModal.update({
                okCancel: true,
                okText: !envName && executeStatus !== 'failed' ? /*#__PURE__*/React.createElement(FormattedMessage, {
                  id: "submit"
                }) : /*#__PURE__*/React.createElement(FormattedMessage, {
                  id: "iknow"
                }),
                onOk: function onOk() {
                  return !envName && executeStatus !== 'failed' ? executeFun(id, myModal) : true;
                },
                children: envName ? /*#__PURE__*/React.createElement(FormattedMessage, {
                  id: "pipeline.execute.no.permission",
                  values: {
                    envName: envName
                  }
                }) : /*#__PURE__*/React.createElement(FormattedMessage, {
                  id: "pipeline.execute.".concat(executeStatus)
                }),
                footer: function footer(okBtn, cancelBtn) {
                  return /*#__PURE__*/React.createElement(Fragment, null, executeStatus !== 'failed' && cancelBtn, okBtn);
                }
              });

            case 6:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6);
    }));
    return _openExecuteCheck.apply(this, arguments);
  }

  function executeFun(_x8, _x9) {
    return _executeFun.apply(this, arguments);
  }

  function _executeFun() {
    _executeFun = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(id, myModal) {
      var response;
      return regeneratorRuntime.wrap(function _callee7$(_context7) {
        while (1) {
          switch (_context7.prev = _context7.next) {
            case 0:
              _context7.next = 2;
              return PiplineStore.executePipeline(projectId, id)["catch"](function (e) {
                return Choerodon.handleResponseError(e);
              });

            case 2:
              response = _context7.sent;

              if (handlePromptError(response, false)) {
                linkToRecord(id);
                myModal.close();
              }

              handleRefresh();

            case 5:
            case "end":
              return _context7.stop();
          }
        }
      }, _callee7);
    }));
    return _executeFun.apply(this, arguments);
  }

  return /*#__PURE__*/React.createElement(Page, {
    className: "c7n-region",
    service: ['choerodon.code.project.deploy.app-deployment.pipeline.ps.default']
  }, /*#__PURE__*/React.createElement(Header, {
    title: /*#__PURE__*/React.createElement(FormattedMessage, {
      id: "pipeline.head"
    })
  }, /*#__PURE__*/React.createElement(HeaderButtons, {
    showClassName: false,
    items: [{
      name: /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "pipeline.header.create"
      }),
      icon: 'playlist_add',
      display: true,
      disabled: true,
      permissions: ['choerodon.code.project.deploy.app-deployment.pipeline.ps.create'],
      handler: showCreate
    }, {
      icon: 'refresh',
      display: true,
      handler: handleRefresh
    }]
  })), /*#__PURE__*/React.createElement("div", {
    className: "c7ncd-tips"
  }, /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement(_Icon, {
    style: {
      position: 'relative',
      bottom: '2px'
    },
    type: "warning"
  }), "\u6CE8\u610F\uFF1A"), /*#__PURE__*/React.createElement("ul", null, /*#__PURE__*/React.createElement("li", null, "\u7531\u4E8ECICD\u9636\u6BB5\u5DF2\u5408\u5E76\u4E3A\u3010\u5E94\u7528\u6D41\u6C34\u7EBF\u3011\uFF0C\u56E0\u6B64\u3010\u90E8\u7F72-\u6D41\u6C34\u7EBF\u3011\u9875\u9762\u5C06\u5728\u8FD1\u671F\u79FB\u9664\u3002"), /*#__PURE__*/React.createElement("li", null, "\u76EE\u524D\u6B64\u9875\u9762\u4E0D\u518D\u652F\u6301\u521B\u5EFA\u4E0E\u4FEE\u6539\uFF0C\u540C\u65F6\u6D41\u6C34\u7EBF\u5BF9\u5E94\u7684\u6267\u884C\u8BB0\u5F55\u4E5F\u5C06\u4E0D\u518D\u4FDD\u7559\uFF1B\u4F46\u4E0D\u4F1A\u5F71\u54CD\u6B64\u9875\u9762\u6D41\u6C34\u7EBF\u7684\u6B63\u5E38\u89E6\u53D1\u4E0E\u6267\u884C\u3002"), /*#__PURE__*/React.createElement("li", null, "\u8BF7\u52A1\u5FC5\u5C3D\u5FEB\u5C06\u4E0B\u65B9\u7684\u6D41\u6C34\u7EBF\u7EF4\u62A4\u81F3\u3010\u5F00\u53D1-\u5E94\u7528\u6D41\u6C34\u7EBF\u3011\u9875\u9762\uFF0C\u7136\u540E\u5C06\u6B64\u9875\u9762\u7684\u6D41\u6C34\u7EBF\u505C\u7528\u5E76\u5220\u9664\u3002"))), /*#__PURE__*/React.createElement(Breadcrumb, null), /*#__PURE__*/React.createElement(Content, {
    className: "".concat(prefixCls, "-content")
  }, /*#__PURE__*/React.createElement(_Table, {
    queryBar: "advancedBar",
    dataSet: piplineDS,
    queryFieldsLimit: 3
  }, /*#__PURE__*/React.createElement(Column, {
    name: "isEnabled",
    renderer: renderStatus
  }), /*#__PURE__*/React.createElement(Column, {
    name: "action",
    renderer: renderAction,
    width: 60
  }), /*#__PURE__*/React.createElement(Column, {
    name: "triggerType",
    renderer: renderTrigger
  }), /*#__PURE__*/React.createElement(Column, {
    name: "envName"
  }), /*#__PURE__*/React.createElement(Column, {
    name: "createUserRealName",
    renderer: renderUser
  }), /*#__PURE__*/React.createElement(Column, {
    name: "lastUpdateDate",
    renderer: renderDate
  }))), pipelineCreateStore.createVisible ? /*#__PURE__*/React.createElement(PipelineCreate, {
    visible: pipelineCreateStore.createVisible,
    pipelineCreateStore: pipelineCreateStore,
    refreshTable: handleRefresh
  }) : null, pipelineCreateStore.editId ? /*#__PURE__*/React.createElement(PipelineEdit, {
    visible: pipelineCreateStore.editVisible,
    PipelineCreateStore: pipelineCreateStore,
    refreshTable: handleRefresh
  }) : null);
}));
export default PiplelineTable;