<script setup>
import { computed, ref, watch, defineComponent, h } from "vue";
import { useNamespace, useLocale } from "@yh-ui/hooks";
defineOptions({
  name: "YhCascaderPanel"
});
const props = defineProps({
  options: { type: Array, required: false, default: () => [] },
  expandedPath: { type: Array, required: true, default: () => [] },
  config: { type: Object, required: true },
  isMultiple: { type: Boolean, required: true, default: false },
  isChecked: { type: Function, required: true },
  virtual: { type: Boolean, required: false, default: false },
  itemHeight: { type: Number, required: false, default: 34 }
});
const emit = defineEmits(["expand", "check"]);
const ns = useNamespace("cascader");
const { t } = useLocale();
const CascaderMenu = defineComponent({
  name: "CascaderMenu",
  props: {
    menu: { type: Array, required: true },
    level: { type: Number, required: true },
    virtual: Boolean,
    itemHeight: { type: Number, default: 34 }
  },
  setup(menuProps, { slots }) {
    const scrollTop = ref(0);
    const visibleInfo = computed(() => {
      if (!menuProps.virtual) return { options: menuProps.menu, startIndex: 0 };
      const containerHeight = 274;
      const visibleCount = Math.ceil(containerHeight / menuProps.itemHeight) + 2;
      const st = scrollTop.value;
      const maxStartIndex = Math.max(0, menuProps.menu.length - visibleCount);
      const startIndex = Math.min(
        Math.max(0, Math.floor(st / menuProps.itemHeight) - 1),
        maxStartIndex
      );
      return {
        options: menuProps.menu.slice(startIndex, startIndex + visibleCount + 2),
        startIndex
      };
    });
    const handleScroll = (e) => {
      scrollTop.value = e.target.scrollTop;
    };
    watch(
      () => menuProps.menu,
      () => {
        scrollTop.value = 0;
      }
    );
    return () => h(
      "div",
      {
        class: [ns.e("menu"), menuProps.virtual && ns.is("virtual")],
        onScroll: handleScroll
      },
      [
        menuProps.virtual ? h(
          "div",
          {
            style: {
              height: `${menuProps.menu.length * menuProps.itemHeight}px`,
              position: "relative"
            }
          },
          visibleInfo.value.options.map((option, idx) => {
            return slots.default?.({
              option,
              level: menuProps.level,
              startIndex: visibleInfo.value.startIndex,
              idx
            });
          })
        ) : menuProps.menu.map(
          (option) => slots.default?.({
            option,
            level: menuProps.level
          })
        ),
        // 空状态处理
        menuProps.menu.length === 0 ? h("div", { class: ns.e("empty") }, t("cascader.noData")) : null
      ]
    );
  }
});
const menus = computed(() => {
  const result = [props.options || []];
  let currentOptions = props.options || [];
  for (const value of props.expandedPath) {
    const option = currentOptions.find((o) => o[props.config.value] === value);
    const children = option ? option[props.config.children] : void 0;
    if (option && children && children.length) {
      result.push(children);
      currentOptions = children;
    } else {
      break;
    }
  }
  return result;
});
const isExpanded = (option, level) => props.expandedPath[level] === option[props.config.value];
const hasChildren = (option) => {
  const children = option[props.config.children];
  return !!(children && children.length > 0);
};
const isLeaf = (option) => {
  const leaf = option[props.config.leaf];
  if (leaf !== void 0) return leaf;
  return !hasChildren(option);
};
const isSelectable = (option) => props.config.checkStrictly ? true : isLeaf(option);
const getPath = (option, level) => [
  ...props.expandedPath.slice(0, level),
  option[props.config.value]
];
const handleCheckboxClick = (option, level, event) => {
  event.stopPropagation();
  if (option[props.config.disabled] || !isSelectable(option)) return;
  emit("check", option, getPath(option, level));
};
const handleClick = (option, level, event) => {
  event.stopPropagation();
  if (option[props.config.disabled]) return;
  const path = getPath(option, level);
  if (hasChildren(option)) emit("expand", option, level);
  if (!props.isMultiple && isSelectable(option)) {
    emit("check", option, path);
  } else if (props.isMultiple && props.config.checkStrictly && !hasChildren(option)) {
    emit("check", option, path);
  }
};
const handleMouseEnter = (option, level) => {
  if (props.config.expandTrigger !== "hover" || option[props.config.disabled]) return;
  if (hasChildren(option)) emit("expand", option, level);
};
</script>

