<script setup lang="ts">
import type { VNode } from 'vue';
import { computed, ref, watch } from 'vue';
import { ElTree } from 'element-plus';
import { objectContextDomainConfigs } from '@/constants/object-context';
import { useRouteStore } from '@/store/modules/route';

interface Props {
  modelValue: boolean;
  /** 已选菜单 key */
  initialSelected: string[];
}
const props = defineProps<Props>();
const emit = defineEmits<{
  (e: 'update:modelValue', v: boolean): void;
  (e: 'confirm', keys: string[]): void;
}>();

const routeStore = useRouteStore();

interface TreeNode {
  key: string;
  label: string;
  /** routeStore.menus 同源的 SvgIconVNode */
  icon?: VNode;
  children?: TreeNode[];
  isLeaf: boolean;
}

// 对象域入口（project_list / product_list）在 picker 视角下当顶级叶子，
// 它们的 children 是"进入某个对象后"的上下文页，不属于通用菜单。
const OBJECT_DOMAIN_ENTRY_KEYS = new Set(objectContextDomainConfigs.map(c => c.entryRouteKey));

function toTreeNodes(menus: any[]): TreeNode[] {
  return menus.map(m => {
    const isDomainEntry = OBJECT_DOMAIN_ENTRY_KEYS.has(m.key);
    const hasChildren = !isDomainEntry && m.children && m.children.length > 0;
    return {
      key: m.key,
      label: m.label as string,
      icon: m.icon,
      isLeaf: !hasChildren,
      children: hasChildren ? toTreeNodes(m.children) : undefined
    };
  });
}

const treeData = computed(() => toTreeNodes(routeStore.menus));
const treeRef = ref<InstanceType<typeof ElTree> | null>(null);

const checkedKeys = ref<string[]>([...props.initialSelected]);

watch(
  () => props.modelValue,
  open => {
    if (open) {
      checkedKeys.value = [...props.initialSelected];
      // 等抽屉 transition 后设置 checked
      setTimeout(() => treeRef.value?.setCheckedKeys(props.initialSelected, false), 100);
    }
  }
);

function handleConfirm() {
  // 父子联动后只取叶子节点（含对象域入口，因为它们 isLeaf=true）
  const allChecked = treeRef.value?.getCheckedKeys(true) ?? [];
  emit(
    'confirm',
    allChecked.map(k => String(k))
  );
  emit('update:modelValue', false);
}
</script>

<template>
  <ElDrawer
    :model-value="modelValue"
    direction="rtl"
    size="380px"
    title="选择快捷入口菜单"
    append-to-body
    @update:model-value="emit('update:modelValue', $event)"
  >
    <template #default>
      <p class="hint">勾选要加入快捷入口的菜单，勾父级会自动选中其所有子菜单。</p>
      <ElTree
        ref="treeRef"
        :data="treeData"
        node-key="key"
        :props="{ label: 'label', children: 'children' }"
        show-checkbox
        default-expand-all
        :check-on-click-node="false"
      >
        <template #default="{ data }">
          <span class="tree-node">
            <ElIcon v-if="data.icon" class="tree-node__icon">
              <component :is="data.icon" />
            </ElIcon>
            <span class="tree-node__label">{{ data.label }}</span>
          </span>
        </template>
      </ElTree>
    </template>
    <template #footer>
      <div class="footer">
        <ElButton @click="emit('update:modelValue', false)">取消</ElButton>
        <ElButton type="primary" @click="handleConfirm">保存</ElButton>
      </div>
    </template>
  </ElDrawer>
</template>

<style scoped>
.hint {
  color: var(--el-text-color-secondary);
  font-size: 13px;
  margin: 0 0 12px;
}
.tree-node {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}
.tree-node__icon {
  color: var(--el-color-primary);
  font-size: 15px;
}
.tree-node__label {
  font-size: 13px;
}
.footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
