import { createPopper } from '@popperjs/core';
import { get, merge, flatMap } from 'lodash-unified';
import escapeHtml from 'escape-html';
import '../../../utils/index.mjs';
import '../../../hooks/index.mjs';
import { isObject, hasOwn, isArray } from '@vue/shared';
import { throwError } from '../../../utils/error.mjs';
import { isBoolean } from '../../../utils/types.mjs';
import { useZIndex } from '../../../hooks/use-z-index/index.mjs';
import { useDelayedToggle } from '../../../hooks/use-delayed-toggle/index.mjs';

const getCell = function(event) {
  var _a;
  return (_a = event.target) == null ? void 0 : _a.closest("td");
};
const orderBy = function(array, sortKey, reverse, sortMethod, sortBy) {
  if (!sortKey && !sortMethod && (!sortBy || Array.isArray(sortBy) && !sortBy.length)) {
    return array;
  }
  if (typeof reverse === "string") {
    reverse = reverse === "descending" ? -1 : 1;
  } else {
    reverse = reverse && reverse < 0 ? -1 : 1;
  }
  const getKey = sortMethod ? null : function(value, index) {
    if (sortBy) {
      if (!Array.isArray(sortBy)) {
        sortBy = [sortBy];
      }
      return sortBy.map((by) => {
        if (typeof by === "string") {
          return get(value, by);
        } else {
          return by(value, index, array);
        }
      });
    }
    if (sortKey !== "$key") {
      if (isObject(value) && "$value" in value)
        value = value.$value;
    }
    return [isObject(value) ? get(value, sortKey) : value];
  };
  const compare = function(a, b) {
    if (sortMethod) {
      return sortMethod(a.value, b.value);
    }
    for (let i = 0, len = a.key.length; i < len; i++) {
      if (a.key[i] < b.key[i]) {
        return -1;
      }
      if (a.key[i] > b.key[i]) {
        return 1;
      }
    }
    return 0;
  };
  return array.map((value, index) => {
    return {
      value,
      index,
      key: getKey ? getKey(value, index) : null
    };
  }).sort((a, b) => {
    let order = compare(a, b);
    if (!order) {
      order = a.index - b.index;
    }
    return order * +reverse;
  }).map((item) => item.value);
};
const getColumnById = function(table, columnId) {
  let column = null;
  table.columns.forEach((item) => {
    if (item.id === columnId) {
      column = item;
    }
  });
  return column;
};
const getColumnByKey = function(table, columnKey) {
  let column = null;
  for (let i = 0; i < table.columns.length; i++) {
    const item = table.columns[i];
    if (item.columnKey === columnKey) {
      column = item;
      break;
    }
  }
  if (!column)
    throwError("ElTable", `No column matching with column-key: ${columnKey}`);
  return column;
};
const getColumnByCell = function(table, cell, namespace) {
  const matches = (cell.className || "").match(new RegExp(`${namespace}-table_[^\\s]+`, "gm"));
  if (matches) {
    return getColumnById(table, matches[0]);
  }
  return null;
};
const getRowIdentity = (row, rowKey) => {
  if (!row)
    throw new Error("Row is required when get row identity");
  if (typeof rowKey === "string") {
    if (!rowKey.includes(".")) {
      return `${row[rowKey]}`;
    }
    const key = rowKey.split(".");
    let current = row;
    for (const element of key) {
      current = current[element];
    }
    return `${current}`;
  } else if (typeof rowKey === "function") {
    return rowKey.call(null, row);
  }
};
const getKeysMap = function(array, rowKey) {
  const arrayMap = {};
  (array || []).forEach((row, index) => {
    arrayMap[getRowIdentity(row, rowKey)] = { row, index };
  });
  return arrayMap;
};
function mergeOptions(defaults, config) {
  const options = {};
  let key;
  for (key in defaults) {
    options[key] = defaults[key];
  }
  for (key in config) {
    if (hasOwn(config, key)) {
      const value = config[key];
      if (typeof value !== "undefined") {
        options[key] = value;
      }
    }
  }
  return options;
}
function parseWidth(width) {
  if (width === "")
    return width;
  if (width !== void 0) {
    width = Number.parseInt(width, 10);
    if (Number.isNaN(width)) {
      width = "";
    }
  }
  return width;
}
function parseMinWidth(minWidth) {
  if (minWidth === "")
    return minWidth;
  if (minWidth !== void 0) {
    minWidth = parseWidth(minWidth);
    if (Number.isNaN(minWidth)) {
      minWidth = 80;
    }
  }
  return minWidth;
}
function parseHeight(height) {
  if (typeof height === "number") {
    return height;
  }
  if (typeof height === "string") {
    if (/^\d+(?:px)?$/.test(height)) {
      return Number.parseInt(height, 10);
    } else {
      return height;
    }
  }
  return null;
}
function compose(...funcs) {
  if (funcs.length === 0) {
    return (arg) => arg;
  }
  if (funcs.length === 1) {
    return funcs[0];
  }
  return funcs.reduce((a, b) => (...args) => a(b(...args)));
}
function toggleRowStatus(statusArr, row, newVal) {
  let changed = false;
  const index = statusArr.indexOf(row);
  const included = index !== -1;
  const toggleStatus = (type) => {
    if (type === "add") {
      statusArr.push(row);
    } else {
      statusArr.splice(index, 1);
    }
    changed = true;
    if (isArray(row.children)) {
      row.children.forEach((item) => {
        toggleRowStatus(statusArr, item, newVal != null ? newVal : !included);
      });
    }
  };
  if (isBoolean(newVal)) {
    if (newVal && !included) {
      toggleStatus("add");
    } else if (!newVal && included) {
      toggleStatus("remove");
    }
  } else {
    included ? toggleStatus("remove") : toggleStatus("add");
  }
  return changed;
}
function walkTreeNode(root, cb, childrenKey = "children", lazyKey = "hasChildren") {
  const isNil = (array) => !(Array.isArray(array) && array.length);
  function _walker(parent, children, level) {
    cb(parent, children, level);
    children.forEach((item) => {
      if (item[lazyKey]) {
        cb(item, null, level + 1);
        return;
      }
      const children2 = item[childrenKey];
      if (!isNil(children2)) {
        _walker(item, children2, level + 1);
      }
    });
  }
  root.forEach((item) => {
    if (item[lazyKey]) {
      cb(item, null, 0);
      return;
    }
    const children = item[childrenKey];
    if (!isNil(children)) {
      _walker(item, children, 0);
    }
  });
}
let removePopper;
function createTablePopper(parentNode, trigger, popperContent, tooltipOptions) {
  tooltipOptions = merge({
    enterable: true,
    showArrow: true
  }, tooltipOptions);
  const { nextZIndex } = useZIndex();
  const ns = parentNode == null ? void 0 : parentNode.dataset.prefix;
  const scrollContainer = parentNode == null ? void 0 : parentNode.querySelector(`.${ns}-scrollbar__wrap`);
  function renderContent() {
    const isLight = tooltipOptions.effect === "light";
    const content2 = document.createElement("div");
    content2.className = [
      `${ns}-popper`,
      isLight ? "is-light" : "is-dark",
      tooltipOptions.popperClass || ""
    ].join(" ");
    popperContent = escapeHtml(popperContent);
    content2.innerHTML = popperContent;
    content2.style.zIndex = String(nextZIndex());
    parentNode == null ? void 0 : parentNode.appendChild(content2);
    return content2;
  }
  function renderArrow() {
    const arrow = document.createElement("div");
    arrow.className = `${ns}-popper__arrow`;
    return arrow;
  }
  function showPopper() {
    popperInstance && popperInstance.update();
  }
  removePopper == null ? void 0 : removePopper();
  removePopper = () => {
    try {
      popperInstance && popperInstance.destroy();
      content && (parentNode == null ? void 0 : parentNode.removeChild(content));
      trigger.removeEventListener("mouseenter", onOpen);
      trigger.removeEventListener("mouseleave", onClose);
      scrollContainer == null ? void 0 : scrollContainer.removeEventListener("scroll", removePopper);
      removePopper = void 0;
    } catch (e) {
    }
  };
  let popperInstance = null;
  let onOpen = showPopper;
  let onClose = removePopper;
  if (tooltipOptions.enterable) {
    ;
    ({ onOpen, onClose } = useDelayedToggle({
      showAfter: tooltipOptions.showAfter,
      hideAfter: tooltipOptions.hideAfter,
      open: showPopper,
      close: removePopper
    }));
  }
  const content = renderContent();
  content.onmouseenter = onOpen;
  content.onmouseleave = onClose;
  const modifiers = [];
  if (tooltipOptions.offset) {
    modifiers.push({
      name: "offset",
      options: {
        offset: [0, tooltipOptions.offset]
      }
    });
  }
  if (tooltipOptions.showArrow) {
    const arrow = content.appendChild(renderArrow());
    modifiers.push({
      name: "arrow",
      options: {
        element: arrow,
        padding: 10
      }
    });
  }
  const popperOptions = tooltipOptions.popperOptions || {};
  popperInstance = createPopper(trigger, content, {
    placement: tooltipOptions.placement || "top",
    strategy: "fixed",
    ...popperOptions,
    modifiers: popperOptions.modifiers ? modifiers.concat(popperOptions.modifiers) : modifiers
  });
  trigger.addEventListener("mouseenter", onOpen);
  trigger.addEventListener("mouseleave", onClose);
  scrollContainer == null ? void 0 : scrollContainer.addEventListener("scroll", removePopper);
  return popperInstance;
}
function getCurrentColumns(column) {
  if (column.children) {
    return flatMap(column.children, getCurrentColumns);
  } else {
    return [column];
  }
}
function getColSpan(colSpan, column) {
  return colSpan + column.colSpan;
}
const isFixedColumn = (index, fixed, store, realColumns) => {
  let start = 0;
  let after = index;
  const columns = store.states.columns.value;
  if (realColumns) {
    const curColumns = getCurrentColumns(realColumns[index]);
    const preColumns = columns.slice(0, columns.indexOf(curColumns[0]));
    start = preColumns.reduce(getColSpan, 0);
    after = start + curColumns.reduce(getColSpan, 0) - 1;
  } else {
    start = index;
  }
  let fixedLayout;
  switch (fixed) {
    case "left":
      if (after < store.states.fixedLeafColumnsLength.value) {
        fixedLayout = "left";
      }
      break;
    case "right":
      if (start >= columns.length - store.states.rightFixedLeafColumnsLength.value) {
        fixedLayout = "right";
      }
      break;
    case "notfixed":
      break;
    default:
      if (after < store.states.fixedLeafColumnsLength.value) {
        fixedLayout = "left";
      } else if (start >= columns.length - store.states.rightFixedLeafColumnsLength.value) {
        fixedLayout = "right";
      }
  }
  return fixedLayout ? {
    direction: fixedLayout,
    start,
    after
  } : {};
};
const getFixedColumnsClass = (namespace, index, fixed, store, realColumns, offset = 0) => {
  const classes = [];
  const { direction, start, after } = isFixedColumn(index, fixed, store, realColumns);
  if (direction) {
    const isLeft = direction === "left";
    classes.push(`${namespace}-fixed-column--${direction}`);
    if (isLeft && after + offset === store.states.fixedLeafColumnsLength.value - 1) {
      classes.push("is-last-column");
    } else if (!isLeft && start - offset === store.states.columns.value.length - store.states.rightFixedLeafColumnsLength.value) {
      classes.push("is-first-column");
    }
  }
  return classes;
};
function getOffset(offset, column) {
  return offset + (column.realWidth === null || Number.isNaN(column.realWidth) ? Number(column.width) : column.realWidth);
}
const getFixedColumnOffset = (index, fixed, store, realColumns) => {
  const {
    direction,
    start = 0,
    after = 0
  } = isFixedColumn(index, fixed, store, realColumns);
  if (!direction) {
    return;
  }
  const styles = {};
  const isLeft = direction === "left";
  const columns = store.states.columns.value;
  if (isLeft) {
    styles.left = columns.slice(0, start).reduce(getOffset, 0);
  } else {
    styles.right = columns.slice(after + 1).reverse().reduce(getOffset, 0);
  }
  return styles;
};
const ensurePosition = (style, key) => {
  if (!style)
    return;
  if (!Number.isNaN(style[key])) {
    style[key] = `${style[key]}px`;
  }
};

export { compose, createTablePopper, ensurePosition, getCell, getColumnByCell, getColumnById, getColumnByKey, getFixedColumnOffset, getFixedColumnsClass, getKeysMap, getRowIdentity, isFixedColumn, mergeOptions, orderBy, parseHeight, parseMinWidth, parseWidth, removePopper, toggleRowStatus, walkTreeNode };
//# sourceMappingURL=util.mjs.map
