<script setup lang="ts">
import { DatabaseZap } from '@vben/icons';
import { $t } from '@vben/locales';

import DbNodeConnectionBadge from '../components/DbNodeConnectionBadge.vue';
import BaseNode from './BaseNode.vue';

defineProps(['selected', 'data', 'id']);

const getFieldCount = (fieldMapping: Record<string, string> | undefined) => {
  if (!fieldMapping) return 0;
  return Object.keys(fieldMapping).length;
};
</script>

<template>
  <BaseNode
    :selected="selected"
    :execution-status="data.executionStatus"
    :execution-result="data.executionResult"
    :label="data.label || $t('ai-platform.workflow.nodes.db_insert.label')"
    :inputs="[{ id: 'target' }]"
    :outputs="[{ id: 'source' }]"
    :node-id="id"
    node-type="db_insert"
  >
    <template #icon><DatabaseZap class="size-5 text-green-600" /></template>
    <template #desc>
      {{ $t('ai-platform.workflow.nodes.db_insert.desc') }}
    </template>

    <div class="space-y-2">
      <DbNodeConnectionBadge
        :db-config="data.db_config"
        show-default-badge
      />

      <!-- 表名 -->
      <div class="flex items-center gap-2">
        <span
          class="rounded border border-green-200 bg-green-50 px-1.5 py-0.5 text-[10px] font-bold text-green-600 dark:border-green-700 dark:bg-green-950 dark:text-green-400"
        >
          INSERT
        </span>
        <span
          class="text-foreground flex-1 truncate font-mono text-xs"
          :title="data.table"
        >
          {{ data.table || $t('ai-platform.workflow.nodes.db_insert.noTable') }}
        </span>
      </div>

      <!-- {{ $t('ai-platform.workflow.nodes.db_insert.fieldMapping') }}预览 -->
      <div
        v-if="data.field_mapping && getFieldCount(data.field_mapping) > 0"
        class="bg-muted rounded px-2 py-1.5"
      >
        <div class="text-muted-foreground mb-1 text-[10px]">
          {{ $t('ai-platform.workflow.nodes.db_insert.fieldMapping') }} ({{
            getFieldCount(data.field_mapping)
          }})
        </div>
        <div class="space-y-0.5">
          <div
            v-for="(value, field) in data.field_mapping"
            :key="field"
            class="flex items-center gap-1 text-[10px]"
          >
            <span class="text-muted-foreground font-medium">{{ field }}</span>
            <span class="text-muted-foreground">←</span>
            <span
              class="truncate font-mono text-green-600 dark:text-green-400"
              :title="value"
              >{{ value }}</span>
          </div>
        </div>
      </div>

      <!-- UPSERT 标记 -->
      <div v-if="data.upsert" class="text-[10px] text-blue-600">
        {{ $t('ai-platform.workflow.nodes.db_insert.upsert') }}
      </div>
    </div>
  </BaseNode>
</template>
