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 { useLocalStore } from 'mobx-react-lite';
import { axios, Choerodon } from '@choerodon/boot';
import { map, isEmpty, forEach, omit, pick, concat } from 'lodash';
import { itemTypeMappings, viewTypeMappings, RES_TYPES, ENV_KEYS } from "./mappings";
var IST_VIEW_TYPE = viewTypeMappings.IST_VIEW_TYPE;
var APP_ITEM = itemTypeMappings.APP_ITEM,
    IST_ITEM = itemTypeMappings.IST_ITEM;
export default function useStore(viewType) {
  return useLocalStore(function () {
    return {
      showHeader: true,
      setShowHeader: function setShowHeader(flag) {
        this.showHeader = flag;
      },

      get getShowHeader() {
        return this.showHeader;
      },

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

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

      changeViewType: function changeViewType(data) {
        this.viewType = data;
      },

      get getViewType() {
        return this.viewType;
      },

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

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

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

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

      upTarget: {},

      /**
       * 设置需要更新的模块信息
       * @param data { type, id }
       */
      setUpTarget: function setUpTarget(data) {
        this.upTarget = data;
      },

      get getUpTarget() {
        return this.upTarget;
      },

      /**
       * 树结构已展开的节点的key
       */
      loadedKeys: [],
      setLoadedKeys: function setLoadedKeys(keys) {
        this.loadedKeys = keys;
      },

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

      childrenDataMap: new Map(),

      get getChildrenDataMap() {
        return this.childrenDataMap;
      },

      parentDataMap: new Map(),

      get getParentDataMap() {
        return this.parentDataMap;
      },

      allTreeData: [],

      get getAllTreeData() {
        return this.allTreeData;
      },

      setAllTreeData: function setAllTreeData(data) {
        this.allTreeData = data;
      },
      checkExist: function checkExist(_ref) {
        return _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
          var projectId, envId, type, id, res;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  projectId = _ref.projectId, envId = _ref.envId, type = _ref.type, id = _ref.id;
                  _context.prev = 1;
                  _context.next = 4;
                  return axios.get("/devops/v1/projects/".concat(projectId, "/envs/").concat(envId, "/check?type=").concat(type, "&object_id=").concat(id));

                case 4:
                  res = _context.sent;

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

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

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

                case 10:
                  _context.prev = 10;
                  _context.t0 = _context["catch"](1);
                  return _context.abrupt("return", true);

                case 13:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, null, [[1, 10]]);
        }))();
      },
      handleSelectedMenuData: function handleSelectedMenuData(_ref2) {
        var treeDs = _ref2.treeDs,
            item = _ref2.item;
        var itemRecord = treeDs.create(item);
        var selectedKey = this.selectedMenu.key;

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

        return itemRecord;
      },
      loadMoreRecordData: function loadMoreRecordData(_ref3) {
        var _this = this;

        var key = _ref3.key,
            treeDs = _ref3.treeDs,
            children = _ref3.children;

        try {
          this.setLoadedKeys([].concat(_toConsumableArray(this.loadedKeys), [key]));

          if (children) {
            return;
          }

          var recordData = this.childrenDataMap.get(key);

          if (recordData) {
            var records = map(recordData, function (item) {
              var itemRecord = _this.handleSelectedMenuData({
                treeDs: treeDs,
                item: item
              });

              return itemRecord;
            });
            treeDs.push.apply(treeDs, _toConsumableArray(records));
          }
        } catch (e) {
          Choerodon.handleResponseError(e);
        }
      },
      loadAllTreeData: function loadAllTreeData(allData, formatMessage) {
        var _this2 = this;

        var flatted = [];
        var expandsKeys = this.expandedKeys;
        this.childrenDataMap.clear();
        this.parentDataMap.clear();

        var flatInstanceData = function flatInstanceData(data) {
          var prevKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
          var itemType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : APP_ITEM;
          var parentNode = arguments.length > 3 ? arguments[3] : undefined;
          var items = [];
          forEach(data, function (node) {
            var children = node.instances;
            var peerNode = omit(node, ['instances']);
            var key = prevKey ? "".concat(prevKey, "**").concat(node.id) : String(node.id);

            var item = _objectSpread(_objectSpread({}, peerNode), {}, {
              name: node.name || node.code,
              expand: expandsKeys.includes(key),
              parentId: prevKey || '0',
              itemType: itemType,
              key: key,
              isLeaf: isEmpty(children)
            });

            flatted.push(item);
            items.push(item);

            _this2.parentDataMap.set(key, parentNode);

            if (!isEmpty(children)) {
              flatInstanceData(children, key, IST_ITEM, item);
            }
          });

          _this2.childrenDataMap.set(prevKey, items);
        };

        var flatResourceData = function flatResourceData(data) {
          forEach(data, function (node) {
            var envInfo = pick(node, ENV_KEYS);
            var envId = envInfo.id;
            var envKey = String(envId);
            var childrenData = node.childrenData;
            var groups = [];
            forEach(RES_TYPES, function (type, index) {
              var child = childrenData[type];
              var groupKey = "".concat(envId, "**").concat(type);
              var group = {
                id: index,
                name: formatMessage({
                  id: type
                }),
                key: groupKey,
                isGroup: true,
                itemType: "group_".concat(type),
                parentId: envKey,
                expand: expandsKeys.includes(groupKey),
                isLeaf: isEmpty(child)
              };
              var items = [];
              forEach(child, function (item) {
                var newItemKey = "".concat(envId, "**").concat(item.id, "**").concat(type);

                var newItem = _objectSpread(_objectSpread({}, item), {}, {
                  name: type === 'instances' ? item.code : item.name,
                  key: newItemKey,
                  itemType: type,
                  parentId: groupKey,
                  expand: false,
                  isLeaf: true
                });

                items.push(newItem);

                _this2.parentDataMap.set(newItemKey, group);
              });
              groups.push(group);
              flatted.push.apply(flatted, [group].concat(items));

              _this2.parentDataMap.set(groupKey, node);

              if (!isEmpty(child)) {
                _this2.childrenDataMap.set(groupKey, items);
              }
            });

            _this2.childrenDataMap.set(envKey, groups);
          });
        };

        if (this.viewType === IST_VIEW_TYPE) {
          forEach(allData, function (node) {
            var children = node.childrenData;
            var key = String(node.id);

            if (!isEmpty(children)) {
              flatInstanceData(children, key, APP_ITEM, node);
            }
          });
        } else {
          flatResourceData(allData);
        }

        var realData = concat(allData, flatted);
        this.setAllTreeData(realData);
        this.setLoadedKeys([]);
      }
    };
  });
}