<template>
  <div :class="ns.e('panel')">
    <CascaderMenu
      v-for="(colMenu, colLevel) in menus"
      :key="colLevel"
      :menu="colMenu"
      :level="colLevel"
      :virtual="virtual"
      :item-height="itemHeight"
    >
      <template #default="{ option, level: menuLevel, startIndex, idx }">
        <div
          :key="option[config.value]"
          :class="[ns.e('node'), ns.is('expanded', isExpanded(option, menuLevel)), ns.is('checked', isChecked(getPath(option, menuLevel))), ns.is('disabled', option[config.disabled]), ns.is('selectable', isSelectable(option))]"
          :style="virtual ? {
  position: 'absolute',
  top: `${(startIndex + idx) * itemHeight}px`,
  left: 0,
  right: 0,
  height: `${itemHeight}px`
} : {}"
          @mousedown.prevent
          @click="handleClick(option, menuLevel, $event)"
          @mouseenter="handleMouseEnter(option, menuLevel)"
        >
          <!-- 多选复选框 -->
          <span
            v-if="isMultiple && isSelectable(option)"
            :class="ns.e('checkbox')"
            @click.stop="handleCheckboxClick(option, menuLevel, $event)"
          >
            <span
              :class="[ns.e('checkbox-inner'), ns.is('checked', isChecked(getPath(option, menuLevel)))]"
            >
              <svg
                v-if="isChecked(getPath(option, menuLevel))"
                viewBox="0 0 1024 1024"
                width="1em"
                height="1em"
              >
                <path
                  fill="currentColor"
                  d="M406.656 706.944L195.84 496.256a32 32 0 1 0-45.248 45.248l256 256 512-512a32 32 0 0 0-45.248-45.248L406.592 706.944z"
                />
              </svg>
            </span>
          </span>

          <!-- 标签内容 -->
          <span :class="ns.e('label')">
            <slot :node="option" :data="option">{{ option[config.label] }}</slot>
          </span>

          <!-- 展开图标 -->
          <span v-if="hasChildren(option)" :class="ns.e('expand-icon')">
            <svg viewBox="0 0 1024 1024" width="1em" height="1em">
              <path
                fill="currentColor"
                d="M340.864 149.312a30.592 30.592 0 0 0 0 42.752L652.736 512 340.864 831.872a30.592 30.592 0 0 0 0 42.752 29.12 29.12 0 0 0 41.728 0L714.24 534.336a32 32 0 0 0 0-44.672L382.592 149.376a29.12 29.12 0 0 0-41.728 0z"
              />
            </svg>
          </span>
        </div>
      </template>
    </CascaderMenu>
  </div>
</template>

<style>
@charset "UTF-8";
/**
 * YH-UI Sass Variables
 * 原具体的 CSS 变量输出规则 (:root, html.dark 等) 已移至 root.scss，以防止各组件样式编译时产生重复的全局变量 CSS 冗余。
 */
