"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.countNodes = void 0;
exports.resetDataWithDisabled = resetDataWithDisabled;
exports.resetDataWithLimit = resetDataWithLimit;
exports.selectAllExcludingDisabled = void 0;
exports.transDataParam = transDataParam;
var _getParentNodes = require("../utils/getParentNodes");
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
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 _objectDestructuringEmpty(obj) { if (obj == null) throw new TypeError("Cannot destructure " + obj); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* eslint-disable */ // import * as React from 'react';
/**
 * transDataParam 根据指定选项字段名重组数据
 *
 * @params {array} array 树数据集合
 * @params {object} optionName 选项字段值(tree-select的标题使用的是label字段）
 *
 * */
function transDataParam(array) {
  var optionName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    key: 'key',
    value: 'key',
    title: 'title',
    label: 'label',
    children: 'children',
    disabled: 'disabled',
    selectable: 'selectable'
  };
  var extra = arguments.length > 2 ? arguments[2] : undefined;
  var trans = function trans(list) {
    if (!list) return [];
    return list.map(function (item) {
      if (item.hasOwnProperty(optionName.disabled || 'disabled')) {
        item[optionName.disabled || 'disabled'] = item[optionName.disabled || 'disabled'];
        item.disabled = item[optionName.disabled || 'disabled']; // TreeData只认这个节点
      }
      if (item.hasOwnProperty(optionName.selectable || 'selectable')) {
        item[optionName.selectable || 'selectable'] = item[optionName.selectable || 'selectable'];
        item.selectable = item[optionName.selectable || 'selectable']; // TreeData只认这个节点
      }
      if (item.hasOwnProperty(optionName.children || 'children')) {
        // item.children = item[optionName.children || 'children'] ? trans(item[optionName.children || 'children']) : []
        item[optionName.children || 'children'] = item[optionName.children || 'children'] ? trans(item[optionName.children || 'children']) : [];
      }
      var newNodeInfo = (0, _getParentNodes.getParentNodes)(array, item[optionName.value || optionName.key || 'key'], {
        childrenParam: (optionName === null || optionName === void 0 ? void 0 : optionName.children) || 'children',
        keyParam: optionName.value || optionName.key || 'key'
      });
      var pathNodes = (0, _getParentNodes.getNodePaths)(array, item[optionName.value || optionName.key || 'key'], {
        childrenParam: (optionName === null || optionName === void 0 ? void 0 : optionName.children) || 'children',
        keyParam: optionName.value || optionName.key || 'key'
      }, {});

      /// disabledFields:指定禁用节点
      var resetByDisabledFields = function resetByDisabledFields(initItem) {
        var oldItem = _objectSpread({}, initItem);
        var nodeItem = Object.assign({}, (_objectDestructuringEmpty(oldItem), oldItem));
        Object.keys(nodeItem).forEach(function (itemKeyName) {
          var isMatch = extra.disabledFields.find(function (fItem) {
            return fItem.key === itemKeyName;
          });
          if (isMatch) {
            var _isMatch$value$split;
            // 确认是否匹配数据，进行设置 disabled
            if ((_isMatch$value$split = isMatch.value.split(',')) !== null && _isMatch$value$split !== void 0 && _isMatch$value$split.includes(nodeItem[itemKeyName])) {
              nodeItem[optionName.disabled || 'disabled'] = true;
            } else if (nodeItem.hasOwnProperty(optionName.disabled || 'disabled')) {
              nodeItem[optionName.disabled || 'disabled'] = nodeItem[optionName.disabled || 'disabled'];
            }
          }
        });
        return nodeItem;
      };
      if (extra !== null && extra !== void 0 && extra.disabledFields && Array.isArray(extra === null || extra === void 0 ? void 0 : extra.disabledFields)) {
        item = resetByDisabledFields(item);
      }
      return _objectSpread(_objectSpread({}, item), {}, {
        key: item[optionName.value || optionName.key || 'key'],
        title: item[optionName.title || optionName.label || 'label' || 'title'],
        label: item[optionName.title || optionName.label || 'label' || 'title'],
        treeFullLevelNamePath: pathNodes,
        treeFullLevelName: pathNodes.map(function (item) {
          return item[optionName.title || optionName.label || 'label' || 'title'];
        }).join((extra === null || extra === void 0 ? void 0 : extra.separator) || '/'),
        treeParentKeys: newNodeInfo.parentKeys.reverse(),
        treeParentNodes: newNodeInfo.nodeParent.reverse()
        // children: trans(item[treeOptionName.children || 'children']),
        // disabled: item[treeOptionName.disabled || 'disabled'],
        // selectable: item[treeOptionName.selectable || 'selectable'],
      });
    });
  };
  return trans(array || []);
}

