import "choerodon-ui/lib/button/style";
import _Button from "choerodon-ui/lib/button";
import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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

import React from 'react';
import { observer } from 'mobx-react-lite';
import { Droppable, Draggable, DragDropContext } from 'react-beautiful-dnd';
import { usePipelineStageEditStore } from "../../stores";
import AddTask from "../../../AddTask";
import AddCDTask from "../../../AddCDTask";
import AddStage from "../AddStage";
import { usePipelineCreateStore } from "../../../../stores";
import ViewVariable from "../../../../../view-variables";
import EditItem from "./EditItem";
import "./index.less";
var modalStyle = {
  width: 380
};
export default observer(function (props) {
  var _stagesSource$columnI;

  var jobList = props.jobList,
      sequence = props.sequence,
      name = props.name,
      columnIndex = props.columnIndex,
      appServiceId = props.appServiceId,
      appServiceName = props.appServiceName,
      image = props.image,
      type = props.type,
      parallel = props.parallel,
      appServiceCode = props.appServiceCode,
      appServiceType = props.appServiceType,
      nextStageType = props.nextStageType,
      stagesSource = props.stagesSource,
      innerRef = props.innerRef,
      dragProvided = props.dragProvided,
      snapshotinner = props.snapshotinner;
  var witchColumnJobIndex = stagesSource && ((_stagesSource$columnI = stagesSource[columnIndex]) === null || _stagesSource$columnI === void 0 ? void 0 : _stagesSource$columnI.jobList.length);

  var _usePipelineStageEdit = usePipelineStageEditStore(),
      addStepDs = _usePipelineStageEdit.addStepDs,
      editBlockStore = _usePipelineStageEdit.editBlockStore,
      stepStore = _usePipelineStageEdit.stepStore,
      projectId = _usePipelineStageEdit.projectId;

  var _ref = editBlockStore || stepStore,
      addNewStep = _ref.addNewStep,
      removeStep = _ref.removeStep,
      eidtStep = _ref.eidtStep,
      newJob = _ref.newJob,
      getStepData = _ref.getStepData,
      editJobLists = _ref.editJobLists;

  var stageLength = getStepData.length;
  var PipelineCreateFormDataSet;
  var AppServiceOptionsDs;

  try {
    PipelineCreateFormDataSet = usePipelineCreateStore().PipelineCreateFormDataSet;
    AppServiceOptionsDs = usePipelineCreateStore().AppServiceOptionsDs;
  } catch (e) {
    window.console.log(e);
  }

  function createNewStage(_x) {
    return _createNewStage.apply(this, arguments);
  } // eslint-disable-next-line consistent-return


  function _createNewStage() {
    _createNewStage = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(firstIf) {
      var res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return addStepDs.validate();

            case 2:
              res = _context.sent;

              if (!res) {
                _context.next = 7;
                break;
              }

              // const a = addStepDs.toData()[0];
              addNewStep(firstIf ? -1 : columnIndex, addStepDs.toData()[0]);
              addStepDs.reset();
              return _context.abrupt("return", true);

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

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

  function editStage() {
    return _editStage.apply(this, arguments);
  }

  function _editStage() {
    _editStage = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (!(addStepDs.current && addStepDs.current.validate())) {
                _context2.next = 4;
                break;
              }

              eidtStep(sequence, addStepDs.current.get('step'), addStepDs.current.get('type'), true);
              _context2.next = 5;
              break;

            case 4:
              return _context2.abrupt("return", false);

            case 5:
              addStepDs.reset();

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

  function swap(arr, from, to) {
    arr.splice(to, 0, arr.splice(from, 1)[0]);
    return arr;
  }

  function onTaskDragEnd(data) {
    var source = data.source,
        destination = data.destination;

    if (!destination) {
      return;
    }

    var arr = _toConsumableArray(swap(jobList, source.index, destination.index));

    editJobLists(sequence, type, arr);
  }

  var getListStyle = function getListStyle(isDraggingOver) {
    return {
      border: isDraggingOver ? '2px dotted #5266d4' : 'none',
      borderRadius: isDraggingOver ? '3px' : '0',
      padding: '2px',
      background: isDraggingOver ? 'rgba(82, 102, 212, 0.1)' : 'none'
    };
  };

  var renderStepTasks = function renderStepTasks() {
    return jobList && jobList.length > 0 ? /*#__PURE__*/React.createElement(DragDropContext, {
      onDragEnd: onTaskDragEnd
    }, /*#__PURE__*/React.createElement(Droppable, {
      droppableId: "dropJobs-".concat(sequence)
    }, function (provided, snapshot) {
      return /*#__PURE__*/React.createElement("div", Object.assign({
        ref: provided.innerRef
      }, provided.droppableProps, {
        className: "c7n-piplineManage-edit-column-lists",
        style: getListStyle(snapshot.isDraggingOver)
      }), jobList.slice().map(function (item, index) {
        return /*#__PURE__*/React.createElement(Draggable, {
          key: "dropJobs-".concat(item.name),
          draggableId: "dropJobs-".concat(item.name),
          index: index
        }, function (dragProvidedByColomn, snapshotinnerByJob) {
          return /*#__PURE__*/React.createElement(EditItem, {
            snapshotinner: snapshotinnerByJob,
            innerRef: dragProvidedByColomn.innerRef,
            dragProvided: dragProvidedByColomn,
            index: index,
            witchColumnJobIndex: witchColumnJobIndex,
            columnIndex: columnIndex + 1,
            sequence: sequence,
            appServiceId: appServiceId,
            appServiceName: appServiceName,
            appServiceCode: appServiceCode,
            AppServiceOptionsDs: AppServiceOptionsDs,
            PipelineCreateFormDataSet: PipelineCreateFormDataSet,
            jobDetail: item,
            image: image,
            openVariableModal: openVariableModal,
            stageType: type || 'CI'
          });
        });
      }), provided.placeholder);
    })) : null;
  };

  var openAddStageModal = function openAddStageModal(_ref2) {
    var optType = _ref2.optType,
        curType = _ref2.curType,
        _ref2$firstIf = _ref2.firstIf,
        firstIf = _ref2$firstIf === void 0 ? false : _ref2$firstIf;
    var title = optType === 'create' ? '添加阶段' : '修改阶段信息';
    var okText = optType === 'create' ? '添加' : '修改';

    if (optType === 'edit') {
      addStepDs.current.set('step', name);
      addStepDs.current.set('type', curType || 'CI');
    }

    var optsFun = optType === 'create' ? function () {
      return createNewStage(firstIf);
    } : editStage;

    _Modal.open({
      key: _Modal.key(),
      title: title,
      drawer: true,
      style: {
        width: 380
      },
      okText: okText,
      children: /*#__PURE__*/React.createElement(AddStage, {
        stageName: name,
        projectId: projectId,
        curType: curType,
        optType: optType,
        addStepDs: addStepDs,
        appServiceType: optType === 'create' ? appServiceType : null,
        firstIf: firstIf,
        appServiceId: appServiceId,
        nextStageType: nextStageType
      }),
      onOk: optsFun,
      onCancel: function onCancel() {
        return addStepDs.reset();
      }
    });
  };

  function deleteStep() {
    _Modal.open({
      title: "\u5220\u9664".concat(name, "\u9636\u6BB5"),
      children: '确认删除此阶段吗？',
      key: _Modal.key(),
      onOk: function onOk() {
        return removeStep(sequence);
      }
    });
  }

  function hanleStepCreateOk(data) {
    newJob(sequence, data);
  }

  function openVariableModal() {
    _Modal.open({
      key: _Modal.key(),
      style: modalStyle,
      drawer: true,
      title: '查看变量配置',
      children: /*#__PURE__*/React.createElement(ViewVariable, {
        appServiceId: appServiceId
      }),
      okCancel: false,
      okText: '关闭'
    });
  }

  var renderNewTaskModalChildren = function renderNewTaskModalChildren() {
    var modalChildren;

    if (type === 'CI') {
      modalChildren = /*#__PURE__*/React.createElement(AddTask, {
        PipelineCreateFormDataSet: PipelineCreateFormDataSet,
        AppServiceOptionsDs: AppServiceOptionsDs,
        handleOk: hanleStepCreateOk,
        appServiceId: appServiceName,
        appServiceName: appServiceName,
        stageName: name,
        image: image,
        columnIndex: columnIndex + 1,
        witchColumnJobIndex: witchColumnJobIndex + 1
      });
    } else {
      modalChildren = /*#__PURE__*/React.createElement(AddCDTask, {
        random: Math.random(),
        stageName: name,
        appServiceId: appServiceName,
        appServiceName: appServiceName,
        appServiceCode: appServiceCode,
        pipelineStageMainSource: getStepData,
        PipelineCreateFormDataSet: PipelineCreateFormDataSet,
        handleOk: hanleStepCreateOk,
        columnIndex: columnIndex + 1,
        witchColumnJobIndex: witchColumnJobIndex + 1
      });
    }

    return modalChildren;
  };

  function openNewTaskModal() {
    _Modal.open({
      key: _Modal.key(),
      title: /*#__PURE__*/React.createElement("div", {
        style: {
          display: 'flex',
          alignItems: 'center'
        }
      }, /*#__PURE__*/React.createElement("span", {
        className: "c7n-piplineManage-edit-title-text"
      }, "\u6DFB\u52A0\u4EFB\u52A1"), type === 'CI' && /*#__PURE__*/React.createElement("div", {
        className: "c7n-piplineManage-edit-title-text-btn",
        onClick: function onClick() {
          return openVariableModal();
        },
        role: "none"
      }, /*#__PURE__*/React.createElement(_Icon, {
        type: "find_in_page-o",
        className: "c7n-piplineManage-edit-title-btn"
      }), /*#__PURE__*/React.createElement("span", null, "\u67E5\u770B\u6D41\u6C34\u7EBF\u53D8\u91CF"))),
      children: renderNewTaskModalChildren(),
      style: {
        width: '740px'
      },
      drawer: true,
      okText: '添加'
    });
  }

  var realType = type === null || type === void 0 ? void 0 : type.toUpperCase();

  var getItemStyle = function getItemStyle(isDragging, draggableStyle) {
    return _objectSpread(_objectSpread({
      // some basic styles to make the items look a bit nicer
      userSelect: 'none'
    }, draggableStyle), {}, {
      cursor: 'unset',
      background: type === 'CI' ? 'rgba(245, 246, 250, 1)' : 'rgba(245,248,250,1)'
    });
  };

  return [columnIndex === 0 && /*#__PURE__*/React.createElement(_Button, {
    className: "extra-addbutton",
    funcType: "raised",
    icon: "add",
    shape: "circle",
    disabled: !appServiceId,
    size: "small",
    onClick: function onClick() {
      return openAddStageModal({
        optType: 'create',
        curType: type,
        firstIf: true
      });
    }
  }), /*#__PURE__*/React.createElement("div", Object.assign({
    className: "c7n-piplineManage-edit-column"
  }, dragProvided.draggableProps, {
    style: getItemStyle(snapshotinner.isDragging, dragProvided.draggableProps.style)
  }), /*#__PURE__*/React.createElement("div", Object.assign({
    ref: innerRef
  }, dragProvided.dragHandleProps, {
    style: {
      cursor: 'all-scroll'
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: "c7n-piplineManage-edit-column-header"
  }, /*#__PURE__*/React.createElement("span", null, name), /*#__PURE__*/React.createElement("span", {
    className: "c7n-piplineManage-stage-type c7n-piplineManage-stage-type-".concat(realType)
  }, realType), /*#__PURE__*/React.createElement("div", {
    className: "c7n-piplineManage-edit-column-header-btnGroup"
  }, /*#__PURE__*/React.createElement(_Button, {
    funcType: "raised",
    shape: "circle",
    size: "small",
    icon: "mode_edit",
    disabled: !appServiceId,
    onClick: function onClick() {
      return openAddStageModal({
        optType: 'edit',
        curType: type
      });
    },
    className: "c7n-piplineManage-edit-column-header-btnGroup-btn"
  }), stageLength > 1 && /*#__PURE__*/React.createElement(_Button, {
    funcType: "raised",
    shape: "circle",
    size: "small",
    onClick: deleteStep,
    icon: "delete_forever",
    disabled: !appServiceId,
    className: "c7n-piplineManage-edit-column-header-btnGroup-btn c7n-piplineManage-edit-column-header-btnGroup-btn-delete"
  }))), /*#__PURE__*/React.createElement("div", {
    className: "c7n-piplineManage-edit-column-stageType"
  }, /*#__PURE__*/React.createElement("span", null, "\u4EFB\u52A1\u5217\u8868"), /*#__PURE__*/React.createElement("span", {
    className: "c7n-piplineManage-stage-type-task c7n-piplineManage-stage-type-task-".concat(parallel || realType === 'CI' ? 'parallel' : 'serial')
  }, parallel || realType === 'CI' ? '任务并行' : '任务串行'))), renderStepTasks(), /*#__PURE__*/React.createElement(_Button, {
    funcType: "flat",
    icon: "add",
    type: "primary",
    onClick: openNewTaskModal,
    style: {
      marginTop: '10px'
    },
    disabled: PipelineCreateFormDataSet && !appServiceId
  }, "\u6DFB\u52A0\u4EFB\u52A1"), /*#__PURE__*/React.createElement(_Button, {
    funcType: "raised",
    icon: "add",
    shape: "circle",
    size: "small",
    disabled: !appServiceId,
    className: "c7n-piplineManage-edit-column-addBtn",
    onClick: function onClick() {
      return openAddStageModal({
        optType: 'create',
        curType: type
      });
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: "c7n-piplineManage-edit-column-arrow"
  }, /*#__PURE__*/React.createElement("span", null), /*#__PURE__*/React.createElement("span", null)))];
});