<script setup>
import { computed, inject } from "vue";
import { useNamespace } from "@yh-ui/hooks";
import { TREE_INJECTION_KEY } from "./tree";
import { YhIcon } from "../../icon";
import { YhCheckbox } from "../../checkbox";
defineOptions({ name: "YhTreeNode" });
const props = defineProps({
  node: { type: Object, required: true }
});
const ns = useNamespace("tree");
const tree = inject(TREE_INJECTION_KEY);
const nodeStyle = computed(() => ({
  paddingLeft: `${props.node.level * tree.props.indent}px`
}));
const isCurrent = computed(() => tree.currentNodeKey.value === props.node.key);
const nodeClass = computed(() => [
  ns.e("node"),
  props.node.class,
  // 支持自定义类名
  {
    [ns.is("expanded")]: props.node.expanded,
    [ns.is("current")]: isCurrent.value && tree.props.highlightCurrent,
    [ns.is("disabled")]: props.node.disabled,
    [ns.is("checked")]: props.node.checked,
    [ns.is("leaf")]: props.node.isLeaf || !props.node.children?.length,
    [ns.is("dragging")]: tree.draggingNodeKey.value === props.node.key,
    [ns.is("drop-inner")]: tree.dropTargetNodeKey.value === props.node.key && tree.dropPosition.value === "inner",
    [ns.is("drop-before")]: tree.dropTargetNodeKey.value === props.node.key && tree.dropPosition.value === "before",
    [ns.is("drop-after")]: tree.dropTargetNodeKey.value === props.node.key && tree.dropPosition.value === "after"
  }
]);
const handleDragStart = (e) => {
  if (!tree.props.draggable || props.node.disabled) return;
  tree.handleDragStart(props.node, e);
};
const handleDragOver = (e) => {
  if (!tree.props.draggable) return;
  e.preventDefault();
  tree.handleDragOver(props.node, e);
};
const handleDragEnter = (e) => {
  if (!tree.props.draggable) return;
  e.preventDefault();
  tree.handleDragEnter(props.node, e);
};
const handleDragLeave = (e) => {
  if (!tree.props.draggable) return;
  tree.handleDragLeave(props.node, e);
};
const handleDragEnd = (e) => {
  if (!tree.props.draggable) return;
  tree.handleDragEnd(props.node, e);
};
const handleDrop = (e) => {
  if (!tree.props.draggable) return;
  e.preventDefault();
  tree.handleDrop(props.node, e);
};
const handleExpandClick = (e) => {
  e.stopPropagation();
  tree.handleNodeExpand(props.node);
};
const handleContentClick = (e) => {
  tree.handleNodeClick(props.node, e);
};
const handleCheckChange = (checked) => {
  tree.handleNodeCheck(props.node, Boolean(checked));
};
defineSlots();
</script>

