import "choerodon-ui/lib/icon/style";
import _Icon from "choerodon-ui/lib/icon";
import "choerodon-ui/pro/lib/button/style";
import _Button from "choerodon-ui/pro/lib/button";
import "choerodon-ui/lib/tooltip/style";
import _Tooltip from "choerodon-ui/lib/tooltip";
import "choerodon-ui/lib/radio/style";
import _Radio from "choerodon-ui/lib/radio";
import "choerodon-ui/lib/select/style";
import _Select from "choerodon-ui/lib/select";
import "choerodon-ui/lib/form/style";
import _Form from "choerodon-ui/lib/form";

var _dec, _dec2, _class;

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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/* eslint-disable */
import React, { Component, Fragment } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter, Prompt } from 'react-router-dom';
import { injectIntl, FormattedMessage } from 'react-intl';
import { Content, Header, Page, Choerodon } from '@choerodon/boot';
import _ from 'lodash';
import Sidebar from 'choerodon-ui/lib/modal/Sidebar';
import StageCard from "../components/stageCard";
import StageCreateModal from "../components/stageCreateModal";
import { STAGE_FLOW_AUTO, STAGE_FLOW_MANUAL, TRIGGER_TYPE_AUTO, TRIGGER_TYPE_MANUAL } from "../components/Constants";
import InterceptMask from "../../../components/intercept-mask";
import EmptyPage from "../components/emptyPage";
import "./index.less";
import "../../main.less";
var FormItem = _Form.Item;
var Option = _Select.Option;
var RadioGroup = _Radio.Group;
var formItemLayout = {
  labelCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 100
    }
  },
  wrapperCol: {
    xs: {
      span: 24
    },
    sm: {
      span: 26
    }
  }
};
var PipelineEdit = (_dec = _Form.create({}), _dec2 = inject('AppState'), _dec(_class = injectIntl(_class = withRouter(_class = _dec2(_class = observer(_class = /*#__PURE__*/function (_Component) {
  _inherits(PipelineEdit, _Component);

  var _super = _createSuper(PipelineEdit);

  function PipelineEdit() {
    var _this;

    _classCallCheck(this, PipelineEdit);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      triggerType: null,
      showCreate: false,
      prevId: null,
      submitLoading: false,
      promptDisplay: true
    };

    _this.onSubmit = function () {
      _this.setState({
        promptDisplay: false
      });

      var _this$props = _this.props,
          PipelineCreateStore = _this$props.PipelineCreateStore,
          validateFieldsAndScroll = _this$props.form.validateFieldsAndScroll,
          projectId = _this$props.AppState.currentMenuType.id,
          refreshTable = _this$props.refreshTable;
      var _PipelineCreateStore$ = PipelineCreateStore.getPipeline,
          objectVersionNumber = _PipelineCreateStore$.objectVersionNumber,
          id = _PipelineCreateStore$.id,
          name = _PipelineCreateStore$.name,
          triggerType = _PipelineCreateStore$.triggerType;
      validateFieldsAndScroll( /*#__PURE__*/function () {
        var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(err, _ref) {
          var users, getStageList, getTaskList, getPipeline, pipelineStageVOs, result;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  users = _ref.users;

                  if (err) {
                    _context.next = 10;
                    break;
                  }

                  getStageList = PipelineCreateStore.getStageList, getTaskList = PipelineCreateStore.getTaskList, getPipeline = PipelineCreateStore.getPipeline;
                  pipelineStageVOs = _.map(getStageList, function (item) {
                    return _objectSpread(_objectSpread({}, item), {}, {
                      pipelineTaskVOs: getTaskList[item.tempId] || null
                    });
                  });

                  _this.setState({
                    submitLoading: true
                  });

                  _context.next = 7;
                  return PipelineCreateStore.editPipeline(projectId, {
                    id: id,
                    objectVersionNumber: objectVersionNumber,
                    name: name,
                    triggerType: triggerType,
                    pipelineUserRels: triggerType === STAGE_FLOW_MANUAL ? _.map(users, function (item) {
                      return item;
                    }) : null,
                    pipelineStageVOs: pipelineStageVOs
                  })["catch"](function (e) {
                    _this.setState({
                      submitLoading: false
                    });

                    Choerodon.handleResponseError(e);
                  });

                case 7:
                  result = _context.sent;

                  _this.setState({
                    submitLoading: false
                  });

                  if (result && result.failed) {
                    Choerodon.prompt(result.message);
                  } else {
                    refreshTable();

                    _this.goBack();
                  }

                case 10:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));

        return function (_x, _x2) {
          return _ref2.apply(this, arguments);
        };
      }());
    };

    _this.changeTriggerType = function (e) {
      var PipelineCreateStore = _this.props.PipelineCreateStore;
      var triggerType = e.target.value;

      _this.setState({
        triggerType: triggerType
      });

      PipelineCreateStore.setTrigger(triggerType);

      if (triggerType === TRIGGER_TYPE_AUTO) {
        PipelineCreateStore.checkCanSubmit();
      } else {
        PipelineCreateStore.setCanSubmit(triggerType === TRIGGER_TYPE_MANUAL);
      }
    };

    _this.openCreateForm = function (prevId) {
      _this.setState({
        showCreate: true,
        prevId: prevId
      });
    };

    _this.closeCreateForm = function () {
      _this.setState({
        showCreate: false,
        prevId: null
      });
    };

    _this.goBack = function () {
      var PipelineCreateStore = _this.props.PipelineCreateStore;
      PipelineCreateStore.setEditVisible(false); // 解决页面尚未退出 但是数据已经为空的问题

      setTimeout(function () {
        PipelineCreateStore.setUser([]);
        PipelineCreateStore.clearStageList();
        PipelineCreateStore.setStageIndex(0);
        PipelineCreateStore.clearTaskList();
        PipelineCreateStore.clearTaskSettings();
        PipelineCreateStore.clearTaskIndex();
        PipelineCreateStore.setTrigger(STAGE_FLOW_AUTO);
        PipelineCreateStore.setPipeline([]);
      }, 150);
    };

    _this.loadMoreWrap = function (e) {
      e.stopPropagation();
      var _this$props2 = _this.props,
          projectId = _this$props2.AppState.currentMenuType.id,
          PipelineCreateStore = _this$props2.PipelineCreateStore;
      var getPageInfo = PipelineCreateStore.getPageInfo;

      var _ref3 = getPageInfo || {},
          pageNum = _ref3.pageNum;

      PipelineCreateStore.loadUser(projectId, pageNum + 1);
    };

    _this.handleSearch = _.debounce(function (value) {
      var _this$props3 = _this.props,
          projectId = _this$props3.AppState.currentMenuType.id,
          PipelineCreateStore = _this$props3.PipelineCreateStore;
      PipelineCreateStore.loadUser(projectId, 1, value);
    }, 700);

    _this.handleUserChange = function (value) {
      var setFieldsValue = _this.props.form.setFieldsValue;

      if (_.includes(value, 'pipeline-create-user-select-more-key')) {
        var realValue = _.remove(value, function (item) {
          return item === 'pipeline-create-user-select-more-key';
        });

        setFieldsValue({
          users: realValue
        });
      }
    };

    return _this;
  }

  _createClass(PipelineEdit, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props4 = this.props,
          PipelineCreateStore = _this$props4.PipelineCreateStore,
          id = _this$props4.AppState.currentMenuType.id;
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var PipelineCreateStore = this.props.PipelineCreateStore;
      PipelineCreateStore.setUser([]);
      PipelineCreateStore.clearStageList();
      PipelineCreateStore.setStageIndex(0);
      PipelineCreateStore.clearTaskList();
      PipelineCreateStore.clearTaskSettings();
      PipelineCreateStore.clearTaskIndex();
      PipelineCreateStore.setTrigger(STAGE_FLOW_AUTO);
      PipelineCreateStore.setPipeline([]);
    }
  }, {
    key: "renderPipelineDom",
    get: function get() {
      var _this2 = this;

      var getStageList = this.props.PipelineCreateStore.getStageList;

      if (getStageList.length === 1) {
        var _ref4 = getStageList[0] || {},
            tempId = _ref4.tempId,
            stageName = _ref4.stageName;

        return /*#__PURE__*/React.createElement(StageCard, {
          head: true,
          allowDelete: false,
          key: tempId,
          stageId: tempId,
          stageName: stageName,
          clickAdd: this.openCreateForm
        });
      }

      return _.map(getStageList, function (_ref5, stageIndex) {
        var tempId = _ref5.tempId,
            stageName = _ref5.stageName;
        return /*#__PURE__*/React.createElement(StageCard, {
          key: tempId,
          head: stageIndex === 0,
          stageId: tempId,
          stageName: stageName,
          clickAdd: _this2.openCreateForm
        });
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props5 = this.props,
          formatMessage = _this$props5.intl.formatMessage,
          getFieldDecorator = _this$props5.form.getFieldDecorator,
          PipelineCreateStore = _this$props5.PipelineCreateStore;
      var _this$state = this.state,
          triggerType = _this$state.triggerType,
          showCreate = _this$state.showCreate,
          prevId = _this$state.prevId,
          submitLoading = _this$state.submitLoading,
          promptDisplay = _this$state.promptDisplay;
      var getLoading = PipelineCreateStore.getLoading,
          getUser = PipelineCreateStore.getUser,
          getIsDisabled = PipelineCreateStore.getIsDisabled,
          getPipeline = PipelineCreateStore.getPipeline,
          getDetailLoading = PipelineCreateStore.getDetailLoading,
          getCanSubmit = PipelineCreateStore.getCanSubmit,
          visible = PipelineCreateStore.editVisible,
          getPageInfo = PipelineCreateStore.getPageInfo;
      var showUserSelector = triggerType ? triggerType === STAGE_FLOW_MANUAL : getPipeline.triggerType === STAGE_FLOW_MANUAL;

      var user = _.map(getUser, function (_ref6) {
        var id = _ref6.id,
            realName = _ref6.realName,
            loginName = _ref6.loginName;
        return /*#__PURE__*/React.createElement(Option, {
          key: id,
          value: String(id)
        }, /*#__PURE__*/React.createElement(_Tooltip, {
          title: loginName
        }, realName || loginName));
      });

      if (getPageInfo && getPageInfo.hasNextPage) {
        user.push( /*#__PURE__*/React.createElement(Option, {
          key: "pipeline-create-user-select-more-key",
          className: "c7n-load-more-wrap"
        }, /*#__PURE__*/React.createElement("div", {
          className: "c7n-option-popover",
          onClick: this.loadMoreWrap
        }, /*#__PURE__*/React.createElement("span", {
          className: "c7n-option-span"
        }, formatMessage({
          id: 'loadMore'
        })))));
      }

      var initUser = _.map(getPipeline.pipelineUserRels, function (item) {
        return String(item);
      });

      return /*#__PURE__*/React.createElement(Sidebar, {
        className: "c7n-region c7n-pipeline-creat",
        title: "".concat(formatMessage({
          id: 'pipeline.header.edit'
        }), "\"").concat(getPipeline.name, "\""),
        visible: visible,
        onOk: this.onSubmit,
        onCancel: this.goBack,
        okText: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "save"
        }),
        cancelText: /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "cancel"
        }),
        confirmLoading: submitLoading,
        keyboard: false,
        footer: [/*#__PURE__*/React.createElement(_Button, {
          key: "submit",
          color: "primary",
          funcType: "raised",
          onClick: this.onSubmit,
          loading: submitLoading,
          disabled: true // disabled={getIsDisabled || !getCanSubmit}

        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "save"
        })), /*#__PURE__*/React.createElement(_Button, {
          key: "cancel",
          funcType: "raised",
          onClick: this.goBack,
          disabled: submitLoading,
          className: "c7ncd-pipeline-btn-cancel"
        }, /*#__PURE__*/React.createElement(FormattedMessage, {
          id: "cancel"
        }))]
      }, _.isNull(getPipeline) ? /*#__PURE__*/React.createElement(EmptyPage, null) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Content, {
        className: "c7n-pipeline-content"
      }, /*#__PURE__*/React.createElement(_Form, {
        layout: "vertical"
      }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "c7n-select_512 c7ncd-formitem-bottom"
      }, formItemLayout), getFieldDecorator('triggerType', {
        initialValue: getPipeline.triggerType
      })( /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", {
        className: "radio-label"
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "pipeline.trigger"
      }), ":"), /*#__PURE__*/React.createElement(RadioGroup, {
        value: PipelineCreateStore.trigger,
        onChange: this.changeTriggerType
      }, /*#__PURE__*/React.createElement(_Radio, {
        value: STAGE_FLOW_AUTO,
        disabled: getPipeline.triggerType
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "pipeline.trigger.auto"
      })), /*#__PURE__*/React.createElement(_Radio, {
        value: STAGE_FLOW_MANUAL,
        disabled: getPipeline.triggerType
      }, /*#__PURE__*/React.createElement(FormattedMessage, {
        id: "pipeline.trigger.manual"
      })))))), showUserSelector && /*#__PURE__*/React.createElement(FormItem, Object.assign({
        className: "c7n-select_512"
      }, formItemLayout), getFieldDecorator('users', {
        rules: [{
          required: true,
          message: formatMessage({
            id: 'required'
          })
        }],
        initialValue: initUser
      })( /*#__PURE__*/React.createElement(_Select, {
        filter: true,
        filterOption: false,
        allowClear: true,
        mode: "multiple",
        label: formatMessage({
          id: 'pipeline.trigger.member'
        }),
        loading: getLoading.user,
        getPopupContainer: function getPopupContainer(triggerNode) {
          return triggerNode.parentNode;
        },
        onSearch: this.handleSearch,
        onChange: this.handleUserChange
      }, user))), /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-pipeline-main"
      }, /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-pipeline-scroll"
      }, this.renderPipelineDom)), getIsDisabled && /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-pipeline-error"
      }, /*#__PURE__*/React.createElement(_Icon, {
        type: "error",
        className: "c7ncd-pipeline-error-icon"
      }), /*#__PURE__*/React.createElement("span", {
        className: "c7ncd-pipeline-error-msg"
      }, "\u8BF7\u68C0\u67E5\u4EFB\u52A1\u7C7B\u578B\u662F\u5426\u6B63\u786E\uFF01")), !getCanSubmit && /*#__PURE__*/React.createElement("div", {
        className: "c7ncd-pipeline-error"
      }, /*#__PURE__*/React.createElement(_Icon, {
        type: "error",
        className: "c7ncd-pipeline-error-icon"
      }), /*#__PURE__*/React.createElement("span", {
        className: "c7ncd-pipeline-error-msg"
      }, formatMessage({
        id: 'pipeline.create.error-2'
      })))), /*#__PURE__*/React.createElement(InterceptMask, {
        visible: submitLoading || getDetailLoading
      })), showCreate && /*#__PURE__*/React.createElement(StageCreateModal, {
        store: PipelineCreateStore,
        prevId: prevId,
        visible: showCreate,
        onClose: this.closeCreateForm
      })));
    }
  }]);

  return PipelineEdit;
}(Component)) || _class) || _class) || _class) || _class) || _class);
export { PipelineEdit as default };