import { createVNode as _createVNode } from "vue";
import { defineComponent, watch, provide, computed } from "vue";
import useMemo from "../_util/hooks/useMemo";
import { createItem, getNonLeafKeys, treeFindPath } from "./utils";
const menuProps = {
  prefixCls: {
    default: 'x-menu'
  },
  indent: {
    type: Number,
    default: 20
  },
  value: [String, Number],
  defaultExpandAll: Boolean,
  expandedKeys: Array,
  mode: {
    type: String,
    default: 'inline'
  },
  options: {
    type: Array,
    default: () => []
  },
  collapsed: {
    type: Boolean,
    default: false
  },
  disabled: Boolean,
  selectable: {
    default: true
  }
};
export const MenuContextKey = Symbol('menu');
export default defineComponent({
  name: 'x-menu',
  props: menuProps,
  emits: ['update:value', 'update:expandedKeys', 'expandChange', 'select', 'click'],

  setup(props, {
    emit
  }) {
    const expandedKeys = props.defaultExpandAll ? getNonLeafKeys(props.options) : [];
    const expandedKeysRef = useMemo(() => props.expandedKeys || expandedKeys);
    const valueRef = useMemo(() => props.value);
    const activePathRef = computed(() => {
      return treeFindPath(props.options, ({
        key
      }) => key === valueRef.value);
    });
    watch(() => props.collapsed, () => [onExpandChange([])]); // ========================== Event ==========================

    function onSelect(item) {
      emit('click', item);

      if (props.collapsed || props.mode === 'horizontal' || props.mode === 'vertical') {
        onExpandChange([]);
      }

      if (!props.selectable) return;
      const val = item.key;
      valueRef.value = val;
      emit('update:value', val);
      emit('select', item);
    }

    function onExpanded(item) {
      const val = item.key;
      const i = expandedKeysRef.value.findIndex(e => e == val);

      if (~i) {
        expandedKeysRef.value.splice(i, 1);
      } else {
        expandedKeysRef.value.push(val);
      }

      onExpandChange(expandedKeysRef.value);
    }

    function onExpandChange(arr) {
      emit('update:expandedKeys', expandedKeysRef.value = arr);
      emit('expandChange', arr);
    } // ========================== Provide ==========================


    provide(MenuContextKey, {
      props,
      valueRef,
      expandedKeysRef,
      activePathRef,
      collapsedRef: computed(() => props.collapsed),
      onSelect,
      onExpanded
    });
    return () => {
      const {
        prefixCls
      } = props;
      const cls = {
        [prefixCls]: true,
        [`${prefixCls}-collapsed`]: props.collapsed,
        [`${prefixCls}-${props.mode}`]: true
      };
      return _createVNode("div", {
        "class": cls,
        "role": "menu"
      }, [props.options.map(createItem)]);
    };
  }

});