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

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

/* eslint-disable import/no-anonymous-default-export */
import forEach from 'lodash/forEach';
import isEmpty from 'lodash/isEmpty';
import JSONBigint from 'json-bigint';

function formatData(_ref) {
  var data = _ref.data,
      expandsKeys = _ref.expandsKeys;
  var newData = [];

  function flatData(value, gitlabProjectId, parentId) {
    forEach(value, function (item) {
      var key = "".concat(parentId ? "".concat(parentId, "-") : '').concat(item.id || item.devopsPipelineRecordRelId);
      var newGitlabProjectId = item.gitlabProjectId || gitlabProjectId;

      var newItem = _objectSpread(_objectSpread({}, item), {}, {
        key: key,
        parentId: parentId ? parentId.toString() : null,
        status: item.latestExecuteStatus || item.status || (item.ciStatus === 'success' && item.cdStatus ? item.cdStatus : item.ciStatus),
        expand: (expandsKeys === null || expandsKeys === void 0 ? void 0 : expandsKeys.indexOf(key)) > -1,
        gitlabProjectId: newGitlabProjectId
      });

      newData.push(newItem);
    });
  }

  flatData(data);
  return newData;
}

export default (function (_ref2) {
  var projectId = _ref2.projectId,
      mainStore = _ref2.mainStore,
      editBlockStore = _ref2.editBlockStore,
      handleSelect = _ref2.handleSelect,
      DEFAULT_SIZE = _ref2.DEFAULT_SIZE;
  return {
    autoCreate: false,
    autoQuery: false,
    selection: 'single',
    primaryKey: 'key',
    idField: 'key',
    parentField: 'parentId',
    expandField: 'expand',
    pageSize: DEFAULT_SIZE,
    transport: {
      read: function read(_ref3) {
        var dataSet = _ref3.dataSet;
        return {
          url: "devops/v1/projects/".concat(projectId, "/cicd_pipelines/query?page=").concat(mainStore.getTreeDataPage || 1, "&size=").concat(DEFAULT_SIZE).concat(mainStore.getSearchValue ? "&searchParam=".concat(mainStore.getSearchValue) : ''),
          method: 'post',
          data: null,
          transformResponse: function transformResponse(response) {
            try {
              var data = JSONBigint.parse(response);

              if (data && data.failed) {
                return data;
              }

              var getExpandedKeys = mainStore.getExpandedKeys,
                  setExpandedKeys = mainStore.setExpandedKeys;
              var expandsKeys = getExpandedKeys;

              var newData = _toConsumableArray(data.content);

              if (isEmpty(getExpandedKeys) && newData.length) {
                var newKeys = newData[0].id.toString();
                expandsKeys = [newKeys];
                setExpandedKeys([newKeys]);
              }

              mainStore.setTreeDataHasMore(data.totalElements > 0 && data.number + 1 < data.totalPages);
              return formatData({
                data: newData,
                expandsKeys: expandsKeys
              });
            } catch (e) {
              return response;
            }
          }
        };
      },
      destroy: function destroy(_ref4) {
        var _ref4$data = _slicedToArray(_ref4.data, 1),
            data = _ref4$data[0];

        return {
          url: "/devops/v1/projects/".concat(projectId, "/cicd_pipelines/").concat(data.id),
          method: 'delete'
        };
      }
    },
    events: {
      select: function select(_ref5) {
        var record = _ref5.record,
            previous = _ref5.previous;
        handleSelect(record, mainStore);
      },
      unSelect: function unSelect(_ref6) {
        var record = _ref6.record;
        // 禁用取消选中
        // eslint-disable-next-line no-param-reassign
        record.isSelected = true;
      },
      load: function load(_ref7) {
        var dataSet = _ref7.dataSet;
        var records = mainStore.getTreeData;

        if (mainStore.getTreeDataPage > 1) {
          dataSet.unshift.apply(dataSet, _toConsumableArray(records));
        }

        mainStore.setTreeData(dataSet.records);

        function selectFirstRecord() {
          var newRecord = dataSet.records[0];

          if (newRecord) {
            newRecord.isSelected = true;
            handleSelect(newRecord, mainStore);
          }
        }

        mainStore.setPageList({});
        var key = mainStore.getSelectedMenu.key;

        if (key) {
          var selectedRecord = dataSet.find(function (treeRecord) {
            return key === treeRecord.get('key');
          });

          if (selectedRecord) {
            selectedRecord.isSelected = true;
            handleSelect(selectedRecord, mainStore);
          } // const pattern = new URLSearchParams(window.location.hash);
          // const newPipelineId = pattern.get('pipelineId');
          // const newPipelineIdRecordId = pattern.get('pipelineIdRecordId');
          // if (selectedRecord) {
          //   selectedRecord.isSelected = true;
          //   handleSelect(selectedRecord, mainStore);
          // } else if (!newPipelineId || !newPipelineIdRecordId) {
          //   selectFirstRecord();
          // }

        } else {
          selectFirstRecord();
        }
      }
    }
  };
});