<script setup lang="ts">
import type { SelectedTable } from '../components/TableSelectDialog.vue';

import { ref, watch } from 'vue';

import { Database, Plus, Trash2 } from '@vben/icons';
import { $t } from '@vben/locales';

import {
  ElButton,
  ElCheckbox,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElSelect,
  ElTag,
} from 'element-plus';

import SmartInput from '../components/SmartInput.vue';
import DbConfigSummary from '../components/DbConfigSummary.vue';
import TableSelectDialog from '../components/TableSelectDialog.vue';

const props = defineProps<{ data: any; nodeId: string }>();
const emit = defineEmits(['update']);

const form = ref({
  label: $t('ai-platform.workflow.panels.dbInsert.label'),
  operation: 'insert',
  table: '',
  db_config: null as null | {
    database: string;
    dbName: string;
    dbType: string;
    schema?: string;
  },
  table_fields: [] as Array<{
    isPrimaryKey: boolean;
    name: string;
    type: string;
  }>,
  field_mapping: [] as Array<{ field: string; value: string }>,
  where_conditions: [] as Array<{
    field: string;
    operator: string;
    value: string;
  }>,
  upsert: false,
  output_variable: 'db_result',
  ...props.data,
});

// 表选择对话框
const tableSelectVisible = ref(false);

// 确保数组存在
if (!form.value.field_mapping) form.value.field_mapping = [];
if (!form.value.where_conditions) form.value.where_conditions = [];
if (!form.value.table_fields) form.value.table_fields = [];

// 将对象格式转换为数组格式（兼容旧数据）
if (props.data.field_mapping && !Array.isArray(props.data.field_mapping)) {
  form.value.field_mapping = Object.entries(props.data.field_mapping).map(
    ([field, value]) => ({
      field,
      value: value as string,
    }),
  );
}

// 条件操作符选项
const operatorOptions = [
  { value: '=', label: $t('ai-platform.workflow.panels.dbQuery.eqOp') },
  { value: '!=', label: $t('ai-platform.workflow.panels.dbQuery.neOp') },
];

watch(
  form,
  (val) => {
    // 将数组格式转换为对象格式存储
    const fieldMappingObj: Record<string, string> = {};
    val.field_mapping.forEach((item: any) => {
      if (item.field) {
        fieldMappingObj[item.field] = item.value;
      }
    });

    emit('update', {
      ...val,
      operation: val.upsert ? 'upsert' : 'insert',
      field_mapping: fieldMappingObj,
    });
  },
  { deep: true },
);

// 添加字段映射
const addFieldMapping = () => {
  form.value.field_mapping.push({ field: '', value: '' });
};

// 删除字段映射
const removeFieldMapping = (index: number) => {
  form.value.field_mapping.splice(index, 1);
};

// 添加条件
const addCondition = () => {
  form.value.where_conditions.push({ field: '', operator: '=', value: '' });
};

// 删除条件
const removeCondition = (index: number) => {
  form.value.where_conditions.splice(index, 1);
};

// 处理表选择
const handleTableSelect = (table: SelectedTable) => {
  form.value.table = table.tableName;
  form.value.db_config = {
    dbName: table.dbName,
    database: table.database,
    schema: table.schema,
    dbType: table.dbType,
  };
  form.value.table_fields = table.fields.map((f) => ({
    name: f.name,
    type: f.type,
    isPrimaryKey: f.isPrimaryKey,
  }));
};

// 快速添加字段映射
const addFieldFromTable = (fieldName: string) => {
  // 检查是否已存在
  if (
    form.value.field_mapping.some(
      (f: { field: string }) => f.field === fieldName,
    )
  )
    return;
  form.value.field_mapping.push({ field: fieldName, value: '' });
};
</script>

