<script setup lang="ts">
import type {
  DbConfigInfo,
  SelectedTableInfo,
  TableRelation,
} from '../components/TableSelectModal.vue';

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

import { Database } from '@vben/icons';

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

import { getActiveModelsApi } from '#/api/ai-platform/ai-platform';

import SmartInput from '../components/SmartInput.vue';
import TableSelectModal from '../components/TableSelectModal.vue';

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

const form = ref({
  label: 'Text-to-SQL',
  user_question: '',
  db_config: null as DbConfigInfo | null,
  selected_tables: [] as string[],
  table_fields: {} as Record<string, any[]>,
  table_relations: [] as TableRelation[],
  model_id: '',
  model_name: '',
  include_table_relations: true,
  output_variable: 'text_to_sql_result',
  ...props.data,
});

// 模型列表
const models = ref<any[]>([]);
const modelsLoading = ref(false);

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

// 已选表数量
const selectedTableCount = computed(
  () => form.value.selected_tables?.length || 0,
);

// 加载模型列表
const loadModels = async () => {
  modelsLoading.value = true;
  try {
    const res = await getActiveModelsApi();
    models.value = res.filter((m) => m.model_type === 'chat');
    if (form.value.model_id && !form.value.model_name) {
      const model = models.value.find((m) => m.id === form.value.model_id);
      if (model) {
        form.value.model_name = model.model_name;
      }
    }
  } catch (error) {
    console.error('加载模型列表失败:', error);
  } finally {
    modelsLoading.value = false;
  }
};

// 监听 model_id 变化，更新 model_name
watch(
  () => form.value.model_id,
  (newId) => {
    const model = models.value.find((m) => m.id === newId);
    if (model) {
      form.value.model_name = model.model_name;
    }
  },
);

watch(
  form,
  (val) => {
    emit('update', val);
  },
  { deep: true },
);

// 处理表选择
const handleTableSelect = (
  tables: SelectedTableInfo[],
  dbConfig: DbConfigInfo,
  relations: TableRelation[],
) => {
  form.value.db_config = dbConfig;
  form.value.selected_tables = tables.map((t) => t.tableName);
  form.value.table_relations = relations;

  // 保存表字段信息
  const tableFields: Record<string, any[]> = {};
  tables.forEach((t) => {
    tableFields[t.tableName] = t.fields;
  });
  form.value.table_fields = tableFields;
};

// 移除已选表
const removeTable = (tableName: string) => {
  form.value.selected_tables = form.value.selected_tables.filter(
    (t: string) => t !== tableName,
  );
  if (form.value.table_fields) {
    delete form.value.table_fields[tableName];
  }
  // 如果没有选中的表了，清空数据库配置
  if (form.value.selected_tables.length === 0) {
    form.value.db_config = null;
  }
};

// 清空所有选中的表
const clearAllTables = () => {
  form.value.selected_tables = [];
  form.value.table_fields = {};
  form.value.db_config = null;
};

onMounted(() => {
  loadModels();
});
</script>