<template>
  <div v-show="node.visible" :class="nodeClass" role="treeitem">
    <div
      :class="ns.e('content')"
      :style="nodeStyle"
      :draggable="tree.props.draggable && !node.disabled"
      @click="handleContentClick"
      @dragstart="handleDragStart"
      @dragover="handleDragOver"
      @dragenter="handleDragEnter"
      @dragleave="handleDragLeave"
      @dragend="handleDragEnd"
      @drop="handleDrop"
    >
      <!-- 展开图标 -->
      <span
        :class="[ns.e('expand-icon'), {
  [ns.is('expanded')]: node.expanded,
  [ns.is('loading')]: node.loading
}]"
        @click="handleExpandClick"
      >
        <slot name="icon" :node="node" :data="node.rawData">
          <template v-if="node.loading">
            <svg class="loading-icon" viewBox="0 0 1024 1024" width="14" height="14">
              <path
                d="M512 1024c-282.77 0-512-229.23-512-512s229.23-512 512-512c28.28 0 51.2 22.92 51.2 51.2s-22.92 51.2-51.2 51.2c-226.28 0-409.6 183.32-409.6 409.6s183.32 409.6 409.6 409.6 409.6-183.32 409.6-409.6c0-28.28 22.92-51.2 51.2-51.2s51.2 22.92 51.2 51.2c0 282.77-229.23 512-512 512z"
                fill="currentColor"
              ></path>
            </svg>
          </template>
          <template v-else-if="!node.isLeaf && (node.children?.length || tree.props.lazy)">
            <svg v-if="node.expanded" viewBox="0 0 1024 1024" width="12" height="12">
              <path d="M192 384l320 320 320-320z" fill="currentColor"></path>
            </svg>
            <svg v-else viewBox="0 0 1024 1024" width="12" height="12">
              <path d="M384 192l320 320-320 320z" fill="currentColor"></path>
            </svg>
          </template>
          <template v-else>
            <span :class="ns.e('expand-placeholder')"></span>
          </template>
        </slot>
      </span>

      <!-- 左侧复选框 -->
      <yh-checkbox
        v-if="tree.props.showCheckbox && tree.props.checkboxPosition === 'left'"
        :model-value="node.checked"
        :indeterminate="node.indeterminate"
        :disabled="node.disabled"
        @update:model-value="handleCheckChange"
        @click.stop
      />

      <!-- 前缀插槽 -->
      <slot name="prefix" :node="node" :data="node.rawData" />

      <!-- 快捷图标 (通过 rawData.icon 渲染) -->
      <yh-icon v-if="node.icon" :name="node.icon" :class="ns.e('icon')" />

      <!-- 节点内容 -->
      <span :class="ns.e('label')">
        <slot name="default" :node="node" :data="node.rawData">
          {{ node.label }}
        </slot>
      </span>

      <!-- 后缀插槽 -->
      <slot name="suffix" :node="node" :data="node.rawData" />

      <!-- 右侧复选框 -->
      <yh-checkbox
        v-if="tree.props.showCheckbox && tree.props.checkboxPosition === 'right'"
        :model-value="node.checked"
        :indeterminate="node.indeterminate"
        :disabled="node.disabled"
        @update:model-value="handleCheckChange"
        @click.stop
      />
    </div>

    <!-- 子节点 (非虚拟滚动模式下递归渲染) -->
    <div
      v-if="!tree.props.virtual && node.children && node.children.length > 0"
      v-show="node.expanded"
      :class="ns.e('children')"
      role="group"
    >
      <yh-tree-node v-for="child in node.children" :key="child.key" :node="child">
        <template #default="{ node: childNode, data: childData }">
          <slot name="default" :node="childNode" :data="childData" />
        </template>
        <template #icon="{ node: childNode, data: childData }">
          <slot name="icon" :node="childNode" :data="childData" />
        </template>
        <template #prefix="{ node: childNode, data: childData }">
          <slot name="prefix" :node="childNode" :data="childData" />
        </template>
        <template #suffix="{ node: childNode, data: childData }">
          <slot name="suffix" :node="childNode" :data="childData" />
        </template>
      </yh-tree-node>
    </div>
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-tree {
  --yh-tree-node-height: var(--yh-tree-node-height, 28px);
  --yh-tree-text-color: var(--yh-tree-label-text-color, var(--yh-text-color-primary, #1d1d1f));
  --yh-tree-hover-bg: var(--yh-tree-node-hover-bg-color, var(--yh-color-primary-light-9, #ecf5ff));
  --yh-tree-current-bg: var(
    --yh-tree-node-selected-bg-color,
    var(--yh-color-primary-light-8, #d9ecff)
  );
}
html.dark .yh-tree {
  --yh-tree-hover-bg: var(--yh-tree-node-hover-bg-color, rgba(255, 255, 255, 0.06));
  --yh-tree-current-bg: var(--yh-tree-node-selected-bg-color, rgba(255, 255, 255, 0.12));
}
.yh-tree {
  font-size: 14px;
  color: var(--yh-tree-text-color);
  user-select: none;
}
.yh-tree__node {
  position: relative;
}
.yh-tree__node.is-disabled .yh-tree__label {
  color: var(--yh-text-color-disabled, #c0c4cc);
  cursor: not-allowed;
}

.yh-tree__node.is-dragging {
  opacity: 0.5;
}

.yh-tree__node.is-drop-inner {
  background-color: var(--yh-color-primary-light-9, #ecf5ff);
}
.yh-tree__node.is-drop-inner .yh-tree__content {
  background-color: var(--yh-color-primary-light-8, #d9ecff);
}

.yh-tree__node.is-drop-before::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background-color: var(--yh-color-primary, #409eff);
  z-index: 10;
}

.yh-tree__node.is-drop-after::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background-color: var(--yh-color-primary, #409eff);
  z-index: 10;
}

.yh-tree__content {
  display: flex;
  align-items: center;
  height: var(--yh-tree-node-height);
  padding-right: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s ease, color 0.2s ease;
}
.yh-tree__content:hover {
  background-color: var(--yh-tree-hover-bg);
}
.yh-tree__node.is-current > .yh-tree__content {
  background-color: var(--yh-tree-current-bg);
  color: var(--yh-color-primary, #409eff);
  font-weight: 500;
}

.yh-tree__expand-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  flex-shrink: 0;
  color: var(--yh-text-color-placeholder, #c0c4cc);
  cursor: pointer;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), color 0.3s ease;
}
.yh-tree__expand-icon:hover {
  color: var(--yh-color-primary, #409eff);
}
.yh-tree__expand-icon.is-expanded {
  color: var(--yh-text-color-secondary, #86868b);
}

.yh-tree__expand-icon.is-loading {
  animation: yh-tree-rotate 1s linear infinite;
  color: var(--yh-color-primary, #409eff) !important;
}

.yh-tree__expand-icon svg {
  transition: fill 0.3s ease;
}

.yh-tree__expand-placeholder {
  display: inline-block;
  width: 24px;
}

.yh-tree__label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: var(--yh-tree-node-height);
}

.yh-tree__icon {
  margin-right: 4px;
  color: var(--yh-text-color-secondary);
}

.yh-tree__empty {
  padding: 20px;
  text-align: center;
  color: var(--yh-text-color-secondary);
  font-size: 13px;
}

.yh-tree--show-line .yh-tree__node {
  position: relative;
}
.yh-tree--show-line .yh-tree__node::before {
  content: "";
  position: absolute;
  left: 11px;
  top: 0;
  height: 100%;
  width: 1px;
  background-color: var(--yh-border-color-light, #dcdfe6);
}
.yh-tree--show-line .yh-tree__node:last-child::before {
  height: 14px;
}
.yh-tree--show-line .yh-tree__content::before {
  content: "";
  position: absolute;
  left: 11px;
  top: 14px;
  width: 12px;
  height: 1px;
  background-color: var(--yh-border-color-light, #dcdfe6);
}
.yh-tree--show-line > .yh-tree__node::before {
  display: none;
}
.yh-tree--show-line > .yh-tree__node > .yh-tree__content::before {
  display: none;
}

.yh-tree .yh-checkbox {
  margin-right: 8px;
}

@keyframes yh-tree-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