/**
 * 根据限制字段limitKey进行重组数据
 *
 * @params {array} hasKeys 已选择的数据
 * @params {array} list 树数据集合
 * @params {object} optionName 选项字段值
 * @params {string} limitKey 指定限制字段名
 *
 * @Return {array}  返回结果数据
 *
 * */
function resetDataWithLimit(hasKeys, list) {
  var optionName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    key: 'key',
    value: 'key',
    title: 'title',
    children: 'children',
    disabled: 'disabled',
    selectable: 'selectable'
  };
  var limitKey = arguments.length > 3 ? arguments[3] : undefined;
  // 利用ID匹配对应选中的完整节点数据
  var filterCheckedNode = function filterCheckedNode(ids, preList) {
    var matchList = [];
    if (Array.isArray(preList) && preList.length > 0) {
      preList.forEach(function (item, i) {
        if (ids.includes(item[optionName.value || 'value'])) {
          matchList.push(_objectSpread({}, item));
        }
        if (item[optionName.children || 'children']) {
          matchList = matchList.concat(filterCheckedNode(ids, item[optionName.children || 'children']));
        }
      });
    }
    return matchList;
  };

  // 筛选同一层级可选择，其他层级数据不可选择（限制按指定字段名的层级数据）
  var filterResetSameLevel = function filterResetSameLevel(preList, matchDataValue) {
    if (!preList) return [];
    if (!matchDataValue) return preList;
    return (preList || []).map(function (preItem) {
      var oldItem = _objectSpread({}, preItem);
      var item = Object.assign({}, (_objectDestructuringEmpty(oldItem), oldItem));
      if (item[limitKey] !== matchDataValue) {
        item.disabled = true;
      } else if (item.hasOwnProperty(optionName.disabled || 'disabled')) {
        item.disabled = item[optionName.disabled || 'disabled'];
      }
      // item.disabled = item[limitKey] !== matchDataValue || item[optionName.disabled || 'disabled']
      item.isLimit = item[limitKey] !== matchDataValue;
      // item.children = filterResetSameLevel(item['children'], matchDataValue)
      item[optionName.children || 'children'] = filterResetSameLevel(item[optionName.children || 'children'], matchDataValue);
      return _objectSpread({}, item);
    });
  };
  // 先筛选出来选中节点的数据，取其中的 level 层级的值(数据必须保证同级类型值一致)
  var prevList = list && Array.isArray(list) ? _toConsumableArray(list) : [];
  var _ref = _toConsumableArray(prevList),
    newList = _ref.slice(0);
  var filterLimitData = filterCheckedNode(hasKeys, newList);
  if (filterLimitData.length > 0) {
    return filterResetSameLevel(newList, filterLimitData[0][limitKey]);
  } else {
    return newList;
  }
}

/**
 * 根据指定禁用字段 disabledFields 进行重组数据
 *
 * @params {array} list 树数据集合
 * @params {object} optionName 选项字段值
 * @params {string} disabledFields 指定限制字段名
 *   @value {string} key:指定禁用的字段名
 *   @value {staring}value：指定禁用的字段值，多个用 , 隔开
 *
 * @Return {array}  返回结果数据
 *
 * */
