"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
const aria$1 = require("../../../utils/dom/aria.js");
const aria = require("../../../constants/aria.js");
const event = require("../../../constants/event.js");
const event$1 = require("../../../utils/dom/event.js");
const types$1 = require("../../../utils/types.js");
const scroll = require("../../../utils/dom/scroll.js");
const arrays = require("../../../utils/arrays.js");
const index = require("../../../hooks/use-namespace/index.js");
const config = require("./config.js");
const types = require("./types.js");
const menu = require("./menu.js");
const node = require("./node.js");
const store = require("./store.js");
const utils = require("./utils.js");
const vue = require("vue");
const isEqual = require("../../../../../lodash-es/isEqual.js");
const flattenDeep = require("../../../../../lodash-es/flattenDeep.js");
const cloneDeep = require("../../../../../lodash-es/cloneDeep.js");
const index$1 = require("../../../../node_modules/@vueuse/shared/index.js");
var index_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ vue.defineComponent({
  name: "ElCascaderPanel",
  __name: "index",
  props: config.cascaderPanelProps,
  emits: config.cascaderPanelEmits,
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emit = __emit;
    let manualChecked = false;
    const ns = index.useNamespace("cascader");
    const config$1 = config.useCascaderConfig(props);
    const slots = vue.useSlots();
    let store$1;
    const initialLoaded = vue.ref(true);
    const initialLoadedOnce = vue.ref(false);
    const menuList = vue.ref([]);
    const checkedValue = vue.ref();
    const menus = vue.ref([]);
    const expandingNode = vue.ref();
    const checkedNodes = vue.ref([]);
    const isHoverMenu = vue.computed(() => config$1.value.expandTrigger === "hover");
    const renderLabelFn = vue.computed(() => props.renderLabel || slots.default);
    const initStore = () => {
      const { options } = props;
      const cfg = config$1.value;
      manualChecked = false;
      store$1 = new store.default(options, cfg);
      menus.value = [store$1.getNodes()];
      if (cfg.lazy && types$1.isEmpty(props.options)) {
        initialLoaded.value = false;
        lazyLoad(void 0, (list) => {
          if (list) {
            store$1 = new store.default(list, cfg);
            menus.value = [store$1.getNodes()];
          }
          initialLoaded.value = true;
          syncCheckedValue(false, true);
        });
      } else syncCheckedValue(false, true);
    };
    const lazyLoad = (node$1, cb) => {
      const cfg = config$1.value;
      node$1 = node$1 || new node.default({}, cfg, void 0, true);
      node$1.loading = true;
      const resolve = (dataList) => {
        const _node = node$1;
        const parent = _node.root ? null : _node;
        _node.loading = false;
        _node.loaded = true;
        _node.childrenData = _node.childrenData || [];
        dataList && (store$1 == null ? void 0 : store$1.appendNodes(dataList, parent));
        dataList && (cb == null ? void 0 : cb(dataList));
        if (node$1.level === 0) initialLoadedOnce.value = true;
      };
      const reject = () => {
        node$1.loading = false;
        node$1.loaded = false;
        if (node$1.level === 0) initialLoaded.value = true;
      };
      cfg.lazyLoad(node$1, resolve, reject);
    };
    const expandNode = (node2, silent) => {
      var _a;
      const { level } = node2;
      const newMenus = menus.value.slice(0, level);
      let newExpandingNode;
      if (node2.isLeaf) newExpandingNode = node2.pathNodes[level - 2];
      else {
        newExpandingNode = node2;
        newMenus.push(node2.children);
      }
      if (((_a = expandingNode.value) == null ? void 0 : _a.uid) !== (newExpandingNode == null ? void 0 : newExpandingNode.uid)) {
        expandingNode.value = node2;
        menus.value = newMenus;
        !silent && emit("expand-change", (node2 == null ? void 0 : node2.pathValues) || []);
      }
    };
    const handleCheckChange = (node2, checked, emitClose = true) => {
      const { checkStrictly, multiple } = config$1.value;
      const oldNode = checkedNodes.value[0];
      manualChecked = true;
      !multiple && (oldNode == null ? void 0 : oldNode.doCheck(false));
      node2.doCheck(checked);
      calculateCheckedValue();
      emitClose && !multiple && !checkStrictly && emit("close");
      !emitClose && !multiple && expandParentNode(node2);
    };
    const expandParentNode = (node2) => {
      if (!node2) return;
      node2 = node2.parent;
      expandParentNode(node2);
      node2 && expandNode(node2);
    };
    const getFlattedNodes = (leafOnly) => store$1 == null ? void 0 : store$1.getFlattedNodes(leafOnly);
    const getCheckedNodes = (leafOnly) => {
      var _a;
      return (_a = getFlattedNodes(leafOnly)) == null ? void 0 : _a.filter(({ checked }) => checked !== false);
    };
    const clearCheckedNodes = () => {
      checkedNodes.value.forEach((node2) => node2.doCheck(false));
      calculateCheckedValue();
      menus.value = menus.value.slice(0, 1);
      expandingNode.value = void 0;
      emit("expand-change", []);
    };
    const calculateCheckedValue = () => {
      const { checkStrictly, multiple } = config$1.value;
      const oldNodes = checkedNodes.value;
      const nodes = utils.sortByOriginalOrder(oldNodes, getCheckedNodes(!checkStrictly));
      const values = nodes.map((node2) => node2.valueByOption);
      checkedNodes.value = nodes;
      checkedValue.value = multiple ? values : values[0] ?? null;
    };
    const syncCheckedValue = (loaded = false, forced = false) => {
      const { modelValue } = props;
      const { lazy, multiple, checkStrictly } = config$1.value;
      const leafOnly = !checkStrictly;
      if (!initialLoaded.value || manualChecked || !forced && isEqual.default(modelValue, checkedValue.value)) return;
      if (lazy && !loaded) {
        const nodes = arrays.unique(flattenDeep.default(arrays.castArray(modelValue))).map((val) => store$1 == null ? void 0 : store$1.getNodeByValue(val)).filter((node2) => !!node2 && !node2.loaded && !node2.loading);
        if (nodes.length) nodes.forEach((node2) => {
          lazyLoad(node2, () => syncCheckedValue(false, forced));
        });
        else syncCheckedValue(true, forced);
      } else {
        syncMenuState(arrays.unique((multiple ? arrays.castArray(modelValue) : [modelValue]).map((val) => store$1 == null ? void 0 : store$1.getNodeByValue(val, leafOnly))), forced);
        checkedValue.value = cloneDeep.default(modelValue ?? void 0);
      }
    };
    const syncMenuState = (newCheckedNodes, reserveExpandingState = true) => {
      const { checkStrictly } = config$1.value;
      const oldNodes = checkedNodes.value;
      const newNodes = newCheckedNodes.filter((node2) => !!node2 && (checkStrictly || node2.isLeaf));
      const oldExpandingNode = store$1 == null ? void 0 : store$1.getSameNode(expandingNode.value);
      const newExpandingNode = reserveExpandingState && oldExpandingNode || newNodes[0];
      if (newExpandingNode) newExpandingNode.pathNodes.forEach((node2) => expandNode(node2, true));
      else expandingNode.value = void 0;
      oldNodes.forEach((node2) => node2.doCheck(false));
      vue.reactive(newNodes).forEach((node2) => node2.doCheck(true));
      checkedNodes.value = newNodes;
      vue.nextTick(scrollToExpandingNode);
    };
    const scrollToExpandingNode = () => {
      if (!index$1.isClient) return;
      menuList.value.forEach((menu2) => {
        const menuElement = menu2 == null ? void 0 : menu2.$el;
        if (menuElement) {
          const container = menuElement.querySelector(`.${ns.namespace.value}-scrollbar__wrap`);
          let activeNode = menuElement.querySelector(`.${ns.b("node")}.in-active-path`);
          if (!activeNode) {
            const activeElements = menuElement.querySelectorAll(`.${ns.b("node")}.${ns.is("active")}`);
            activeNode = activeElements[activeElements.length - 1];
          }
          scroll.scrollIntoView(container, activeNode);
        }
      });
    };
    const handleKeyDown = (e) => {
      var _a, _b;
      const target = e.target;
      const code = event$1.getEventCode(e);
      switch (code) {
        case aria.EVENT_CODE.up:
        case aria.EVENT_CODE.down:
          e.preventDefault();
          aria$1.focusNode(aria$1.getSibling(target, code === aria.EVENT_CODE.up ? -1 : 1, `.${ns.b("node")}[tabindex="-1"]`));
          break;
        case aria.EVENT_CODE.left: {
          e.preventDefault();
          const expandedNode = (_a = menuList.value[utils.getMenuIndex(target) - 1]) == null ? void 0 : _a.$el.querySelector(`.${ns.b("node")}[aria-expanded="true"]`);
          aria$1.focusNode(expandedNode);
          break;
        }
        case aria.EVENT_CODE.right: {
          e.preventDefault();
          const firstNode = (_b = menuList.value[utils.getMenuIndex(target) + 1]) == null ? void 0 : _b.$el.querySelector(`.${ns.b("node")}[tabindex="-1"]`);
          aria$1.focusNode(firstNode);
          break;
        }
        case aria.EVENT_CODE.enter:
        case aria.EVENT_CODE.numpadEnter:
          utils.checkNode(target);
          break;
      }
    };
    vue.provide(types.CASCADER_PANEL_INJECTION_KEY, vue.reactive({
      config: config$1,
      expandingNode,
      checkedNodes,
      isHoverMenu,
      initialLoaded,
      renderLabelFn,
      lazyLoad,
      expandNode,
      handleCheckChange
    }));
    vue.watch(config$1, (newVal, oldVal) => {
      if (isEqual.default(newVal, oldVal)) return;
      initStore();
    }, { immediate: true });
    vue.watch(() => props.options, initStore, { deep: true });
    vue.watch(() => props.modelValue, () => {
      manualChecked = false;
      syncCheckedValue();
    }, { deep: true });
    vue.watch(() => checkedValue.value, (val) => {
      if (!isEqual.default(val, props.modelValue)) {
        emit(event.UPDATE_MODEL_EVENT, val);
        emit(event.CHANGE_EVENT, val);
      }
    });
    const loadLazyRootNodes = () => {
      if (initialLoadedOnce.value) return;
      initStore();
    };
    vue.onBeforeUpdate(() => menuList.value = []);
    vue.onMounted(() => !types$1.isEmpty(props.modelValue) && syncCheckedValue());
    __expose({
      menuList,
      menus,
      checkedNodes,
      handleKeyDown,
      handleCheckChange,
      getFlattedNodes,
      getCheckedNodes,
      clearCheckedNodes,
      calculateCheckedValue,
      scrollToExpandingNode,
      loadLazyRootNodes
    });
    return (_ctx, _cache) => {
      return vue.openBlock(), vue.createElementBlock("div", {
        class: vue.normalizeClass([vue.unref(ns).b("panel"), vue.unref(ns).is("bordered", __props.border)]),
        onKeydown: handleKeyDown
      }, [(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(menus.value, (menu$1, index2) => {
        return vue.openBlock(), vue.createBlock(menu.default, {
          key: index2,
          ref_for: true,
          ref: (item) => menuList.value[index2] = item,
          index: index2,
          nodes: [...menu$1]
        }, {
          empty: vue.withCtx(() => [vue.renderSlot(_ctx.$slots, "empty")]),
          _: 3
        }, 8, ["index", "nodes"]);
      }), 128))], 34);
    };
  }
});
exports.default = index_vue_vue_type_script_setup_true_lang_default;
