<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,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  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.dbQuery.label'),
  operation: 'select',
  table: '',
  db_config: null as null | {
    database: string;
    dbName: string;
    dbType: string;
    schema?: string;
  },
  table_fields: [] as Array<{
    isPrimaryKey: boolean;
    name: string;
    type: string;
  }>,
  where_conditions: [] as Array<{
    field: string;
    operator: string;
    value: string;
  }>,
  return_fields: '*',
  limit: 100,
  order_by: '',
  output_variable: 'db_result',
  ...props.data,
});

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

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

// 条件操作符选项
const operatorOptions = [
  { value: '=', label: $t('ai-platform.workflow.panels.dbQuery.eqOp') },
  { value: '!=', label: $t('ai-platform.workflow.panels.dbQuery.neOp') },
  { value: '>', label: $t('ai-platform.workflow.panels.dbQuery.gtOp') },
  { value: '>=', label: $t('ai-platform.workflow.panels.dbQuery.gteOp') },
  { value: '<', label: $t('ai-platform.workflow.panels.dbQuery.ltOp') },
  { value: '<=', label: $t('ai-platform.workflow.panels.dbQuery.lteOp') },
  { value: 'like', label: $t('ai-platform.workflow.panels.dbQuery.likeOp') },
  { value: 'in', label: $t('ai-platform.workflow.panels.dbQuery.inOp') },
  {
    value: 'is_null',
    label: $t('ai-platform.workflow.panels.dbQuery.isNullOp'),
  },
  {
    value: 'is_not_null',
    label: $t('ai-platform.workflow.panels.dbQuery.isNotNullOp'),
  },
];

watch(
  form,
  (val) => {
    // 将 return_fields 字符串转换为数组
    let returnFields = val.return_fields;
    if (typeof returnFields === 'string') {
      returnFields =
        returnFields === '*' || returnFields.trim() === ''
          ? ['*']
          : returnFields
              .split(',')
              .map((f: string) => f.trim())
              .filter(Boolean);
    }

    emit('update', {
      ...val,
      return_fields: returnFields,
    });
  },
  { deep: true },
);

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,
  }));
};
</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.dbQuery.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" />
    </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.availableFields') }}
      </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"
        >
          {{ field.name }}
        </ElTag>
      </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.queryConditions')
        }}</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-28">
            <ElOption
              v-for="op in operatorOptions"
              :key="op.value"
              :value="op.value"
              :label="op.label"
            />
          </ElSelect>
          <SmartInput
            v-if="!['is_null', 'is_not_null'].includes(item.operator)"
            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="text-muted-foreground py-2 text-center text-xs"
        >
          {{ $t('ai-platform.workflow.panels.common.noConditionQueryAll') }}
        </div>
      </div>
    </div>

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.returnFields')">
      <ElInput
        v-model="form.return_fields"
        placeholder="* or id,name,created_at"
      />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.common.returnFieldsHint') }}
      </div>
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.orderBy')">
      <ElInput v-model="form.order_by" placeholder="e.g. created_at DESC" />
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.limitRows')">
      <ElInputNumber v-model="form.limit" :min="1" :max="1000" />
    </ElFormItem>

    <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.resultSavedTo') }}
      </div>
    </ElFormItem>

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