<script setup lang="ts">
import { DatabaseBackup } 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_update.label')"
    :inputs="[{ id: 'target' }]"
    :outputs="[{ id: 'source' }]"
    :node-id="id"
    node-type="db_update"
  >
    <template #icon><DatabaseBackup class="size-5 text-orange-600" /></template>
    <template #desc>
      {{ $t('ai-platform.workflow.nodes.db_update.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-orange-200 bg-orange-50 px-1.5 py-0.5 text-[10px] font-bold text-orange-600"
        >
          UPDATE
        </span>
        <span
          class="text-foreground flex-1 truncate font-mono text-xs"
          :title="data.table"
        >
          {{ data.table || $t('ai-platform.workflow.nodes.db_update.noTable') }}
        </span>
      </div>

      <!-- 字段映射预览 -->
      <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_update.updateFields') }} ({{
            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-orange-600" :title="value">{{
              value
            }}</span>
          </div>
        </div>
      </div>

      <!-- 条件预览 -->
      <div
        v-if="data.where_conditions && data.where_conditions.length > 0"
        class="rounded bg-yellow-50 px-2 py-1.5"
      >
        <div class="text-[10px] text-yellow-700">
          {{
            $t('ai-platform.workflow.nodes.common.conditions', {
              count: data.where_conditions.length,
            })
          }}
        </div>
      </div>
    </div>
  </BaseNode>
</template>
