<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';

import { $t } from '@vben/locales';

import {
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElOption,
  ElRadioButton,
  ElRadioGroup,
  ElSelect,
  ElSwitch,
} from 'element-plus';

import { getFormListApi } from '#/api/ai-platform/form-manager-lite';

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

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

// 根据节点类型设置默认值
const getDefaultLabel = () => {
  switch (props.nodeType) {
    case 'form_data_create': {
      return $t('ai-platform.workflow.panels.formData.createLabel');
    }
    case 'form_data_delete': {
      return $t('ai-platform.workflow.panels.formData.deleteLabel');
    }
    case 'form_data_list': {
      return $t('ai-platform.workflow.panels.formData.listLabel');
    }
    case 'form_data_read': {
      return $t('ai-platform.workflow.panels.formData.readLabel');
    }
    case 'form_data_update': {
      return $t('ai-platform.workflow.panels.formData.updateLabel');
    }
    case 'form_schema_to_llm': {
      return $t('ai-platform.workflow.panels.formData.schemaToLlmLabel');
    }
    default: {
      return $t('ai-platform.workflow.panels.formData.label');
    }
  }
};

const getDefaultOutputVariable = () => {
  switch (props.nodeType) {
    case 'form_data_create': {
      return 'form_data_create_result';
    }
    case 'form_data_delete': {
      return 'form_data_delete_result';
    }
    case 'form_data_list': {
      return 'form_data_list';
    }
    case 'form_data_read': {
      return 'form_data';
    }
    case 'form_data_update': {
      return 'form_data_update_result';
    }
    case 'form_schema_to_llm': {
      return 'llm_output_schema';
    }
    default: {
      return 'form_data_result';
    }
  }
};

const form = ref({
  label: getDefaultLabel(),
  form_code: '',
  id: '',
  data: '',
  page: 1,
  page_size: 20,
  filters: '',
  sort: [],
  hard_delete: false,
  is_array: false,
  include_fields: [],
  exclude_fields: [],
  output_variable: getDefaultOutputVariable(),
  ...props.data,
});

// 表单输入模式：variable（变量输入）或 select（下拉选择）
const formInputMode = ref<'select' | 'variable'>('variable');

// 表单列表
const formList = ref<any[]>([]);
const formLoading = ref(false);

// 加载表单列表
const loadFormList = async () => {
  try {
    formLoading.value = true;
    const res = await getFormListApi({
      page: 1,
      pageSize: 100,
      status: 'published',
      includeGloballyVisible: true,
    });
    formList.value = res.items || [];
  } catch (error) {
    console.error('加载表单列表失败:', error);
  } finally {
    formLoading.value = false;
  }
};

onMounted(() => {
  loadFormList();
});

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

