<script lang="ts" setup>
/**
 * 表选择与关系设计模态框
 * 步骤1: 选择数据库表
 * 步骤2: 设计表关系
 */
import type { ColumnInfo } from '#/api/core/database-manager';

import { computed, onMounted, ref, watch } from 'vue';

import {
  Check,
  ChevronDown,
  ChevronRight,
  Database,
  Link,
  RefreshCw,
  X,
} from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCheckbox,
  ElDialog,
  ElIcon,
  ElMessage,
  ElOption,
  ElScrollbar,
  ElSelect,
  ElTag,
  ElTooltip,
  ElTree,
} from 'element-plus';

import {
  getDatabaseConfigsApi,
  getDatabasesApi,
  getSchemasApi,
  getTableColumnsApi,
  getTablesApi,
} from '#/api/core/database-manager';
import { DatabaseTreeNodeIcon } from '#/components/database-tree-node-icon';
import { DatabaseTreeNodeLabel } from '#/components/database-tree-node-label';

// 树节点类型
interface TreeNode {
  id: string;
  label: string;
  type: 'connection' | 'database' | 'schema' | 'table';
  isLeaf: boolean;
  meta?: {
    database?: string;
    dbName?: string;
    dbType?: string;
    schema?: string;
    table?: string;
  };
  children?: TreeNode[];
}

// 表字段类型
interface TableField {
  name: string;
  type: string;
  comment: string;
  nullable: boolean;
  isPrimaryKey: boolean;
}

// 选中的表信息
export interface SelectedTableInfo {
  tableName: string;
  dbName: string;
  dbType: string;
  database: string;
  schema?: string;
  fields: TableField[];
}

// 数据库配置信息
export interface DbConfigInfo {
  dbName: string;
  dbType: string;
  database: string;
  schema?: string;
}

// 表关系类型
export interface TableRelation {
  id: string;
  sourceTable: string;
  sourceField: string;
  targetTable: string;
  targetField: string;
  relationType: 'many-to-many' | 'many-to-one' | 'one-to-many' | 'one-to-one';
}

const props = defineProps<{
  dbConfig?: DbConfigInfo;
  selectedTables?: string[];
  tableRelations?: TableRelation[];
  visible: boolean;
}>();

const emit = defineEmits<{
  select: [
    tables: SelectedTableInfo[],
    dbConfig: DbConfigInfo,
    relations: TableRelation[],
  ];
  'update:visible': [value: boolean];
}>();

// 对话框可见性
const dialogVisible = ref(false);

// 当前步骤
const currentStep = ref(0);

// 表折叠状态（步骤2左侧）
const tableExpandedMap = ref<Map<string, boolean>>(new Map());

// 步骤配置
const steps = [
  {
    index: 1,
    get title() {
      return $t('ai-platform.workflow.editor.tableSelectModal.step1');
    },
    icon: Database,
  },
  {
    index: 2,
    get title() {
      return $t('ai-platform.workflow.editor.tableSelectModal.step2');
    },
    icon: Link,
  },
];

// 表关系列表
const relations = ref<TableRelation[]>([]);

// 树相关
const treeData = ref<TreeNode[]>([]);
const loading = ref(false);

// 树配置
const treeProps = {
  label: 'label',
  children: 'children',
  isLeaf: 'isLeaf',
};

// 当前选中的表节点（用于预览）
const selectedTableNode = ref<null | TreeNode>(null);
const previewFields = ref<TableField[]>([]);
const previewLoading = ref(false);

// 已勾选的表（支持多选）
const checkedTables = ref<Map<string, SelectedTableInfo>>(new Map());

// 当前数据库配置
const currentDbConfig = ref<DbConfigInfo | null>(null);

// 已选表数量
const checkedCount = computed(() => checkedTables.value.size);

// 是否可以进入下一步
const canGoNext = computed(() => {
  if (currentStep.value === 0) {
    return checkedCount.value >= 1;
  }
  return true;
});

// 是否可以返回上一步
const canGoPrev = computed(() => currentStep.value > 0);

// 是否是最后一步
const isLastStep = computed(() => currentStep.value === steps.length - 1);

// 获取已选表的信息列表
const selectedTableInfoList = computed(() => {
  return [...checkedTables.value.values()];
});

