var _excluded = ["id"];

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

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

import { runInAction } from 'mobx';
import forEach from 'lodash/forEach';
import remove from 'lodash/remove';
import moment from 'moment';
import setEnvRecentItem from "../../../utils/setEnvRecentItem";
var GROUP_ITEM = 'group';
var ENV_ITEM = 'detail';
/**
 * 通过DataSet创建Record
 */

function formatTreeData(_ref) {
  var data = _ref.data,
      expandedKeys = _ref.expandedKeys,
      formatMessage = _ref.formatMessage,
      intlPrefix = _ref.intlPrefix;
  var result = [];
  forEach(data, function (_ref2) {
    var id = _ref2.devopsEnvGroupId,
        devopsEnvGroupName = _ref2.devopsEnvGroupName,
        envs = _ref2.devopsEnvironmentRepDTOs;
    var groupKey = "group-".concat(id);
    var name = devopsEnvGroupName || '';

    if (!name && !id) {
      name = formatMessage({
        id: "".concat(intlPrefix, ".group.default")
      });
    }

    result.push({
      id: id,
      name: name,
      key: groupKey,
      itemType: GROUP_ITEM,
      parentId: '',
      expand: expandedKeys.includes(groupKey)
    });
    forEach(envs, function (_ref3) {
      var envId = _ref3.id,
          rest = _objectWithoutProperties(_ref3, _excluded);

      var key = "".concat(groupKey, "-").concat(envId);
      result.push(_objectSpread(_objectSpread({}, rest), {}, {
        id: envId,
        key: key,
        parentId: groupKey,
        itemType: ENV_ITEM,
        expand: false
      }));
    });
  });
  return result;
}

function handleSelect(_ref4) {
  var record = _ref4.record,
      store = _ref4.store,
      previous = _ref4.previous,
      dataSet = _ref4.dataSet,
      projectId = _ref4.projectId,
      organizationId = _ref4.organizationId,
      projectName = _ref4.projectName;

  if (record) {
    var itemType = record.get('itemType');
    var synchro = record.get('synchro');
    var failed = record.get('failed');

    if (itemType === GROUP_ITEM) {
      var data = record.toData();
      store.setSelectedMenu(data);
      dataSet.query();
    } else if (synchro && !failed) {
      var _data = record.toData();

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

      store.setSelectedMenu(_data);
      setEnvRecentItem({
        value: recentEnv
      });
    } else {
      runInAction(function () {
        // 处理中和创建失败的环境不允许选中
        record.isSelected = false;
        previous.isSelected = true;
      });
    }
  }
}

export default (function (_ref5) {
  var projectId = _ref5.projectId,
      store = _ref5.store,
      formatMessage = _ref5.formatMessage,
      intlPrefix = _ref5.intlPrefix,
      organizationId = _ref5.organizationId,
      projectName = _ref5.projectName;
  return {
    autoQuery: true,
    paging: false,
    dataKey: null,
    selection: 'single',
    parentField: 'parentId',
    expandField: 'expand',
    idField: 'key',
    events: {
      select: function select(_ref6) {
        var dataSet = _ref6.dataSet,
            record = _ref6.record,
            previous = _ref6.previous;
        handleSelect({
          record: record,
          store: store,
          previous: previous,
          dataSet: dataSet,
          projectId: projectId,
          organizationId: organizationId,
          projectName: projectName
        });
      },
      unSelect: function unSelect(_ref7) {
        var record = _ref7.record;
        record.isSelected = true;
      }
    },
    transport: {
      read: {
        url: "/devops/v1/projects/".concat(projectId, "/envs/env_tree_menu"),
        method: 'get',
        transformResponse: function transformResponse(response) {
          try {
            var expandedKeys = store.getExpandedKeys;
            var groups = JSON.parse(response);

            if (groups && groups.failed) {
              return groups;
            } else {
              if (groups[0] && groups[0].devopsEnvGroupId) {
                var defaultGroup = remove(groups, function (_ref8) {
                  var devopsEnvGroupId = _ref8.devopsEnvGroupId;
                  return !devopsEnvGroupId;
                });
                groups.unshift.apply(groups, _toConsumableArray(defaultGroup));
              }

              return formatTreeData({
                data: groups,
                expandedKeys: expandedKeys,
                intlPrefix: intlPrefix,
                formatMessage: formatMessage
              });
            }
          } catch (e) {
            return response;
          }
        }
      }
    }
  };
});