function resetDataWithDisabled(list, optionName, disabledFields) {
  // 筛选与禁用字段内值相同的节点进行禁用
  var filterResetTargetFields = function filterResetTargetFields(preList, fields) {
    if (!preList) return [];
    return preList.map(function (preItem) {
      var oldItem = _objectSpread({}, preItem);
      var item = Object.assign({}, (_objectDestructuringEmpty(oldItem), oldItem));
      Object.keys(item).forEach(function (itemKeyName) {
        var isMatch = (fields || []).find(function (fItem) {
          return fItem.key === itemKeyName;
        });
        if (isMatch) {
          var _isMatch$value$split2;
          // 确认是否匹配数据，进行设置 disabled
          if ((_isMatch$value$split2 = isMatch.value.split(',')) !== null && _isMatch$value$split2 !== void 0 && _isMatch$value$split2.includes(item[itemKeyName])) {
            item.disabled = true;
            item[(optionName === null || optionName === void 0 ? void 0 : optionName.disabled) || 'disabled'] = true;
          } else if (item.hasOwnProperty(optionName.disabled || 'disabled')) {
            item.disabled = item[optionName.disabled || 'disabled'];
            item[(optionName === null || optionName === void 0 ? void 0 : optionName.disabled) || 'disabled'] = item[optionName.disabled || 'disabled'];
          }
        }
        if (itemKeyName === (optionName.children || 'children') || itemKeyName === 'children') {
          item[optionName.children || 'children'] = filterResetTargetFields(item[itemKeyName], fields);
        }
      });
      return _objectSpread({}, item);
    });
  };
  var prevList = list && Array.isArray(list) ? _toConsumableArray(list) : [];
  var _ref2 = _toConsumableArray(prevList),
    newList = _ref2.slice(0);
  return filterResetTargetFields(newList, disabledFields);
}

/**
 * 计算节点总数
 *
 * */
var countNodes = exports.countNodes = function countNodes(nodes) {
  var optionName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    children: 'children',
    disabled: 'disabled'
  };
  var count = 0;
  var stack = _toConsumableArray(nodes);
  while (stack.length) {
    var node = stack.pop();
    count++;
    if (node[(optionName === null || optionName === void 0 ? void 0 : optionName.children) || 'children'] && node[(optionName === null || optionName === void 0 ? void 0 : optionName.children) || 'children'].length) {
      stack.push.apply(stack, _toConsumableArray(node[(optionName === null || optionName === void 0 ? void 0 : optionName.children) || 'children']));
    }
  }
  return count;
};

/**
 * 全选树节点，排除禁用节点
 * @param {Array} treeData 树数据组
 * @param {Object} optionName 指定节点字段
 * @param {Boolean} updateSource 是否同步更改数据源，始数组内会加入 checked:true字段
 *
 * @return {Number} selectedAllCount  可全选的数量
 * @return {Array} selectedAllNodes   可全选的节点集合
 * @return {Array} selectedAllKeys  可全选的节点key集合
 * @return {Number } totalCount    全部节点数量
 * @return {Array } treeData       更改后的数量组
 *
 * @example selectAllExcludingDisabled([],{ children: 'children', disabled: 'disabled' }, false)
 * */

var selectAllExcludingDisabled = exports.selectAllExcludingDisabled = function selectAllExcludingDisabled(treeData) {
  var optionName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
    children: 'children',
    disabled: 'disabled',
    value: 'value'
  };
  var updateSource = arguments.length > 2 ? arguments[2] : undefined;
  var totalCount = 0;
  // const startTime = performance.now();
  // 创建树的深拷贝
  // const newTreeData = JSON.parse(JSON.stringify(treeData|| []));
  var stack = _toConsumableArray(treeData);
  var selectedCount = 0;
  var selectedNodes = [];
  var selectedKeys = [];
  while (stack.length) {
    var node = stack.pop();
    // console.log('node', node)
    totalCount++;
    // 只有当节点不是禁用状态时才选中
    if (!node[(optionName === null || optionName === void 0 ? void 0 : optionName.disabled) || 'disabled']) {
      if (updateSource) {
        node.checked = true; // 这个是更改原数据
      }
      selectedNodes.push(node);
      selectedKeys.push(node[(optionName === null || optionName === void 0 ? void 0 : optionName.value) || 'value']);
      selectedCount++;
    }

    // 如果有子节点，添加到栈中继续处理
    if (node[(optionName === null || optionName === void 0 ? void 0 : optionName.children) || 'children'] && node[(optionName === null || optionName === void 0 ? void 0 : optionName.children) || 'children'].length) {
      stack.push.apply(stack, _toConsumableArray(node[(optionName === null || optionName === void 0 ? void 0 : optionName.children) || 'children']));
    }
  }

  // const endTime = performance.now();
  // const pastTime = `全选操作: 选中 ${selectedCount} 个节点, 耗时: ${(endTime - startTime).toFixed(2)}ms`;

  return {
    count: selectedCount,
    nodes: selectedNodes,
    keys: selectedKeys,
    treeData: treeData,
    totalCount: totalCount
  };
};