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

import omit from 'lodash/omit';
import isEmpty from 'lodash/isEmpty';
import pick from 'lodash/pick';
import forEach from 'lodash/forEach';
import moment from 'moment';
import setEnvRecentItem from "../../../utils/setEnvRecentItem";
import { itemTypeMappings, viewTypeMappings, RES_TYPES, ENV_KEYS } from "./mappings";
var IST_VIEW_TYPE = viewTypeMappings.IST_VIEW_TYPE,
    RES_VIEW_TYPE = viewTypeMappings.RES_VIEW_TYPE;
var ENV_ITEM = itemTypeMappings.ENV_ITEM,
    APP_ITEM = itemTypeMappings.APP_ITEM,
    IST_ITEM = itemTypeMappings.IST_ITEM;

function formatResource(_ref) {
  var value = _ref.value,
      expandsKeys = _ref.expandsKeys,
      formatMessage = _ref.formatMessage;
  if (isEmpty(value)) return [];
  var flatted = [];
  forEach(value, function (node, key) {
    var envInfo = pick(node, ENV_KEYS);
    var envId = envInfo.id;
    var envKey = String(envId);
    flatted.push(_objectSpread(_objectSpread({}, envInfo), {}, {
      key: envKey,
      itemType: ENV_ITEM,
      expand: expandsKeys.includes(envKey),
      parentId: '0',
      childrenData: omit(node, ENV_KEYS),
      isLeaf: false
    }));
  });
  return flatted;
}

function formatInstance(_ref2) {
  var value = _ref2.value,
      expandsKeys = _ref2.expandsKeys;
  if (isEmpty(value)) return [];
  var flatted = [];

  function flatData(data) {
    var prevKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
    var itemType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ENV_ITEM;
    forEach(data, function (node) {
      var children = node.apps;
      var peerNode = omit(node, ['apps']);
      var key = prevKey ? "".concat(prevKey, "**").concat(node.id) : String(node.id);
      flatted.push(_objectSpread(_objectSpread({}, peerNode), {}, {
        name: node.name || node.code,
        expand: expandsKeys.includes(key),
        parentId: prevKey || '0',
        itemType: itemType,
        key: key,
        childrenData: !isEmpty(children) ? children : null,
        isLeaf: isEmpty(children)
      }));
    });
  }

  flatData(value);
  return flatted;
}

function handleSelect(_ref3) {
  var record = _ref3.record,
      store = _ref3.store,
      projectId = _ref3.projectId,
      organizationId = _ref3.organizationId,
      projectName = _ref3.projectName;

  if (record) {
    var data = record.toData();
    store.setSelectedMenu(data);
    var item = getParentRecord(record);

    if (item && item.itemType === ENV_ITEM) {
      var recentEnv = _objectSpread(_objectSpread({}, item), {}, {
        projectId: projectId,
        organizationId: organizationId,
        projectName: projectName,
        clickTime: moment().format('YYYY-MM-DD HH:mm:ss')
      });

      setEnvRecentItem({
        value: recentEnv
      });
    }
  }
}

function getParentRecord(record) {
  if (record.parent) {
    return getParentRecord(record.parent);
  }

  return record.toData();
}

export default (function (_ref4) {
  var _formatMaps, _urlMaps;

  var store = _ref4.store,
      type = _ref4.type,
      projectId = _ref4.projectId,
      formatMessage = _ref4.formatMessage,
      organizationId = _ref4.organizationId,
      projectName = _ref4.projectName;
  var formatMaps = (_formatMaps = {}, _defineProperty(_formatMaps, IST_VIEW_TYPE, formatInstance), _defineProperty(_formatMaps, RES_VIEW_TYPE, formatResource), _formatMaps);
  var urlMaps = (_urlMaps = {}, _defineProperty(_urlMaps, IST_VIEW_TYPE, "/devops/v1/projects/".concat(projectId, "/envs/ins_tree_menu")), _defineProperty(_urlMaps, RES_VIEW_TYPE, "/devops/v1/projects/".concat(projectId, "/envs/resource_tree_menu")), _urlMaps);
  return {
    autoQuery: true,
    paging: false,
    dataKey: null,
    selection: 'single',
    parentField: 'parentId',
    expandField: 'expand',
    idField: 'key',
    fields: [{
      name: 'id',
      type: 'string'
    }, {
      name: 'name',
      type: 'string'
    }, {
      name: 'key',
      type: 'string'
    }, {
      name: 'parentId',
      type: 'string'
    }, {
      name: 'itemType',
      type: 'string'
    }],
    events: {
      query: function query() {
        // 请求数据前清空已加载子节点的key,确保展开的子节点获取最新数据
        store.setLoadedKeys([]);
        return true;
      },
      load: function load(_ref5) {
        var dataSet = _ref5.dataSet;

        if (!store.getSearchValue) {
          store.loadAllTreeData(dataSet.toData(), formatMessage);
        }
      },
      select: function select(_ref6) {
        var record = _ref6.record;
        handleSelect({
          record: record,
          store: store,
          projectId: projectId,
          organizationId: organizationId,
          projectName: projectName
        });
      },
      unSelect: function unSelect(_ref7) {
        var record = _ref7.record;
        // 禁用取消选中
        // eslint-disable-next-line no-param-reassign
        record.isSelected = true;
      }
    },
    transport: {
      read: {
        url: urlMaps[type],
        method: 'get',
        transformResponse: function transformResponse(response) {
          try {
            var data = JSON.parse(response);

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

            var expandsKeys = store.getExpandedKeys;
            store.getSearchValue && store.setSearchValue('');
            return formatMaps[type]({
              value: data,
              expandsKeys: expandsKeys,
              formatMessage: formatMessage
            });
          } catch (e) {
            return response;
          }
        }
      }
    }
  };
});