.yh-cascader {
  --yh-cascader-height: 32px;
  --yh-cascader-height-large: 40px;
  --yh-cascader-height-small: 24px;
  --yh-cascader-bg-color: var(--yh-fill-color-blank, #fff);
  --yh-cascader-border-color: var(--yh-border-color, #dcdfe6);
  --yh-cascader-border-color-hover: var(--yh-border-color-hover, #c0c4cc);
  --yh-cascader-border-color-focus: var(--yh-color-primary, #409eff);
  --yh-cascader-border-radius: var(--yh-border-radius-base, 4px);
  --yh-cascader-text-color: var(--yh-text-color-regular, #606266);
  --yh-cascader-placeholder-color: var(--yh-text-color-placeholder, #a8abb2);
  --yh-cascader-disabled-bg-color: var(--yh-fill-color-light, #f5f7fa);
  --yh-cascader-disabled-text-color: var(--yh-text-color-placeholder, #a8abb2);
  --yh-cascader-node-height: 34px;
  --yh-cascader-node-bg-color-hover: var(--yh-fill-color-light, #f5f7fa);
  --yh-cascader-node-text-color-hover: var(--yh-text-color-regular, #606266);
  --yh-cascader-node-bg-color-active: var(--yh-fill-color-light, #f5f7fa);
  --yh-cascader-node-text-color-active: var(--yh-color-primary, #409eff);
  --yh-cascader-dropdown-bg-color: var(--yh-bg-color-overlay, #fff);
  --yh-cascader-dropdown-border-color: var(--yh-border-color-light, #e4e7ed);
  --yh-cascader-dropdown-shadow: var(--yh-box-shadow-light, 0 2px 12px 0 rgba(0, 0, 0, 0.1));
  --yh-cascader-menu-min-width: 180px;
  --yh-cascader-menu-max-height: 274px;
  --yh-cascader-menu-border-color: var(--yh-border-color-light, #e4e7ed);
  position: relative;
  display: inline-flex;
  width: 100%;
  font-size: 14px;
  cursor: pointer;
}
.yh-cascader__wrapper {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
  position: relative;
  width: 100%;
  min-height: var(--yh-cascader-height);
  padding: 2px 30px 2px 11px;
  background-color: var(--yh-cascader-bg-color);
  border: 1px solid var(--yh-cascader-border-color);
  border-radius: var(--yh-cascader-border-radius);
  box-sizing: border-box;
  transition: border-color 0.2s;
}
.yh-cascader__wrapper:hover {
  border-color: var(--yh-cascader-border-color-hover);
}

.yh-cascader__inner {
  flex: 1;
  min-width: 50px;
  height: calc(var(--yh-cascader-height) - 6px);
  padding: 0;
  color: var(--yh-cascader-text-color);
  font-size: inherit;
  line-height: calc(var(--yh-cascader-height) - 6px);
  background: transparent;
  border: none;
  outline: none;
  cursor: pointer;
}
.yh-cascader__inner::placeholder {
  color: var(--yh-cascader-placeholder-color);
}
.yh-cascader__inner:disabled {
  cursor: not-allowed;
}

.yh-cascader__selected-value {
  position: absolute;
  left: 11px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--yh-cascader-text-color);
  pointer-events: none;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: calc(100% - 50px);
}

.yh-cascader__suffix {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: inline-flex;
  align-items: center;
  gap: 4px;
  color: var(--yh-cascader-placeholder-color);
}

.yh-cascader__icon {
  width: 14px;
  height: 14px;
  line-height: 1;
}

.yh-cascader__clear {
  cursor: pointer;
  transition: color 0.2s;
}
.yh-cascader__clear:hover {
  color: var(--yh-text-color-secondary, #909399);
}

.yh-cascader__arrow {
  transition: transform 0.3s;
}
.yh-cascader__arrow.is-reverse {
  transform: rotate(180deg);
}

.yh-cascader__tag {
  display: inline-flex;
  align-items: center;
  max-width: 100%;
  height: 22px;
  padding: 0 8px;
  font-size: 12px;
  color: var(--yh-text-color-regular, #606266);
  background-color: var(--yh-fill-color, #f0f2f5);
  border-radius: var(--yh-border-radius-small, 2px);
}

.yh-cascader__tag-text {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.yh-cascader__tag-close {
  display: inline-flex;
  align-items: center;
  margin-left: 4px;
  cursor: pointer;
  transition: color 0.2s;
}
.yh-cascader__tag-close:hover {
  color: var(--yh-color-danger, #f56c6c);
}
.yh-cascader__tag-close svg {
  width: 12px;
  height: 12px;
}

.yh-cascader__dropdown {
  --yh-cascader-dropdown-bg-color: var(--yh-bg-color-overlay, #fff);
  --yh-cascader-dropdown-border-color: var(--yh-border-color-light, #e4e7ed);
  --yh-cascader-dropdown-shadow: var(--yh-box-shadow-light, 0 2px 12px 0 rgba(0, 0, 0, 0.1));
  --yh-cascader-border-radius: var(--yh-border-radius-base, 4px);
  --yh-cascader-menu-border-color: var(--yh-border-color-light, #e4e7ed);
  --yh-cascader-text-color: var(--yh-text-color-regular, #606266);
  --yh-cascader-node-height: 34px;
  --yh-cascader-node-bg-color-hover: var(--yh-fill-color-light, #f5f7fa);
  --yh-cascader-node-text-color-active: var(--yh-color-primary, #409eff);
  --yh-cascader-menu-min-width: 180px;
  --yh-cascader-menu-max-height: 274px;
  position: absolute;
  z-index: 2000;
  margin-top: 4px;
  background-color: var(--yh-cascader-dropdown-bg-color, #fff);
  border: 1px solid var(--yh-cascader-dropdown-border-color, #e4e7ed);
  border-radius: var(--yh-border-radius-base, 4px);
  box-shadow: var(--yh-cascader-dropdown-shadow, 0 2px 12px 0 rgba(0, 0, 0, 0.1));
}

.yh-cascader__panel {
  display: flex;
  background-color: var(--yh-cascader-dropdown-bg-color, #fff);
  border-radius: var(--yh-cascader-border-radius, 4px);
  overflow: hidden;
}

.yh-cascader__menu {
  min-width: var(--yh-cascader-menu-min-width);
  max-height: var(--yh-cascader-menu-max-height);
  padding: 6px 0;
  overflow-y: auto;
  border-right: 1px solid var(--yh-cascader-menu-border-color);
}
.yh-cascader__menu:last-child {
  border-right: none;
}

.yh-cascader__node {
  display: flex;
  align-items: center;
  padding: 0 30px 0 20px;
  height: var(--yh-cascader-node-height);
  line-height: var(--yh-cascader-node-height);
  font-size: 14px;
  color: var(--yh-cascader-text-color);
  cursor: pointer;
  position: relative;
}
.yh-cascader__node:hover {
  background-color: var(--yh-cascader-node-bg-color-hover);
  color: var(--yh-cascader-node-text-color-hover);
}
.yh-cascader__node.is-expanded {
  background-color: var(--yh-cascader-node-bg-color-active);
  color: var(--yh-cascader-node-text-color-active);
}
.yh-cascader__node.is-checked {
  color: var(--yh-color-primary, #409eff);
  background-color: var(--yh-color-primary-light-9, #ecf5ff);
  font-weight: 600;
}
.yh-cascader__node.is-checked.is-expanded {
  background-color: var(--yh-color-primary-light-9, #ecf5ff);
}
.yh-cascader__node.is-disabled {
  color: var(--yh-cascader-disabled-text-color);
  cursor: not-allowed;
}
.yh-cascader__node.is-disabled:hover {
  background-color: transparent;
}

.yh-cascader__checkbox {
  margin-right: 8px;
}

.yh-cascader__checkbox-inner {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 14px;
  height: 14px;
  border: 1px solid var(--yh-border-color, #dcdfe6);
  border-radius: 2px;
  background-color: var(--yh-bg-color, #fff);
  transition: all 0.2s;
}
.yh-cascader__checkbox-inner.is-checked {
  background-color: var(--yh-color-primary, #409eff);
  border-color: var(--yh-color-primary, #409eff);
}
.yh-cascader__checkbox-inner svg {
  width: 10px;
  height: 10px;
  color: #fff;
}

.yh-cascader__label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.yh-cascader__expand-icon {
  position: absolute;
  right: 10px;
  color: var(--yh-cascader-placeholder-color);
}
.yh-cascader__expand-icon svg {
  width: 12px;
  height: 12px;
}

.yh-cascader__suggestions {
  max-height: var(--yh-cascader-menu-max-height);
  padding: 6px 0;
  overflow-y: auto;
}

.yh-cascader__suggestion {
  padding: 0 20px;
  height: var(--yh-cascader-node-height);
  line-height: var(--yh-cascader-node-height);
  font-size: 14px;
  color: var(--yh-cascader-text-color);
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.yh-cascader__suggestion:hover {
  background-color: var(--yh-cascader-node-bg-color-hover);
}
.yh-cascader__suggestion.is-checked {
  color: var(--yh-color-primary, #409eff);
  background-color: var(--yh-color-primary-light-9, #ecf5ff);
  font-weight: 600;
}

.yh-cascader__empty {
  padding: 10px 0;
  text-align: center;
  color: var(--yh-text-color-secondary, #909399);
  font-size: 14px;
}

.yh-cascader.is-focused .yh-cascader__wrapper {
  border-color: var(--yh-cascader-border-color-focus);
}

.yh-cascader.is-disabled {
  cursor: not-allowed;
}
.yh-cascader.is-disabled .yh-cascader__wrapper {
  background-color: var(--yh-cascader-disabled-bg-color);
  border-color: var(--yh-cascader-dropdown-border-color);
  cursor: not-allowed;
}

.yh-cascader.is-disabled .yh-cascader__inner {
  color: var(--yh-cascader-disabled-text-color);
}

.yh-cascader--large {
  font-size: 14px;
}
.yh-cascader--large .yh-cascader__wrapper {
  min-height: var(--yh-cascader-height-large);
}

.yh-cascader--large .yh-cascader__inner {
  height: calc(var(--yh-cascader-height-large) - 6px);
  line-height: calc(var(--yh-cascader-height-large) - 6px);
}

.yh-cascader--large .yh-cascader__tag {
  height: 26px;
}

.yh-cascader--small {
  font-size: 12px;
}
.yh-cascader--small .yh-cascader__wrapper {
  min-height: var(--yh-cascader-height-small);
}

.yh-cascader--small .yh-cascader__inner {
  height: calc(var(--yh-cascader-height-small) - 6px);
  line-height: calc(var(--yh-cascader-height-small) - 6px);
}

.yh-cascader--small .yh-cascader__tag {
  height: 18px;
  font-size: 10px;
}

.yh-cascader-dropdown-enter-active,
.yh-cascader-dropdown-leave-active {
  transition: opacity 0.2s, transform 0.2s;
}

.yh-cascader-dropdown-enter-from,
.yh-cascader-dropdown-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