watch(
  () => props.visible,
  (val) => {
    dialogVisible.value = val;
    if (val) {
      currentStep.value = 0;
      // 初始化已选中的表
      checkedTables.value = new Map();
      if (props.selectedTables && props.selectedTables.length > 0) {
        props.selectedTables.forEach((tableName) => {
          checkedTables.value.set(tableName, {
            tableName,
            dbName: props.dbConfig?.dbName || '',
            dbType: props.dbConfig?.dbType || '',
            database: props.dbConfig?.database || '',
            schema: props.dbConfig?.schema,
            fields: [],
          });
        });
      }
      // 初始化表关系
      relations.value = props.tableRelations ? [...props.tableRelations] : [];
    }
  },
);

watch(dialogVisible, (val) => {
  emit('update:visible', val);
});

function hasSchemaLayer(dbType?: string) {
  const normalized = dbType?.toLowerCase() || '';
  return (
    normalized === 'postgresql' ||
    normalized === 'sqlserver' ||
    normalized === 'oracle'
  );
}

// 加载数据库配置列表
async function loadDatabaseConfigs() {
  loading.value = true;
  try {
    const res = await getDatabaseConfigsApi();
    treeData.value = res.map((config: any) => ({
      id: `conn-${config.db_name}`,
      label: config.display_name || config.name,
      type: 'connection' as const,
      isLeaf: false,
      meta: {
        dbName: config.db_name,
        dbType: config.db_type,
        isSystem: config.is_system,
      },
    }));
  } catch (error) {
    console.error('Failed to load database configs:', error);
  } finally {
    loading.value = false;
  }
}

// 懒加载节点
async function loadNode(node: any, resolve: (data: TreeNode[]) => void) {
  // 根节点
  if (node.level === 0) {
    resolve(treeData.value);
    return;
  }

  const data = node.data as TreeNode;

  switch (data.type) {
    case 'connection': {
      // 加载数据库列表
      try {
        const databases = await getDatabasesApi(data.meta!.dbName!);
        const children: TreeNode[] = databases.map((db: any) => ({
          id: `db-${data.meta!.dbName}-${db.name}`,
          label: db.name,
          type: 'database' as const,
          isLeaf: false,
          meta: {
            ...data.meta,
            database: db.name,
          },
        }));
        resolve(children);
      } catch (error) {
        console.error('Failed to load databases:', error);
        resolve([]);
      }

      break;
    }
    case 'database': {
      try {
        if (hasSchemaLayer(data.meta?.dbType)) {
          const schemas = await getSchemasApi(
            data.meta!.dbName!,
            data.meta!.database!,
          );
          const children: TreeNode[] = schemas.map((schema: any) => ({
            id: `schema-${data.meta!.dbName}-${data.meta!.database}-${schema.name}`,
            label: schema.name,
            type: 'schema' as const,
            isLeaf: false,
            meta: {
              ...data.meta,
              schema: schema.name,
            },
          }));
          resolve(children);
        } else {
          const tables = await getTablesApi(
            data.meta!.dbName!,
            data.meta!.database!,
          );
          const children: TreeNode[] = tables.map((table: any) => ({
            id: `table-${data.meta!.dbName}-${data.meta!.database}-${table.table_name}`,
            label: table.table_name,
            type: 'table' as const,
            isLeaf: true,
            meta: {
              ...data.meta,
              table: table.table_name,
            },
          }));
          resolve(children);
        }
      } catch (error) {
        console.error('Failed to load database children:', error);
        resolve([]);
      }

      break;
    }
    case 'schema': {
      // 加载表列表
      try {
        const tables = await getTablesApi(
          data.meta!.dbName!,
          data.meta!.database!,
          data.meta!.schema!,
        );
        const children: TreeNode[] = tables.map((table: any) => ({
          id: `table-${data.meta!.dbName}-${data.meta!.database}-${data.meta!.schema}-${table.table_name}`,
          label: table.table_name,
          type: 'table' as const,
          isLeaf: true,
          meta: {
            ...data.meta,
            schema: data.meta!.schema || table.schema_name,
            table: table.table_name,
          },
        }));
        resolve(children);
      } catch (error) {
        console.error('Failed to load tables:', error);
        resolve([]);
      }

      break;
    }
    default: {
      resolve([]);
    }
  }
}