<template>
  <ElForm label-position="top" size="small" class="space-y-4">
    <ElAlert type="info" :closable="false" show-icon>
      <template #title>
        <span class="text-xs font-medium">{{
          $t('ai-platform.workflow.panels.textToSql.description')
        }}</span>
      </template>
    </ElAlert>

    <ElAlert type="warning" :closable="false" show-icon>
      <template #title>
        <span class="text-xs">{{
          $t('ai-platform.workflow.panels.textToSql.chainDbSqlHint')
        }}</span>
      </template>
    </ElAlert>

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.nodeName')">
      <ElInput v-model="form.label" placeholder="Text-to-SQL" />
    </ElFormItem>

    <ElFormItem
      :label="$t('ai-platform.workflow.panels.textToSql.queryQuestion')"
      required
    >
      <SmartInput
        v-model="form.user_question"
        :current-node-id="nodeId"
        type="textarea"
        :rows="3"
        :placeholder="
          $t('ai-platform.workflow.panels.textToSql.queryPlaceholder')
        "
      />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.textToSql.varRefHint')
        }}<code v-pre>{{ start.user_input }}</code>
      </div>
    </ElFormItem>

    <ElFormItem
      :label="$t('ai-platform.workflow.panels.textToSql.dataTables')"
      required
    >
      <div class="w-full space-y-2">
        <!-- 选择按钮 -->
        <ElButton
          type="primary"
          plain
          class="w-full"
          @click="tableSelectVisible = true"
        >
          <Database class="mr-1 h-4 w-4" />
          {{
            selectedTableCount > 0
              ? $t('ai-platform.workflow.panels.textToSql.modifySelection')
              : $t('ai-platform.workflow.panels.textToSql.selectTables')
          }}
        </ElButton>

        <!-- 数据库配置信息 -->
        <div v-if="form.db_config" class="bg-muted rounded px-3 py-2">
          <div class="text-muted-foreground text-xs">
            <span class="font-medium">{{ form.db_config.database }}</span>
            <span v-if="form.db_config.schema"
              >.{{ form.db_config.schema }}</span
            >
            <span class="text-muted-foreground ml-2"
              >({{ form.db_config.dbType }})</span
            >
          </div>
        </div>

        <!-- 已选表列表 -->
        <div v-if="selectedTableCount > 0" class="space-y-1">
          <div class="flex items-center justify-between">
            <span class="text-muted-foreground text-xs">{{
              $t('ai-platform.workflow.panels.textToSql.selectedTables', {
                count: selectedTableCount,
              })
            }}</span>
            <ElButton link size="small" type="danger" @click="clearAllTables">
              {{ $t('ai-platform.workflow.panels.textToSql.clear') }}
            </ElButton>
          </div>
          <div class="flex flex-wrap gap-1">
            <ElTag
              v-for="tableName in form.selected_tables"
              :key="tableName"
              closable
              size="small"
              @close="removeTable(tableName)"
            >
              {{ tableName }}
            </ElTag>
          </div>
        </div>
        <div v-else class="text-muted-foreground text-xs">
          {{ $t('ai-platform.workflow.panels.textToSql.autoAnalyzeHint') }}
        </div>
      </div>
    </ElFormItem>

    <ElFormItem
      :label="$t('ai-platform.workflow.panels.textToSql.includeRelations')"
    >
      <div class="flex items-center justify-between">
        <span class="text-muted-foreground text-xs">{{
          $t('ai-platform.workflow.panels.textToSql.includeRelationsHint')
        }}</span>
        <ElSwitch v-model="form.include_table_relations" />
      </div>
    </ElFormItem>

    <!-- 表选择对话框 -->
    <TableSelectModal
      v-model:visible="tableSelectVisible"
      :selected-tables="form.selected_tables"
      :db-config="form.db_config || undefined"
      :table-relations="form.table_relations"
      @select="handleTableSelect"
    />

    <ElFormItem
      :label="$t('ai-platform.workflow.panels.textToSql.llmModel')"
      required
    >
      <ElSelect
        v-model="form.model_id"
        :placeholder="
          $t('ai-platform.workflow.panels.textToSql.selectLlmModel')
        "
        :loading="modelsLoading"
        class="w-full"
        filterable
      >
        <ElOption
          v-for="model in models"
          :key="model.id"
          :label="model.model_name"
          :value="model.id"
        >
          <div class="flex items-center justify-between">
            <span>{{ model.model_name }}</span>
            <span class="text-muted-foreground text-xs">{{
              model.provider_name
            }}</span>
          </div>
        </ElOption>
      </ElSelect>
      <!-- <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.textToSql.modelRecommendation') }}
      </div> -->
    </ElFormItem>

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

    <!-- 输出变量说明 -->
    <div class="bg-muted rounded-lg p-3">
      <div class="mb-2 text-xs font-medium">
        {{ $t('ai-platform.workflow.panels.common.outputVars') }}
      </div>
      <div class="space-y-1 text-xs">
        <div class="flex items-start gap-2">
          <code class="bg-background rounded px-1"
            >{{ form.output_variable }}_sql</code
          >
          <span class="text-muted-foreground">{{
            $t('ai-platform.workflow.panels.textToSql.sqlOutput')
          }}</span>
        </div>
        <div class="flex items-start gap-2">
          <code class="bg-background rounded px-1"
            >{{ form.output_variable }}_thought</code
          >
          <span class="text-muted-foreground">{{
            $t('ai-platform.workflow.panels.textToSql.reasoningOutput')
          }}</span>
        </div>
      </div>
    </div>
  </ElForm>
</template>
