import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
var _excluded = ["eventKey", "dragOver", "dragOverGapTop", "dragOverGapBottom", "isLeaf", "isStart", "isEnd", "expanded", "selected", "checked", "halfChecked", "loading", "domRef", "active", "data", "onMousemove"];
import { createVNode as _createVNode } from "vue";
import { useInjectTreeContext } from './contextTypes';
import { getDataAndAria } from './util';
import Indent from './Indent';
import { convertNodePropsToEventData } from './utils/treeUtil';
import { computed, defineComponent, getCurrentInstance, onMounted, onUpdated, reactive, ref } from 'vue';
import { treeNodeProps } from './props';
import classNames from '../_util/classNames';
import { warning } from '../vc-util/warning';
import pick from 'lodash-es/pick';
var ICON_OPEN = 'open';
var ICON_CLOSE = 'close';
var defaultTitle = '---';
export default defineComponent({
  name: 'TreeNode',
  inheritAttrs: false,
  props: treeNodeProps,
  isTreeNode: 1,
  slots: ['title', 'icon', 'switcherIcon'],
  setup: function setup(props, _ref) {
    var attrs = _ref.attrs,
        slots = _ref.slots,
        expose = _ref.expose;
    warning(!('slots' in props.data), "treeData slots is deprecated, please use ".concat(Object.keys(props.data.slots || {}).map(function (key) {
      return '`v-slot:' + key + '` ';
    }), "instead"));
    var dragNodeHighlight = ref(false);
    var context = useInjectTreeContext();
    var selectHandle = ref();
    var hasChildren = computed(function () {
      var eventKey = props.eventKey;
      var keyEntities = context.value.keyEntities;

      var _ref2 = keyEntities[eventKey] || {},
          children = _ref2.children;

      return !!(children || []).length;
    });
    var isLeaf = computed(function () {
      var isLeaf = props.isLeaf,
          loaded = props.loaded;
      var loadData = context.value.loadData;
      var has = hasChildren.value;

      if (isLeaf === false) {
        return false;
      }

      return isLeaf || !loadData && !has || loadData && loaded && !has;
    });
    var nodeState = computed(function () {
      var expanded = props.expanded;

      if (isLeaf.value) {
        return null;
      }

      return expanded ? ICON_OPEN : ICON_CLOSE;
    });
    var isDisabled = computed(function () {
      var disabled = props.disabled;
      var treeDisabled = context.value.disabled;
      return !!(treeDisabled || disabled);
    });
    var isCheckable = computed(function () {
      var checkable = props.checkable;
      var treeCheckable = context.value.checkable; // Return false if tree or treeNode is not checkable

      if (!treeCheckable || checkable === false) return false;
      return treeCheckable;
    });
    var isSelectable = computed(function () {
      var selectable = props.selectable;
      var treeSelectable = context.value.selectable; // Ignore when selectable is undefined or null

      if (typeof selectable === 'boolean') {
        return selectable;
      }

      return treeSelectable;
    });
    var renderArgsData = computed(function () {
      return _objectSpread(_objectSpread(_objectSpread({}, pick(props, ['active', 'checkable', 'checked', 'disableCheckbox', 'disabled', 'expanded', 'isLeaf', 'loading', 'selectable', 'selected', 'halfChecked'])), props.data), {}, {
        dataRef: props.data,
        data: props.data,
        isLeaf: isLeaf.value
      });
    });
    var eventData = computed(function () {
      return convertNodePropsToEventData(props);
    });
    var dragNodeEvent = reactive({
      eventData: eventData,
      eventKey: computed(function () {
        return props.eventKey;
      }),
      selectHandle: selectHandle,
      pos: computed(function () {
        return props.pos;
      }),
      key: getCurrentInstance().vnode.key
    });
    expose(dragNodeEvent);

    var onSelectorDoubleClick = function onSelectorDoubleClick(e) {
      var onNodeDoubleClick = context.value.onNodeDoubleClick;
      onNodeDoubleClick(e, eventData.value);
    };

    var onSelect = function onSelect(e) {
      if (isDisabled.value) return;
      var onNodeSelect = context.value.onNodeSelect;
      e.preventDefault();
      onNodeSelect(e, eventData.value);
    };

    var onCheck = function onCheck(e) {
      if (isDisabled.value) return;
      var disableCheckbox = props.disableCheckbox,
          checked = props.checked;
      var onNodeCheck = context.value.onNodeCheck;
      if (!isCheckable.value || disableCheckbox) return;
      e.preventDefault();
      var targetChecked = !checked;
      onNodeCheck(e, eventData.value, targetChecked);
    };

    var onSelectorClick = function onSelectorClick(e) {
      // Click trigger before select/check operation
      var onNodeClick = context.value.onNodeClick;
      onNodeClick(e, eventData.value);

      if (isSelectable.value) {
        onSelect(e);
      } else {
        onCheck(e);
      }
    };

    var onMouseEnter = function onMouseEnter(e) {
      var onNodeMouseEnter = context.value.onNodeMouseEnter;
      onNodeMouseEnter(e, eventData.value);
    };

    var onMouseLeave = function onMouseLeave(e) {
      var onNodeMouseLeave = context.value.onNodeMouseLeave;
      onNodeMouseLeave(e, eventData.value);
    };

    var onContextmenu = function onContextmenu(e) {
      var onNodeContextMenu = context.value.onNodeContextMenu;
      onNodeContextMenu(e, eventData.value);
    };

    var onDragStart = function onDragStart(e) {
      var onNodeDragStart = context.value.onNodeDragStart;
      e.stopPropagation();
      dragNodeHighlight.value = true;
      onNodeDragStart(e, dragNodeEvent);

      try {
        // ie throw error
        // firefox-need-it
        e.dataTransfer.setData('text/plain', '');
      } catch (error) {// empty
      }
    };

    var onDragEnter = function onDragEnter(e) {
      var onNodeDragEnter = context.value.onNodeDragEnter;
      e.preventDefault();
      e.stopPropagation();
      onNodeDragEnter(e, dragNodeEvent);
    };

    var onDragOver = function onDragOver(e) {
      var onNodeDragOver = context.value.onNodeDragOver;
      e.preventDefault();
      e.stopPropagation();
      onNodeDragOver(e, dragNodeEvent);
    };

    var onDragLeave = function onDragLeave(e) {
      var onNodeDragLeave = context.value.onNodeDragLeave;
      e.stopPropagation();
      onNodeDragLeave(e, dragNodeEvent);
    };

    var onDragEnd = function onDragEnd(e) {
      var onNodeDragEnd = context.value.onNodeDragEnd;
      e.stopPropagation();
      dragNodeHighlight.value = false;
      onNodeDragEnd(e, dragNodeEvent);
    };

    var onDrop = function onDrop(e) {
      var onNodeDrop = context.value.onNodeDrop;
      e.preventDefault();
      e.stopPropagation();
      dragNodeHighlight.value = false;
      onNodeDrop(e, dragNodeEvent);
    }; // Disabled item still can be switch


    var onExpand = function onExpand(e) {
      var onNodeExpand = context.value.onNodeExpand;
      if (props.loading) return;
      onNodeExpand(e, eventData.value);
    };

    var renderSwitcherIconDom = function renderSwitcherIconDom() {
      var _context$value$slots, _props$data, _props$data$slots;

      var _props$switcherIcon = props.switcherIcon,
          switcherIconFromProps = _props$switcherIcon === void 0 ? slots.switcherIcon || ((_context$value$slots = context.value.slots) === null || _context$value$slots === void 0 ? void 0 : _context$value$slots[(_props$data = props.data) === null || _props$data === void 0 ? void 0 : (_props$data$slots = _props$data.slots) === null || _props$data$slots === void 0 ? void 0 : _props$data$slots.switcherIcon]) : _props$switcherIcon;
      var switcherIconFromCtx = context.value.switcherIcon;
      var switcherIcon = switcherIconFromProps || switcherIconFromCtx; // if switcherIconDom is null, no render switcher span

      if (typeof switcherIcon === 'function') {
        return switcherIcon(renderArgsData.value);
      }

      return switcherIcon;
    }; // Load data to avoid default expanded tree without data


    var syncLoadData = function syncLoadData() {
      var expanded = props.expanded,
          loading = props.loading,
          loaded = props.loaded;
      var _context$value = context.value,
          loadData = _context$value.loadData,
          onNodeLoad = _context$value.onNodeLoad;

      if (loading) {
        return;
      } // read from state to avoid loadData at same time


      if (loadData && expanded && !isLeaf.value) {
        // We needn't reload data when has children in sync logic
        // It's only needed in node expanded
        if (!hasChildren.value && !loaded) {
          onNodeLoad(eventData.value);
        }
      }
    };

    onMounted(function () {
      syncLoadData();
    });
    onUpdated(function () {//syncLoadData();
    }); // Switcher

    var renderSwitcher = function renderSwitcher() {
      var expanded = props.expanded;
      var prefixCls = context.value.prefixCls; // if switcherIconDom is null, no render switcher span

      var switcherIconDom = renderSwitcherIconDom();

      if (isLeaf.value) {
        return switcherIconDom !== false ? _createVNode("span", {
          "class": classNames("".concat(prefixCls, "-switcher"), "".concat(prefixCls, "-switcher-noop"))
        }, [switcherIconDom]) : null;
      }

      var switcherCls = classNames("".concat(prefixCls, "-switcher"), "".concat(prefixCls, "-switcher_").concat(expanded ? ICON_OPEN : ICON_CLOSE));
      return switcherIconDom !== false ? _createVNode("span", {
        "onClick": onExpand,
        "class": switcherCls
      }, [switcherIconDom]) : null;
    }; // Checkbox


    var renderCheckbox = function renderCheckbox() {
      var _context$value$custom, _context$value2;

      var checked = props.checked,
          halfChecked = props.halfChecked,
          disableCheckbox = props.disableCheckbox;
      var prefixCls = context.value.prefixCls;
      var disabled = isDisabled.value;
      var checkable = isCheckable.value;
      if (!checkable) return null;
      return _createVNode("span", {
        "class": classNames("".concat(prefixCls, "-checkbox"), checked && "".concat(prefixCls, "-checkbox-checked"), !checked && halfChecked && "".concat(prefixCls, "-checkbox-indeterminate"), (disabled || disableCheckbox) && "".concat(prefixCls, "-checkbox-disabled")),
        "onClick": onCheck
      }, [(_context$value$custom = (_context$value2 = context.value).customCheckable) === null || _context$value$custom === void 0 ? void 0 : _context$value$custom.call(_context$value2)]);
    };

    var renderIcon = function renderIcon() {
      var loading = props.loading;
      var prefixCls = context.value.prefixCls;
      return _createVNode("span", {
        "class": classNames("".concat(prefixCls, "-iconEle"), "".concat(prefixCls, "-icon__").concat(nodeState.value || 'docu'), loading && "".concat(prefixCls, "-icon_loading"))
      }, null);
    };

    var renderDropIndicator = function renderDropIndicator() {
      var disabled = props.disabled,
          eventKey = props.eventKey;
      var _context$value3 = context.value,
          draggable = _context$value3.draggable,
          dropLevelOffset = _context$value3.dropLevelOffset,
          dropPosition = _context$value3.dropPosition,
          prefixCls = _context$value3.prefixCls,
          indent = _context$value3.indent,
          dropIndicatorRender = _context$value3.dropIndicatorRender,
          dragOverNodeKey = _context$value3.dragOverNodeKey,
          direction = _context$value3.direction;
      var mergedDraggable = draggable !== false; // allowDrop is calculated in Tree.tsx, there is no need for calc it here

      var showIndicator = !disabled && mergedDraggable && dragOverNodeKey === eventKey;
      return showIndicator ? dropIndicatorRender({
        dropPosition: dropPosition,
        dropLevelOffset: dropLevelOffset,
        indent: indent,
        prefixCls: prefixCls,
        direction: direction
      }) : null;
    }; // Icon + Title


    var renderSelector = function renderSelector() {
      var _context$value$slots2, _props$data2, _props$data2$slots, _context$value$slots3;

      var selected = props.selected,
          _props$icon = props.icon,
          icon = _props$icon === void 0 ? slots.icon : _props$icon,
          loading = props.loading,
          data = props.data;
      var title = slots.title || ((_context$value$slots2 = context.value.slots) === null || _context$value$slots2 === void 0 ? void 0 : _context$value$slots2[(_props$data2 = props.data) === null || _props$data2 === void 0 ? void 0 : (_props$data2$slots = _props$data2.slots) === null || _props$data2$slots === void 0 ? void 0 : _props$data2$slots.title]) || ((_context$value$slots3 = context.value.slots) === null || _context$value$slots3 === void 0 ? void 0 : _context$value$slots3.title) || props.title;
      var _context$value4 = context.value,
          prefixCls = _context$value4.prefixCls,
          showIcon = _context$value4.showIcon,
          treeIcon = _context$value4.icon,
          draggable = _context$value4.draggable,
          loadData = _context$value4.loadData,
          contextSlots = _context$value4.slots;
      var disabled = isDisabled.value;
      var mergedDraggable = typeof draggable === 'function' ? draggable(data) : draggable;
      var wrapClass = "".concat(prefixCls, "-node-content-wrapper"); // Icon - Still show loading icon when loading without showIcon

      var $icon;

      if (showIcon) {
        var _context$value$slots4, _data$slots;

        var currentIcon = icon || ((_context$value$slots4 = context.value.slots) === null || _context$value$slots4 === void 0 ? void 0 : _context$value$slots4[data === null || data === void 0 ? void 0 : (_data$slots = data.slots) === null || _data$slots === void 0 ? void 0 : _data$slots.icon]) || treeIcon;
        $icon = currentIcon ? _createVNode("span", {
          "class": classNames("".concat(prefixCls, "-iconEle"), "".concat(prefixCls, "-icon__customize"))
        }, [typeof currentIcon === 'function' ? currentIcon(renderArgsData.value) : currentIcon]) : renderIcon();
      } else if (loadData && loading) {
        $icon = renderIcon();
      } // Title


      var titleNode;

      if (typeof title === 'function') {
        titleNode = title(renderArgsData.value);
      } else if (contextSlots.valuetitleRender) {
        titleNode = contextSlots.valuetitleRender(renderArgsData.value);
      } else {
        titleNode = title;
      }

      titleNode = titleNode === undefined ? defaultTitle : titleNode;

      var $title = _createVNode("span", {
        "class": "".concat(prefixCls, "-title")
      }, [titleNode]);

      return _createVNode("span", {
        "ref": selectHandle,
        "title": typeof title === 'string' ? title : '',
        "class": classNames("".concat(wrapClass), "".concat(wrapClass, "-").concat(nodeState.value || 'normal'), !disabled && (selected || dragNodeHighlight.value) && "".concat(prefixCls, "-node-selected"), !disabled && mergedDraggable && 'draggable'),
        "draggable": !disabled && mergedDraggable || undefined,
        "aria-grabbed": !disabled && mergedDraggable || undefined,
        "onMouseenter": onMouseEnter,
        "onMouseleave": onMouseLeave,
        "onContextmenu": onContextmenu,
        "onClick": onSelectorClick,
        "onDblclick": onSelectorDoubleClick,
        "onDragstart": mergedDraggable ? onDragStart : undefined
      }, [$icon, $title, renderDropIndicator()]);
    };

    return function () {
      var _classNames;

      var _props$attrs = _objectSpread(_objectSpread({}, props), attrs),
          eventKey = _props$attrs.eventKey,
          dragOver = _props$attrs.dragOver,
          dragOverGapTop = _props$attrs.dragOverGapTop,
          dragOverGapBottom = _props$attrs.dragOverGapBottom,
          isLeaf = _props$attrs.isLeaf,
          isStart = _props$attrs.isStart,
          isEnd = _props$attrs.isEnd,
          expanded = _props$attrs.expanded,
          selected = _props$attrs.selected,
          checked = _props$attrs.checked,
          halfChecked = _props$attrs.halfChecked,
          loading = _props$attrs.loading,
          domRef = _props$attrs.domRef,
          active = _props$attrs.active,
          data = _props$attrs.data,
          onMousemove = _props$attrs.onMousemove,
          otherProps = _objectWithoutProperties(_props$attrs, _excluded);

      var _context$value5 = context.value,
          prefixCls = _context$value5.prefixCls,
          filterTreeNode = _context$value5.filterTreeNode,
          draggable = _context$value5.draggable,
          keyEntities = _context$value5.keyEntities,
          dropContainerKey = _context$value5.dropContainerKey,
          dropTargetKey = _context$value5.dropTargetKey;
      var disabled = isDisabled.value;
      var dataOrAriaAttributeProps = getDataAndAria(otherProps);

      var _ref3 = keyEntities[eventKey] || {},
          level = _ref3.level;

      var isEndNode = isEnd[isEnd.length - 1];
      var mergedDraggable = typeof draggable === 'function' ? draggable(data) : draggable;
      return _createVNode("div", _objectSpread({
        "ref": domRef,
        "class": classNames(attrs.class, "".concat(prefixCls, "-treenode"), (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-treenode-disabled"), disabled), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-switcher-").concat(expanded ? 'open' : 'close'), !isLeaf), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-checkbox-checked"), checked), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-checkbox-indeterminate"), halfChecked), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-selected"), selected), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-loading"), loading), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-active"), active), _defineProperty(_classNames, "".concat(prefixCls, "-treenode-leaf-last"), isEndNode), _defineProperty(_classNames, 'drop-target', dropTargetKey === eventKey), _defineProperty(_classNames, 'drop-container', dropContainerKey === eventKey), _defineProperty(_classNames, 'drag-over', !disabled && dragOver), _defineProperty(_classNames, 'drag-over-gap-top', !disabled && dragOverGapTop), _defineProperty(_classNames, 'drag-over-gap-bottom', !disabled && dragOverGapBottom), _defineProperty(_classNames, 'filter-node', filterTreeNode && filterTreeNode(eventData.value)), _classNames)),
        "style": attrs.style,
        "onDragenter": mergedDraggable ? onDragEnter : undefined,
        "onDragover": mergedDraggable ? onDragOver : undefined,
        "onDragleave": mergedDraggable ? onDragLeave : undefined,
        "onDrop": mergedDraggable ? onDrop : undefined,
        "onDragend": mergedDraggable ? onDragEnd : undefined,
        "onMousemove": onMousemove
      }, dataOrAriaAttributeProps), [_createVNode(Indent, {
        "prefixCls": prefixCls,
        "level": level,
        "isStart": isStart,
        "isEnd": isEnd
      }, null), renderSwitcher(), renderCheckbox(), renderSelector()]);
    };
  }
});