// 点击节点
async function handleNodeClick(data: TreeNode) {
  if (data.type === 'table') {
    selectedTableNode.value = data;
    await loadTableColumns(data);
  }
}

// 加载表字段
async function loadTableColumns(node: TreeNode) {
  if (!node.meta?.table) return;

  previewLoading.value = true;
  try {
    const columns = await getTableColumnsApi(
      node.meta.dbName!,
      node.meta.table,
      node.meta.database,
      node.meta.schema,
    );
    previewFields.value = columns.map((col: ColumnInfo) => ({
      name: col.column_name,
      type: col.data_type,
      comment: col.description || '',
      nullable: col.is_nullable,
      isPrimaryKey: col.is_primary_key,
    }));
  } catch (error) {
    console.error('Failed to load columns:', error);
    previewFields.value = [];
  } finally {
    previewLoading.value = false;
  }
}

// 检查表是否已选中
function isTableChecked(tableName?: string) {
  if (!tableName) return false;
  return checkedTables.value.has(tableName);
}

// 切换表选中状态
async function toggleTableCheck(node: TreeNode) {
  const tableName = node.meta?.table;
  if (!tableName) return;

  // 检查是否是同一个数据库/schema
  if (checkedTables.value.size > 0) {
    const firstTable = checkedTables.value.values().next().value;
    if (
      firstTable &&
      (firstTable.dbName !== node.meta.dbName ||
        firstTable.database !== node.meta.database ||
        firstTable.schema !== node.meta.schema)
    ) {
      ElMessage.warning(
        $t('ai-platform.workflow.editor.tableSelectModal.sameDbWarning'),
      );
      return;
    }
  }

  if (checkedTables.value.has(tableName)) {
    checkedTables.value.delete(tableName);
    // 同时移除相关的表关系
    relations.value = relations.value.filter(
      (r) => r.sourceTable !== tableName && r.targetTable !== tableName,
    );
  } else {
    // 获取字段信息
    let fields: TableField[] = [];
    if (
      previewFields.value.length > 0 &&
      selectedTableNode.value?.meta?.table === tableName
    ) {
      fields = [...previewFields.value];
    } else {
      try {
        const columns = await getTableColumnsApi(
          node.meta!.dbName!,
          tableName,
          node.meta!.database,
          node.meta!.schema,
        );
        fields = columns.map((col: ColumnInfo) => ({
          name: col.column_name,
          type: col.data_type,
          comment: col.description || '',
          nullable: col.is_nullable,
          isPrimaryKey: col.is_primary_key,
        }));
      } catch (error) {
        console.error('Failed to load columns:', error);
      }
    }

    checkedTables.value.set(tableName, {
      tableName,
      dbName: node.meta.dbName!,
      dbType: node.meta.dbType || '',
      database: node.meta.database || '',
      schema: node.meta.schema,
      fields,
    });

    // 更新当前数据库配置
    currentDbConfig.value = {
      dbName: node.meta.dbName!,
      dbType: node.meta.dbType || '',
      database: node.meta.database || '',
      schema: node.meta.schema,
    };
  }
}

// 移除已选表
function removeCheckedTable(tableName: string) {
  checkedTables.value.delete(tableName);
  // 同时移除相关的表关系
  relations.value = relations.value.filter(
    (r) => r.sourceTable !== tableName && r.targetTable !== tableName,
  );
}

// 清空所有选中
function clearAllChecked() {
  checkedTables.value.clear();
  currentDbConfig.value = null;
  relations.value = [];
}

