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

/* eslint-disable no-param-reassign */
import { useLocalStore } from 'mobx-react-lite';
import { axios, Choerodon } from '@choerodon/boot';
import map from 'lodash/map';
import { handlePromptError } from "../../../utils";
export default function useStore(_ref) {
  var DEFAULT_SIZE = _ref.DEFAULT_SIZE;
  return useLocalStore(function () {
    return {
      navBounds: {},
      setNavBounds: function setNavBounds(data) {
        this.navBounds = data;
      },

      get getNavBounds() {
        return this.navBounds;
      },

      selectedMenu: {},
      setSelectedMenu: function setSelectedMenu(data) {
        this.selectedMenu = data;
      },

      get getSelectedMenu() {
        return this.selectedMenu;
      },

      expandedKeys: [],
      setExpandedKeys: function setExpandedKeys(keys) {
        this.expandedKeys = keys;
      },

      get getExpandedKeys() {
        return this.expandedKeys.slice();
      },

      searchValue: '',
      setSearchValue: function setSearchValue(value) {
        this.searchValue = value;
      },

      get getSearchValue() {
        return this.searchValue;
      },

      pageList: {},

      get getPageList() {
        return this.pageList;
      },

      setPageList: function setPageList(data) {
        this.pageList = data;
      },
      treeDataHasMore: false,

      get getTreeDataHasMore() {
        return this.treeDataHasMore;
      },

      setTreeDataHasMore: function setTreeDataHasMore(flag) {
        this.treeDataHasMore = flag;
      },
      treeDataPage: 1,

      get getTreeDataPage() {
        return this.treeDataPage;
      },

      setTreeDataPage: function setTreeDataPage(data) {
        this.treeDataPage = data;
      },
      treeData: [],

      get getTreeData() {
        return this.treeData;
      },

      setTreeData: function setTreeData(data) {
        this.treeData = data;
      },
      loadedKeys: [],
      setLoadedKeys: function setLoadedKeys(keys) {
        this.loadedKeys = keys;
      },

      get getLoadedKeys() {
        return this.loadedKeys.slice();
      },

      changeRecordExecute: function changeRecordExecute(_ref2) {
        return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
          var projectId, gitlabProjectId, recordId, type, devopsPipelineRecordRelId, res;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  projectId = _ref2.projectId, gitlabProjectId = _ref2.gitlabProjectId, recordId = _ref2.recordId, type = _ref2.type, devopsPipelineRecordRelId = _ref2.devopsPipelineRecordRelId;
                  _context.prev = 1;
                  _context.next = 4;
                  return axios.get("/devops/v1/projects/".concat(projectId, "/cicd_pipelines_record/").concat(type, "?gitlab_project_id=").concat(gitlabProjectId, "&gitlab_pipeline_id=").concat(recordId).concat(devopsPipelineRecordRelId ? "&record_rel_id=".concat(devopsPipelineRecordRelId) : ''));

                case 4:
                  res = _context.sent;
                  return _context.abrupt("return", handlePromptError(res));

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

                case 12:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, null, [[1, 8]]);
        }))();
      },
      changePipelineActive: function changePipelineActive(_ref3) {
        return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
          var projectId, pipelineId, type, res;
          return regeneratorRuntime.wrap(function _callee2$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  projectId = _ref3.projectId, pipelineId = _ref3.pipelineId, type = _ref3.type;
                  _context2.prev = 1;
                  _context2.next = 4;
                  return axios.put("/devops/v1/projects/".concat(projectId, "/cicd_pipelines/").concat(pipelineId, "/").concat(type));

                case 4:
                  res = _context2.sent;
                  return _context2.abrupt("return", handlePromptError(res));

                case 8:
                  _context2.prev = 8;
                  _context2.t0 = _context2["catch"](1);
                  Choerodon.handleResponseError(_context2.t0);
                  return _context2.abrupt("return", false);

                case 12:
                case "end":
                  return _context2.stop();
              }
            }
          }, _callee2, null, [[1, 8]]);
        }))();
      },
      checkLinkToGitlab: function checkLinkToGitlab(projectId, appServiceId, type) {
        return axios.get("/devops/v1/projects/".concat(projectId, "/member-check/").concat(appServiceId, "?type=").concat(type || 'CI_PIPELINE_DETAIL'));
      },

      /**
       ** 人工审核阶段或任务
       * @param projectId
       * @param cdRecordId
       * @param stageRecordId
       * @param result
       */
      auditStage: function auditStage(_ref4) {
        var projectId = _ref4.projectId,
            cdRecordId = _ref4.cdRecordId,
            stageRecordId = _ref4.stageRecordId,
            result = _ref4.result;
        return axios.post("devops/v1/projects/".concat(projectId, "/pipeline_records/").concat(cdRecordId, "/stage_records/").concat(stageRecordId, "/audit?result=").concat(result));
      },

      /**
       ** 人工审核阶段或任务
       * @param projectId
       * @param cdRecordId
       * @param stageRecordId
       * @param jobRecordId
       * @param result
       */
      auditJob: function auditJob(_ref5) {
        var projectId = _ref5.projectId,
            cdRecordId = _ref5.cdRecordId,
            stageRecordId = _ref5.stageRecordId,
            jobRecordId = _ref5.jobRecordId,
            result = _ref5.result;
        return axios.post("/devops/v1/projects/".concat(projectId, "/pipeline_records/").concat(cdRecordId, "/stage_records/").concat(stageRecordId, "/job_records/").concat(jobRecordId, "/audit?result=").concat(result));
      },

      /**
       ** 人工审核预检，判断是否可以审核
       * @param projectId
       * @param cdRecordId
       * @param data
       */
      canCheck: function canCheck(projectId, cdRecordId, data) {
        return axios.post("/devops/v1/projects/".concat(projectId, "/pipeline_records/").concat(cdRecordId, "/check_audit_status"), JSON.stringify(data));
      },
      loadRecords: function loadRecords(projectId, pipelineId, page) {
        return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
          var res;
          return regeneratorRuntime.wrap(function _callee3$(_context3) {
            while (1) {
              switch (_context3.prev = _context3.next) {
                case 0:
                  _context3.prev = 0;
                  _context3.next = 3;
                  return axios.get("/devops/v1/projects/".concat(projectId, "/cicd_pipelines_record/").concat(pipelineId, "?page=").concat(page, "&size=5"));

                case 3:
                  res = _context3.sent;

                  if (!handlePromptError(res)) {
                    _context3.next = 6;
                    break;
                  }

                  return _context3.abrupt("return", res);

                case 6:
                  return _context3.abrupt("return", handlePromptError(res));

                case 9:
                  _context3.prev = 9;
                  _context3.t0 = _context3["catch"](0);
                  return _context3.abrupt("return", false);

                case 12:
                case "end":
                  return _context3.stop();
              }
            }
          }, _callee3, null, [[0, 9]]);
        }))();
      },
      loadRecordData: function loadRecordData(_ref6) {
        var _this = this;

        return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
          var projectId, key, treeDs, recordData, recordsChildren, moreRecordOption;
          return regeneratorRuntime.wrap(function _callee4$(_context4) {
            while (1) {
              switch (_context4.prev = _context4.next) {
                case 0:
                  projectId = _ref6.projectId, key = _ref6.key, treeDs = _ref6.treeDs;
                  _context4.prev = 1;

                  _this.setLoadedKeys([].concat(_toConsumableArray(_this.loadedKeys), [key]));

                  _context4.next = 5;
                  return _this.loadRecords(projectId, key, 1);

                case 5:
                  recordData = _context4.sent;

                  if (recordData) {
                    recordsChildren = map(recordData.list, function (item) {
                      item.key = "".concat(key, "-").concat(item.id || item.ciRecordId || item.cdRecordId);
                      item.parentId = key;
                      item.status = item.status || (item.ciStatus === 'success' && item.cdStatus ? item.cdStatus : item.ciStatus);
                      item.isLeaf = true;
                      var itemRecord = treeDs.create(item);
                      var selectedKey = _this.getSelectedMenu.key;

                      if (selectedKey && selectedKey === item.key) {
                        itemRecord.isSelected = true;

                        _this.setSelectedMenu(item);
                      }

                      return itemRecord;
                    });

                    if (recordData.hasNextPage) {
                      moreRecordOption = treeDs.create({
                        key: "".concat(key, "-more"),
                        parentId: key
                      });
                      recordsChildren.push(moreRecordOption);
                    }

                    treeDs.push.apply(treeDs, _toConsumableArray(recordsChildren));
                  }

                  _context4.next = 12;
                  break;

                case 9:
                  _context4.prev = 9;
                  _context4.t0 = _context4["catch"](1);
                  Choerodon.handleResponseError(_context4.t0);

                case 12:
                case "end":
                  return _context4.stop();
              }
            }
          }, _callee4, null, [[1, 9]]);
        }))();
      }
    };
  });
}