<template>
  <ElForm label-position="top" size="small" class="space-y-4">
    <ElFormItem :label="$t('ai-platform.workflow.panels.common.nodeName')">
      <ElInput
        v-model="form.label"
        :placeholder="$t('ai-platform.workflow.panels.dbInsert.placeholder')"
      />
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.targetTable')">
      <div class="flex w-full gap-2">
        <ElInput
          v-model="form.table"
          :placeholder="
            $t('ai-platform.workflow.panels.common.tablePlaceholder')
          "
          readonly
          class="flex-1"
        >
          <template #prefix>
            <Database class="text-muted-foreground h-4 w-4" />
          </template>
        </ElInput>
        <ElButton
          type="primary"
          :icon="Plus"
          @click="tableSelectVisible = true"
        >
          {{ $t('ai-platform.workflow.panels.common.selectTable') }}
        </ElButton>
      </div>
      <DbConfigSummary
        :db-config="form.db_config"
        show-default-write-warning
      />
    </ElFormItem>

    <!-- 表字段快捷选择 -->
    <div v-if="form.table_fields.length > 0" class="mb-4">
      <div class="text-foreground mb-2 text-sm font-medium">
        {{ $t('ai-platform.workflow.panels.common.tableFields') }}
      </div>
      <div class="flex flex-wrap gap-1">
        <ElTag
          v-for="field in form.table_fields"
          :key="field.name"
          :type="field.isPrimaryKey ? 'warning' : 'info'"
          size="small"
          class="cursor-pointer"
          @click="addFieldFromTable(field.name)"
        >
          {{ field.name }}
          <span class="ml-1 text-[10px] opacity-60">{{ field.type }}</span>
        </ElTag>
      </div>
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.common.clickFieldToAdd') }}
      </div>
    </div>

    <!-- 字段映射 -->
    <div class="mb-4">
      <div class="mb-2 flex items-center justify-between">
        <span class="text-foreground text-sm font-medium">{{
          $t('ai-platform.workflow.panels.common.fieldMapping')
        }}</span>
        <ElButton
          link
          type="primary"
          :icon="Plus"
          size="small"
          @click="addFieldMapping"
        >
          {{ $t('ai-platform.workflow.panels.common.addField') }}
        </ElButton>
      </div>

      <div class="space-y-2">
        <div
          v-for="(item, index) in form.field_mapping"
          :key="index"
          class="border-border bg-muted flex items-center gap-2 rounded border p-2"
        >
          <ElSelect
            v-if="form.table_fields.length > 0"
            v-model="item.field"
            :placeholder="$t('ai-platform.workflow.panels.common.selectField')"
            size="small"
            class="max-w-36"
            filterable
            allow-create
          >
            <ElOption
              v-for="f in form.table_fields"
              :key="f.name"
              :value="f.name"
              :label="f.name"
            />
          </ElSelect>
          <ElInput
            v-else
            v-model="item.field"
            :placeholder="$t('ai-platform.workflow.panels.common.dbField')"
            size="small"
            class="min-w-32"
          />
          <span class="text-muted-foreground">←</span>
          <SmartInput
            v-model="item.value"
            :current-node-id="nodeId"
            :placeholder="$t('ai-platform.workflow.panels.common.varValue')"
            size="small"
            class="flex-1"
          />
          <ElButton
            link
            type="danger"
            :icon="Trash2"
            size="small"
            @click="removeFieldMapping(index)"
          />
        </div>

        <div
          v-if="form.field_mapping.length === 0"
          class="text-muted-foreground py-4 text-center text-xs"
        >
          {{ $t('ai-platform.workflow.panels.common.clickAddField') }}
        </div>
      </div>
    </div>

    <!-- UPSERT 选项 -->
    <ElFormItem>
      <ElCheckbox v-model="form.upsert">
        {{ $t('ai-platform.workflow.panels.common.upsert') }}
      </ElCheckbox>
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.common.upsertHint') }}
      </div>
    </ElFormItem>

    <!-- UPSERT 条件 -->
    <div v-if="form.upsert" class="mb-4">
      <div class="mb-2 flex items-center justify-between">
        <span class="text-foreground text-sm font-medium">
          {{ $t('ai-platform.workflow.panels.common.judgeCondition') }}
          <span class="text-red-500">*</span>
        </span>
        <ElButton
          link
          type="primary"
          :icon="Plus"
          size="small"
          @click="addCondition"
        >
          {{ $t('ai-platform.workflow.panels.common.addCondition') }}
        </ElButton>
      </div>

      <div class="space-y-2">
        <div
          v-for="(item, index) in form.where_conditions"
          :key="index"
          class="border-border bg-muted flex items-center gap-2 rounded border p-2"
        >
          <ElInput
            v-model="item.field"
            :placeholder="$t('ai-platform.workflow.panels.common.field')"
            size="small"
            class="w-24"
          />
          <ElSelect v-model="item.operator" size="small" class="w-20">
            <ElOption
              v-for="op in operatorOptions"
              :key="op.value"
              :value="op.value"
              :label="op.label"
            />
          </ElSelect>
          <SmartInput
            v-model="item.value"
            :current-node-id="nodeId"
            :placeholder="$t('ai-platform.workflow.panels.common.value')"
            size="small"
            class="flex-1"
          />
          <ElButton
            link
            type="danger"
            :icon="Trash2"
            size="small"
            @click="removeCondition(index)"
          />
        </div>

        <div
          v-if="form.where_conditions.length === 0"
          class="py-4 text-center text-xs text-red-500 dark:text-red-400"
        >
          {{ $t('ai-platform.workflow.panels.common.addJudgeConditionHint') }}
        </div>
      </div>
    </div>

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.outputVarName')">
      <ElInput v-model="form.output_variable" placeholder="db_result" />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.common.insertResultSavedTo') }}
      </div>
    </ElFormItem>

    <!-- 表选择对话框 -->
    <TableSelectDialog
      v-model:visible="tableSelectVisible"
      :current-table="form.table"
      @select="handleTableSelect"
    />
  </ElForm>
</template>