// 生成唯一ID
function generateId() {
  return `rel-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
}

// 添加表关系
function addRelation() {
  const tableNames = [...checkedTables.value.keys()];
  if (tableNames.length < 2) {
    ElMessage.warning(
      $t('ai-platform.workflow.editor.tableSelectModal.selectAtLeastTwo'),
    );
    return;
  }
  relations.value.push({
    id: generateId(),
    sourceTable: tableNames[0] || '',
    sourceField: '',
    targetTable: tableNames[1] || '',
    targetField: '',
    relationType: 'many-to-one',
  });
}

// 删除表关系
function removeRelation(id: string) {
  relations.value = relations.value.filter((r) => r.id !== id);
}

// 获取表的字段列表
function getTableFields(tableName: string): TableField[] {
  const tableInfo = checkedTables.value.get(tableName);
  return tableInfo?.fields || [];
}

// 上一步
function handlePrev() {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
}

// 下一步
function handleNext() {
  if (currentStep.value < steps.length - 1) {
    currentStep.value++;
  }
}

// 确认选择
function handleConfirm() {
  if (checkedTables.value.size === 0) {
    ElMessage.warning(
      $t('ai-platform.workflow.editor.tableSelectModal.selectAtLeastOne'),
    );
    return;
  }

  // 验证表关系
  for (const rel of relations.value) {
    if (
      !rel.sourceTable ||
      !rel.sourceField ||
      !rel.targetTable ||
      !rel.targetField
    ) {
      ElMessage.warning(
        $t('ai-platform.workflow.editor.tableSelectModal.completeRelations'),
      );
      return;
    }
  }

  const tables = [...checkedTables.value.values()];
  const firstTable = tables[0];
  const dbConfig = currentDbConfig.value || {
    dbName: firstTable?.dbName || '',
    dbType: firstTable?.dbType || '',
    database: firstTable?.database || '',
    schema: firstTable?.schema,
  };

  emit('select', tables, dbConfig, relations.value);
  dialogVisible.value = false;
}

// 关闭
function handleClose() {
  dialogVisible.value = false;
}

// 刷新树
async function refreshTree() {
  await loadDatabaseConfigs();
  ElMessage.success(
    $t('ai-platform.workflow.editor.tableSelectModal.refreshSuccess'),
  );
}

// 初始化
onMounted(() => {
  loadDatabaseConfigs();
});
</script>

<template>
  <ElDialog
    v-model="dialogVisible"
    :show-close="false"
    fullscreen
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="table-select-modal"
    header-class="!pb-0"
  >
    <template #header>
      <div
        class="bg-background-deep flex h-14 w-full items-center justify-between rounded-[8px] px-6 shadow-sm"
      >
        <!-- 左侧：Logo和标题 -->
        <div class="flex items-center gap-3">
          <div class="flex items-center gap-2">
            <div
              class="bg-primary flex h-8 w-8 items-center justify-center rounded"
            >
              <Database class="h-4 w-4 text-white" />
            </div>
            <span class="text-foreground/70 text-base font-medium">{{
              $t('ai-platform.workflow.editor.tableSelectModal.title')
            }}</span>
          </div>
        </div>

        <!-- 中间：步骤条 -->
        <div class="absolute left-1/2 flex -translate-x-1/2 items-center">
          <template v-for="(step, index) in steps" :key="index">
            <div
              class="flex cursor-pointer items-center px-4 py-1"
              :class="{ 'cursor-not-allowed': index > currentStep }"
              @click="index < currentStep ? (currentStep = index) : null"
            >
              <div
                class="flex items-center justify-center rounded-full border px-3 py-1 text-sm transition-all"
                :class="[
                  index === currentStep
                    ? 'bg-primary/10 border-primary text-primary font-medium'
                    : index < currentStep
                      ? 'border-primary/50 text-primary/80 bg-transparent'
                      : 'border-border text-muted-foreground bg-transparent',
                ]"
              >
                <span
                  class="mr-2 flex h-5 w-5 items-center justify-center rounded-full text-xs"
                  :class="
                    index === currentStep
                      ? 'bg-primary text-white'
                      : index < currentStep
                        ? 'bg-primary/80 text-white'
                        : 'bg-muted text-muted-foreground'
                  "
                >
                  {{ step.index }}
                </span>
                {{ step.title }}
              </div>
            </div>
            <div
              v-if="index < steps.length - 1"
              class="bg-border h-[1px] w-8"
              :class="{ 'bg-primary/50': index < currentStep }"
            ></div>
          </template>
        </div>

        <!-- 右侧：操作按钮 -->
        <div class="flex items-center gap-3">
          <ElButton v-if="canGoPrev" @click="handlePrev">
            {{ $t('ai-platform.workflow.editor.tableSelectModal.prevStep') }}
          </ElButton>
          <ElButton
            v-if="!isLastStep"
            type="primary"
            plain
            :disabled="!canGoNext"
            @click="handleNext"
          >
            {{ $t('ai-platform.workflow.editor.tableSelectModal.nextStep') }}
          </ElButton>
          <ElButton
            v-if="isLastStep"
            type="primary"
            plain
            @click="handleConfirm"
          >
            <Check class="mr-1 h-4 w-4" />
            {{
              $t('ai-platform.workflow.editor.tableSelectModal.confirmSelect')
            }}
          </ElButton>
          <ElButton @click="handleClose">
            {{ $t('ai-platform.workflow.editor.tableSelectModal.close') }}
          </ElButton>
        </div>
      </div>
    </template>

    <!-- 步骤内容 -->
    <div class="h-[calc(100vh-120px)] overflow-hidden">
      <!-- 步骤1: 选择数据表 -->
      <div v-show="currentStep === 0" class="flex h-full gap-4 py-4">
        <!-- 左侧：数据库树形结构 -->
        <div
          class="border-border bg-card flex h-full w-[300px] flex-col rounded-lg border"
        >
          <div
            class="border-border flex items-center justify-between border-b px-3 py-2"
          >
            <div class="flex items-center gap-2">
              <ElIcon><Database /></ElIcon>
              <span class="text-sm font-medium">{{
                $t('ai-platform.workflow.editor.tableSelectModal.database')
              }}</span>
            </div>
            <ElTooltip
              :content="
                $t('ai-platform.workflow.editor.tableSelectModal.refresh')
              "
            >
              <ElButton
                :icon="RefreshCw"
                link
                size="small"
                @click="refreshTree"
              />
            </ElTooltip>
          </div>

          <!-- 树形结构 -->
          <ElScrollbar class="flex-1">
            <div v-if="loading" class="flex h-32 items-center justify-center">
              <span class="text-muted-foreground text-sm">{{
                $t('ai-platform.workflow.editor.tableSelectModal.loading')
              }}</span>
            </div>
            <ElTree
              v-else
              :data="treeData"
              :props="treeProps"
              :load="loadNode"
              node-key="id"
              lazy
              highlight-current
              class="p-2"
              @node-click="handleNodeClick"
            >
              <template #default="{ data }">
                <div
                  class="flex w-full items-center justify-between gap-2 pr-2"
                >
                  <div class="flex items-center gap-2">
                    <DatabaseTreeNodeIcon
                      :type="data.type"
                      :db-type="data.meta?.dbType"
                      :size="16"
                    />
                    <DatabaseTreeNodeLabel
                      :label="data.label"
                      :type="data.type"
                      :is-system="data.meta?.isSystem"
                      :db-name="data.meta?.dbName"
                    />
                  </div>
                  <!-- 表节点显示复选框 -->
                  <ElCheckbox
                    v-if="data.type === 'table'"
                    :model-value="isTableChecked(data.meta?.table)"
                    size="small"
                    @click.stop
                    @change="toggleTableCheck(data)"
                  />
                </div>
              </template>
            </ElTree>
          </ElScrollbar>
        </div>

        <!-- 中间：字段预览 -->
        <div
          class="border-border bg-card flex w-[280px] flex-col rounded-lg border"
        >
          <div class="border-border flex items-center gap-2 border-b px-3 py-2">
            <span class="text-sm font-medium">
              {{
                selectedTableNode
                  ? $t('ai-platform.workflow.editor.tableSelectModal.fieldOf', {
                      table: selectedTableNode.label,
                    })
                  : $t(
                      'ai-platform.workflow.editor.tableSelectModal.fieldPreview',
                    )
              }}
            </span>
          </div>

          <ElScrollbar class="flex-1">
            <div
              v-if="!selectedTableNode"
              class="flex h-full items-center justify-center"
            >
              <span class="text-muted-foreground text-sm">{{
                $t(
                  'ai-platform.workflow.editor.tableSelectModal.clickToPreview',
                )
              }}</span>
            </div>
            <div
              v-else-if="previewLoading"
              class="flex h-32 items-center justify-center"
            >
              <span class="text-muted-foreground text-sm">{{
                $t('ai-platform.workflow.editor.tableSelectModal.loading')
              }}</span>
            </div>
            <div v-else class="p-2">
              <div
                v-for="field in previewFields"
                :key="field.name"
                class="border-border/50 flex items-center justify-between border-b px-2 py-1.5 text-xs last:border-b-0"
              >
                <div class="flex items-center gap-1">
                  <span
                    class="font-mono"
                    :class="{ 'text-primary font-medium': field.isPrimaryKey }"
                  >
                    {{ field.name }}
                  </span>
                  <ElTag v-if="field.isPrimaryKey" size="small" type="warning">
                    PK
                  </ElTag>
                </div>
                <span class="text-muted-foreground">{{ field.type }}</span>
              </div>
              <div
                v-if="previewFields.length === 0"
                class="text-muted-foreground py-8 text-center text-sm"
              >
                {{
                  $t('ai-platform.workflow.editor.tableSelectModal.noFields')
                }}
              </div>
            </div>
          </ElScrollbar>
        </div>

        <!-- 右侧：已选表列表 -->
        <div
          class="border-border bg-card flex flex-1 flex-col rounded-lg border"
        >
          <div
            class="border-border flex items-center justify-between border-b px-3 py-2"
          >
            <div class="flex items-center gap-2">
              <Database class="h-4 w-4" />
              <span class="text-sm font-medium">{{
                $t(
                  'ai-platform.workflow.editor.tableSelectModal.selectedTables',
                )
              }}</span>
              <ElTag v-if="checkedCount > 0" size="small" type="primary">
                {{ checkedCount }}
              </ElTag>
            </div>
            <ElButton
              v-if="checkedCount > 0"
              link
              size="small"
              type="danger"
              @click="clearAllChecked"
            >
              {{ $t('ai-platform.workflow.editor.tableSelectModal.clearAll') }}
            </ElButton>
          </div>

          <ElScrollbar class="flex-1">
            <div
              v-if="checkedCount === 0"
              class="flex h-full min-h-[200px] items-center justify-center"
            >
              <span class="text-muted-foreground text-sm">
                {{
                  $t(
                    'ai-platform.workflow.editor.tableSelectModal.clickCheckboxHint',
                  )
                }}
              </span>
            </div>
            <div v-else class="space-y-1 p-2">
              <div
                v-for="[tableName, tableInfo] in checkedTables"
                :key="tableName"
                class="bg-muted group flex items-center justify-between rounded px-3 py-2"
              >
                <div class="flex flex-col">
                  <span class="text-primary text-sm font-medium">{{
                    tableName
                  }}</span>
                  <span class="text-muted-foreground text-xs">
                    {{
                      $t(
                        'ai-platform.workflow.editor.tableSelectModal.fieldsCount',
                        { count: tableInfo.fields.length },
                      )
                    }}
                  </span>
                </div>
                <ElButton
                  :icon="X"
                  link
                  size="small"
                  class="opacity-0 group-hover:opacity-100"
                  @click="removeCheckedTable(tableName)"
                />
              </div>
            </div>
          </ElScrollbar>

          <!-- 数据库配置信息 -->
          <div
            v-if="currentDbConfig"
            class="border-border bg-muted border-t px-3 py-2"
          >
            <div class="text-muted-foreground text-xs">
              <span class="font-medium">{{ currentDbConfig.database }}</span>
              <span v-if="currentDbConfig.schema">.{{ currentDbConfig.schema }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 步骤2: 设计表关系 -->
      <div v-show="currentStep === 1" class="flex h-full gap-4 p-4">
        <!-- 左侧：已选表和字段 -->
        <div
          class="border-border bg-card flex w-[280px] flex-col rounded-lg border"
        >
          <div class="border-border flex items-center gap-2 border-b px-3 py-2">
            <Database class="h-4 w-4" />
            <span class="text-sm font-medium">{{
              $t('ai-platform.workflow.editor.tableSelectModal.selectedTables')
            }}</span>
            <ElTag size="small" type="primary">{{ checkedCount }}</ElTag>
          </div>

          <ElScrollbar class="flex-1">
            <div class="space-y-2 p-2">
              <div
                v-for="table in selectedTableInfoList"
                :key="table.tableName"
                class="border-border rounded-lg border"
              >
                <!-- 表头：可点击折叠/展开 -->
                <div
                  class="bg-primary/5 hover:bg-primary/10 flex cursor-pointer items-center justify-between px-3 py-2"
                  @click="
                    tableExpandedMap.set(
                      table.tableName,
                      !tableExpandedMap.get(table.tableName),
                    )
                  "
                >
                  <div class="flex items-center gap-2">
                    <component
                      :is="
                        tableExpandedMap.get(table.tableName)
                          ? ChevronDown
                          : ChevronRight
                      "
                      class="text-muted-foreground h-3.5 w-3.5"
                    />
                    <span class="text-primary text-sm font-medium">{{
                      table.tableName
                    }}</span>
                    <ElTag size="small" class="scale-75">
                      {{ table.fields.length }}
                    </ElTag>
                  </div>
                </div>
                <!-- 字段列表：展开时显示，不使用滚动 -->
                <div
                  v-show="tableExpandedMap.get(table.tableName)"
                  class="border-border border-t"
                >
                  <div
                    v-for="field in table.fields"
                    :key="field.name"
                    class="hover:bg-muted/50 flex items-center justify-between px-3 py-1.5 text-xs"
                  >
                    <div class="flex items-center gap-1">
                      <span
                        :class="{
                          'text-primary font-medium': field.isPrimaryKey,
                        }"
                      >
                        {{ field.name }}
                      </span>
                      <ElTag
                        v-if="field.isPrimaryKey"
                        size="small"
                        type="warning"
                        class="scale-75"
                      >
                        PK
                      </ElTag>
                    </div>
                    <span class="text-muted-foreground">{{ field.type }}</span>
                  </div>
                </div>
              </div>
            </div>
          </ElScrollbar>
        </div>

        <!-- 右侧：表关系配置 -->
        <div
          class="border-border bg-card flex flex-1 flex-col rounded-lg border"
        >
          <div
            class="border-border flex items-center justify-between border-b px-3 py-2"
          >
            <div class="flex items-center gap-2">
              <Link class="h-4 w-4" />
              <span class="text-sm font-medium">{{
                $t(
                  'ai-platform.workflow.editor.tableSelectModal.tableRelations',
                )
              }}</span>
              <ElTag v-if="relations.length > 0" size="small" type="success">
                {{ relations.length }}
              </ElTag>
            </div>
            <ElButton
              type="primary"
              size="small"
              :disabled="checkedCount < 2"
              @click="addRelation"
            >
              {{
                $t('ai-platform.workflow.editor.tableSelectModal.addRelation')
              }}
            </ElButton>
          </div>

          <ElScrollbar class="flex-1">
            <div
              v-if="checkedCount < 2"
              class="flex h-full items-center justify-center"
            >
              <span class="text-muted-foreground text-sm">{{
                $t(
                  'ai-platform.workflow.editor.tableSelectModal.selectTwoTablesFirst',
                )
              }}</span>
            </div>
            <div
              v-else-if="relations.length === 0"
              class="flex h-full items-center justify-center"
            >
              <div class="text-center">
                <p class="text-muted-foreground mb-2 text-sm">
                  {{
                    $t(
                      'ai-platform.workflow.editor.tableSelectModal.noRelations',
                    )
                  }}
                </p>
                <p class="text-muted-foreground text-xs">
                  {{
                    $t(
                      'ai-platform.workflow.editor.tableSelectModal.addRelationHint',
                    )
                  }}
                </p>
              </div>
            </div>
            <div v-else class="space-y-3 p-3">
              <div
                v-for="(relation, index) in relations"
                :key="relation.id"
                class="bg-muted rounded-lg p-4"
              >
                <div class="mb-3 flex items-center justify-between">
                  <span class="text-sm font-medium">{{
                    $t(
                      'ai-platform.workflow.editor.tableSelectModal.relationIndex',
                      { index: index + 1 },
                    )
                  }}</span>
                  <ElButton
                    link
                    size="small"
                    type="danger"
                    @click="removeRelation(relation.id)"
                  >
                    {{
                      $t('ai-platform.workflow.editor.tableSelectModal.delete')
                    }}
                  </ElButton>
                </div>

                <!-- 源表配置 -->
                <div class="mb-3">
                  <div class="text-muted-foreground mb-1 text-xs">
                    {{
                      $t(
                        'ai-platform.workflow.editor.tableSelectModal.sourceTable',
                      )
                    }}
                  </div>
                  <div class="flex gap-2">
                    <ElSelect
                      v-model="relation.sourceTable"
                      :placeholder="
                        $t(
                          'ai-platform.workflow.editor.tableSelectModal.selectTable',
                        )
                      "
                      size="small"
                      class="flex-1"
                    >
                      <ElOption
                        v-for="table in selectedTableInfoList"
                        :key="table.tableName"
                        :label="table.tableName"
                        :value="table.tableName"
                      />
                    </ElSelect>
                    <ElSelect
                      v-model="relation.sourceField"
                      :placeholder="
                        $t(
                          'ai-platform.workflow.editor.tableSelectModal.selectField',
                        )
                      "
                      size="small"
                      class="flex-1"
                      :disabled="!relation.sourceTable"
                    >
                      <ElOption
                        v-for="field in getTableFields(relation.sourceTable)"
                        :key="field.name"
                        :label="field.name"
                        :value="field.name"
                      />
                    </ElSelect>
                  </div>
                </div>

                <!-- 关系类型 -->
                <div class="my-3">
                  <div class="text-muted-foreground mb-1 text-xs">
                    {{
                      $t(
                        'ai-platform.workflow.editor.tableSelectModal.relationType',
                      )
                    }}
                  </div>
                  <ElSelect
                    v-model="relation.relationType"
                    size="small"
                    class="w-full"
                  >
                    <ElOption
                      value="one-to-one"
                      :label="
                        $t(
                          'ai-platform.workflow.editor.tableSelectModal.oneToOne',
                        )
                      "
                    />
                    <ElOption
                      value="one-to-many"
                      :label="
                        $t(
                          'ai-platform.workflow.editor.tableSelectModal.oneToMany',
                        )
                      "
                    />
                    <ElOption
                      value="many-to-one"
                      :label="
                        $t(
                          'ai-platform.workflow.editor.tableSelectModal.manyToOne',
                        )
                      "
                    />
                    <ElOption
                      value="many-to-many"
                      :label="
                        $t(
                          'ai-platform.workflow.editor.tableSelectModal.manyToMany',
                        )
                      "
                    />
                  </ElSelect>
                </div>

                <!-- 目标表配置 -->
                <div>
                  <div class="text-muted-foreground mb-1 text-xs">
                    {{
                      $t(
                        'ai-platform.workflow.editor.tableSelectModal.targetTable',
                      )
                    }}
                  </div>
                  <div class="flex gap-2">
                    <ElSelect
                      v-model="relation.targetTable"
                      :placeholder="
                        $t(
                          'ai-platform.workflow.editor.tableSelectModal.selectTable',
                        )
                      "
                      size="small"
                      class="flex-1"
                    >
                      <ElOption
                        v-for="table in selectedTableInfoList"
                        :key="table.tableName"
                        :label="table.tableName"
                        :value="table.tableName"
                      />
                    </ElSelect>
                    <ElSelect
                      v-model="relation.targetField"
                      :placeholder="
                        $t(
                          'ai-platform.workflow.editor.tableSelectModal.selectField',
                        )
                      "
                      size="small"
                      class="flex-1"
                      :disabled="!relation.targetTable"
                    >
                      <ElOption
                        v-for="field in getTableFields(relation.targetTable)"
                        :key="field.name"
                        :label="field.name"
                        :value="field.name"
                      />
                    </ElSelect>
                  </div>
                </div>
              </div>
            </div>
          </ElScrollbar>

          <!-- 提示信息 -->
          <div class="border-border bg-muted/50 border-t px-3 py-2">
            <div class="text-muted-foreground text-xs">
              {{ $t('ai-platform.workflow.editor.tableSelectModal.hint') }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </ElDialog>
</template>

<style>
.table-select-modal .el-dialog__header {
  /* padding: 16px; */
  margin-right: 0;
}

.table-select-modal .el-dialog__body {
  padding: 0;
}

/* 懒加载时 loading 替换箭头位置 */
.table-select-modal .el-tree-node__content:has(.el-tree-node__loading-icon)
  > .el-tree-node__expand-icon {
  display: none;
}

.table-select-modal .el-tree-node__loading-icon {
  order: -1;
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  margin-right: 0;
}

.table-select-modal .el-tree-node__expand-icon {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  padding: 0;
}

.table-select-modal .el-tree-node__content {
  display: flex;
  align-items: center;
  height: 28px;
  line-height: 28px;
  border-radius: 4px;
}
</style>
