import "choerodon-ui/pro/lib/data-set/style";
import _DataSet from "choerodon-ui/pro/lib/data-set";

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

import React, { createContext, useCallback, useContext, useEffect, useMemo } from 'react';
import { inject } from 'mobx-react';
import { observer } from 'mobx-react-lite';
import { withRouter } from 'react-router-dom';
import { TabCode } from '@choerodon/master';
import { injectIntl } from 'react-intl';
import { useQueryString } from '@choerodon/components';
import queryString from 'query-string';
import { viewTypeMappings, itemTypeMappings } from "./mappings";
import TreeDataSet from "./TreeDataSet";
import useStore from "./useStore";
import ResourceServices from "../services";
var Store = /*#__PURE__*/createContext();
export function useResourceStore() {
  return useContext(Store);
}
export var StoreProvider = withRouter(injectIntl(inject('AppState')(observer(function (props) {
  var formatMessage = props.intl.formatMessage,
      _props$AppState$curre = props.AppState.currentMenuType,
      id = _props$AppState$curre.id,
      organizationId = _props$AppState$curre.organizationId,
      projectName = _props$AppState$curre.name,
      children = props.children,
      _props$location = props.location,
      state = _props$location.state,
      search = _props$location.search;
  var urlActiveKey = useQueryString().activeKey;
  var viewTypeMemo = useMemo(function () {
    return viewTypeMappings;
  }, []);
  var itemTypes = useMemo(function () {
    return itemTypeMappings;
  }, []);

  var _ref = state || queryString.parse(search) || {},
      activeKey = _ref.activeKey;

  if (!activeKey) {
    activeKey = urlActiveKey;
  }

  var newViewType = activeKey || '';
  var resourceStore = useStore(newViewType);
  var viewType = resourceStore.getViewType;
  var treeDs = useMemo(function () {
    return new _DataSet(TreeDataSet({
      store: resourceStore,
      type: viewType,
      projectId: id,
      formatMessage: formatMessage,
      organizationId: organizationId,
      projectName: projectName
    }));
  }, [viewType, id]);
  useEffect(function () {
    // NOTE: 1、部署或实例视图的部署后跳转至实例视图实例层。2、资源视图的部署后跳转至资源视图实例层。
    // 3、消息通知通过url传参跳转至资源视图各资源列表层。
    handleSelect();
  }, []);
  var handleSelect = useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    var IST_VIEW_TYPE, RES_VIEW_TYPE, _ref3, envId, appServiceId, instanceId, _ref3$itemType, itemType, newEnvId, res, parentId;

    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            IST_VIEW_TYPE = viewTypeMemo.IST_VIEW_TYPE, RES_VIEW_TYPE = viewTypeMemo.RES_VIEW_TYPE;
            _ref3 = state || queryString.parse(search) || {}, envId = _ref3.envId, appServiceId = _ref3.appServiceId, instanceId = _ref3.instanceId, _ref3$itemType = _ref3.itemType, itemType = _ref3$itemType === void 0 ? 'instances' : _ref3$itemType;

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

            newEnvId = envId;

            if (state) {
              _context.next = 9;
              break;
            }

            _context.next = 7;
            return ResourceServices.getEncrypt([envId]);

          case 7:
            res = _context.sent;

            if (res && res[envId]) {
              newEnvId = res[envId];
            }

          case 9:
            if (newViewType === IST_VIEW_TYPE) {
              if (instanceId) {
                parentId = "".concat(newEnvId, "**").concat(appServiceId);
                resourceStore.setSelectedMenu({
                  id: instanceId,
                  parentId: parentId,
                  key: "".concat(parentId, "**").concat(instanceId),
                  itemType: itemTypes.IST_ITEM
                });
                resourceStore.setExpandedKeys(["".concat(newEnvId), "".concat(newEnvId, "**").concat(appServiceId)]);
              } else {
                resourceStore.setSelectedMenu({
                  id: newEnvId,
                  parentId: '0',
                  key: String(newEnvId),
                  itemType: itemTypes.ENV_ITEM
                });
                resourceStore.setExpandedKeys(["".concat(newEnvId)]);
              }
            } else {
              resourceStore.setSelectedMenu({
                id: 0,
                name: formatMessage({
                  id: itemType
                }),
                key: "".concat(newEnvId, "**").concat(itemType),
                isGroup: true,
                itemType: "group_".concat(itemType),
                parentId: String(newEnvId)
              });
              resourceStore.setExpandedKeys(["".concat(newEnvId)]);
            }

          case 10:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })), [state, search]);

  var value = _objectSpread(_objectSpread({}, props), {}, {
    prefixCls: 'c7ncd-deployment',
    intlPrefix: 'c7ncd.deployment',
    permissions: ['devops-service.devops-environment.listEnvTree', 'devops-service.devops-environment.listResourceEnvTree'],
    viewTypeMappings: viewTypeMemo,
    itemTypes: itemTypes,
    resourceStore: resourceStore,
    treeDs: treeDs
  });

  return /*#__PURE__*/React.createElement(Store.Provider, {
    value: value
  }, children);
}))));