// 判断是否显示某个字段
const showField = (field: string) => {
  const nodeType = props.nodeType;
  switch (field) {
    case 'data': {
      return ['form_data_create', 'form_data_update'].includes(nodeType);
    }
    case 'exclude_fields':
    case 'include_fields':
    case 'is_array': {
      return nodeType === 'form_schema_to_llm';
    }
    case 'filters':
    case 'page':
    case 'page_size':
    case 'sort': {
      return nodeType === 'form_data_list';
    }
    case 'hard_delete': {
      return nodeType === 'form_data_delete';
    }
    case 'id': {
      return ['form_data_delete', 'form_data_read', 'form_data_update'].includes(nodeType);
    }
    default: {
      return true;
    }
  }
};
</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="getDefaultLabel()" />
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.formData.formCode')">
      <div class="flex items-center gap-2 mb-2">
        <ElRadioGroup v-model="formInputMode" size="small">
          <ElRadioButton value="variable">{{ $t('ai-platform.workflow.panels.formData.variableInput') }}</ElRadioButton>
          <ElRadioButton value="select">{{ $t('ai-platform.workflow.panels.formData.selectFromList') }}</ElRadioButton>
        </ElRadioGroup>
      </div>

      <!-- 变量输入模式 -->
      <template v-if="formInputMode === 'variable'">
        <SmartInput
          v-model="form.form_code"
          :current-node-id="nodeId"
          :placeholder="
            $t('ai-platform.workflow.panels.formData.formCodeInputPlaceholder') +
            ' {{form_code}}'
          "
        />
        <div class="text-muted-foreground mt-1 text-xs">
          {{ $t('ai-platform.workflow.panels.formData.formCodeInputHint') }}
        </div>
      </template>

      <!-- 下拉选择模式 -->
      <template v-else>
        <ElSelect
          v-model="form.form_code"
          :placeholder="$t('ai-platform.workflow.panels.formData.selectFormPlaceholder')"
          filterable
          :loading="formLoading"
          class="w-full"
        >
          <ElOption
            v-for="f in formList"
            :key="f.code"
            :label="`${f.name} (${f.code})`"
            :value="f.code"
          />
        </ElSelect>
        <div class="text-muted-foreground mt-1 text-xs">
          {{ $t('ai-platform.workflow.panels.formData.selectedFormHint', { code: form.form_code || '-' }) }}
        </div>
      </template>
    </ElFormItem>

    <!-- 记录ID（读取/更新/删除） -->
    <ElFormItem v-if="showField('id')" :label="$t('ai-platform.workflow.panels.formData.recordId')">
      <SmartInput
        v-model="form.id"
        :current-node-id="nodeId"
        :placeholder="
          $t('ai-platform.workflow.panels.formData.recordIdPlaceholder') +
          ' {{record_id}}'
        "
      />
    </ElFormItem>

    <!-- 数据（创建/更新） -->
    <ElFormItem v-if="showField('data')">
      <template #label>
        <div class="flex items-center gap-2">
          <span>{{ $t('ai-platform.workflow.panels.formData.data') }}</span>
          <span class="text-muted-foreground text-xs">(JSON)</span>
        </div>
      </template>
      <SmartInput
        v-model="form.data"
        :current-node-id="nodeId"
        type="textarea"
        :rows="6"
        :placeholder="$t('ai-platform.workflow.panels.formData.dataPlaceholder') + ' {{llm_response}}'"
      />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.formData.dataHint') }}
      </div>
    </ElFormItem>

    <!-- 分页（列表查询） -->
    <template v-if="showField('page')">
      <div class="flex gap-4">
        <ElFormItem :label="$t('ai-platform.workflow.panels.formData.pageNum')" class="flex-1">
          <ElInputNumber v-model="form.page" :min="1" class="w-full" />
        </ElFormItem>
        <ElFormItem :label="$t('ai-platform.workflow.panels.formData.pageSize')" class="flex-1">
          <ElInputNumber v-model="form.page_size" :min="1" :max="1000" class="w-full" />
        </ElFormItem>
      </div>
    </template>

    <!-- 过滤条件（列表查询） -->
    <ElFormItem v-if="showField('filters')">
      <template #label>
        <div class="flex items-center gap-2">
          <span>{{ $t('ai-platform.workflow.panels.formData.filterConditions') }}</span>
          <span class="text-muted-foreground text-xs">(JSON)</span>
        </div>
      </template>
      <SmartInput
        v-model="form.filters"
        :current-node-id="nodeId"
        type="textarea"
        :rows="4"
        placeholder="{&quot;status&quot;: &quot;active&quot;, &quot;name&quot;: {&quot;type&quot;: &quot;like&quot;, &quot;value&quot;: &quot;Zhang&quot;}}"
      />
    </ElFormItem>

    <!-- 硬删除（删除） -->
    <ElFormItem v-if="showField('hard_delete')">
      <div class="flex items-center gap-2">
        <ElSwitch v-model="form.hard_delete" />
        <span class="text-sm">{{ $t('ai-platform.workflow.panels.formData.hardDelete') }}</span>
      </div>
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.formData.hardDeleteHint') }}
      </div>
    </ElFormItem>

    <!-- 数组模式（表单转LLM结构） -->
    <ElFormItem v-if="showField('is_array')">
      <div class="flex items-center gap-2">
        <ElSwitch v-model="form.is_array" />
        <span class="text-sm">{{ $t('ai-platform.workflow.panels.formData.generateArray') }}</span>
      </div>
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.formData.generateArrayHint') }}
      </div>
    </ElFormItem>

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