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

import { $t } from '@vben/locales';
import { ChevronDown, ChevronRight, CirclePlus, Code, List, Trash2 } from '@vben/icons';

import {
  ElButton,
  ElInput,
  ElInputNumber,
  ElOption,
  ElSelect,
  ElSwitch,
} from 'element-plus';

import { ZqDialog } from '#/components/zq-dialog';

interface SchemaField {
  name: string;
  type: string;
  description: string;
  required: boolean;
  items?: SchemaField; // array 类型的元素定义
  properties?: SchemaField[]; // object 类型的子属性
  enum?: string[]; // 枚举值（仅 string 类型）
  default?: any; // 默认值
  minimum?: number; // 最小值（number/integer）
  maximum?: number; // 最大值（number/integer）
}

const props = defineProps<{
  modelValue: boolean;
  schema: SchemaField[];
}>();

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void;
  (e: 'update:schema', value: SchemaField[]): void;
  (e: 'confirm', value: SchemaField[]): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
});

// 本地编辑的schema
const localSchema = ref<SchemaField[]>([]);

// 展开状态
const expandedNodes = ref<Set<string>>(new Set());

// 编辑模式：visual 可视化编辑，json JSON编辑
const editMode = ref<'visual' | 'json'>('visual');

// JSON 编辑内容
const jsonContent = ref('');

// JSON 解析错误
const jsonError = ref('');

// 高级配置展开状态（用于 enum/default/min/max）
const advancedExpanded = ref<Set<string>>(new Set());

// 切换高级配置展开状态
const toggleAdvanced = (fieldPath: string) => {
  if (advancedExpanded.value.has(fieldPath)) {
    advancedExpanded.value.delete(fieldPath);
  } else {
    advancedExpanded.value.add(fieldPath);
  }
};

// 字段类型选项
const fieldTypeOptions = computed(() => [
  { label: $t('ai-platform.workflow.editor.schemaConfigDialog.typeString'), value: 'string' },
  { label: $t('ai-platform.workflow.editor.schemaConfigDialog.typeNumber'), value: 'number' },
  { label: $t('ai-platform.workflow.editor.schemaConfigDialog.typeInteger'), value: 'integer' },
  { label: $t('ai-platform.workflow.editor.schemaConfigDialog.typeBoolean'), value: 'boolean' },
  { label: $t('ai-platform.workflow.editor.schemaConfigDialog.typeArray'), value: 'array' },
  { label: $t('ai-platform.workflow.editor.schemaConfigDialog.typeObject'), value: 'object' },
]);

// 深拷贝
const deepClone = <T>(obj: T): T => {
  return JSON.parse(JSON.stringify(obj));
};

// 初始化
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      localSchema.value = deepClone(props.schema || []);
      expandedNodes.value = new Set();
      // 同步 JSON 内容
      syncJsonFromSchema();
      jsonError.value = '';
    }
  },
  { immediate: true },
);

// 将内部字段数组转换为标准 JSON Schema 格式
const buildJsonSchema = (fields: SchemaField[]): any => {
  const properties: Record<string, any> = {};
  const required: string[] = [];

  for (const field of fields) {
    if (!field.name) continue;

    const prop: any = {
      type: field.type,
      description: field.description || undefined,
    };

    if (field.enum && field.enum.length > 0) {
      prop.enum = field.enum;
    }
    if (field.default !== undefined && field.default !== '') {
      prop.default = field.default;
    }
    if (field.minimum !== undefined && field.minimum !== null) {
      prop.minimum = field.minimum;
    }
    if (field.maximum !== undefined && field.maximum !== null) {
      prop.maximum = field.maximum;
    }

    if (field.type === 'object' && field.properties) {
      const nested = buildJsonSchema(field.properties);
      prop.properties = nested.properties;
      if (nested.required?.length > 0) {
        prop.required = nested.required;
      }
    } else if (field.type === 'array' && field.items) {
      if (field.items.type === 'object' && field.items.properties) {
        const nested = buildJsonSchema(field.items.properties);
        prop.items = {
          type: 'object',
          properties: nested.properties,
        };
        if (nested.required?.length > 0) {
          prop.items.required = nested.required;
        }
      } else {
        prop.items = { type: field.items.type };
      }
    }

    properties[field.name] = prop;
    if (field.required) {
      required.push(field.name);
    }
  }

  return { properties, required };
};

// 将标准 JSON Schema 格式转换为内部字段数组
const parseJsonSchema = (schema: any): SchemaField[] => {
  const fields: SchemaField[] = [];
  const properties = schema.properties || {};
  const required = schema.required || [];

  for (const [name, prop] of Object.entries(properties) as [string, any][]) {
    const field: SchemaField = {
      name,
      type: prop.type || 'string',
      description: prop.description || '',
      required: required.includes(name),
    };

    if (prop.enum) {
      field.enum = prop.enum;
    }
    if (prop.default !== undefined) {
      field.default = prop.default;
    }
    if (prop.minimum !== undefined) {
      field.minimum = prop.minimum;
    }
    if (prop.maximum !== undefined) {
      field.maximum = prop.maximum;
    }

    if (prop.type === 'object' && prop.properties) {
      field.properties = parseJsonSchema({ properties: prop.properties, required: prop.required });
    } else if (prop.type === 'array' && prop.items) {
      if (prop.items.type === 'object' && prop.items.properties) {
        field.items = {
          name: 'item',
          type: 'object',
          description: '',
          required: false,
          properties: parseJsonSchema({ properties: prop.items.properties, required: prop.items.required }),
        };
      } else {
        field.items = {
          name: 'item',
          type: prop.items.type || 'string',
          description: '',
          required: false,
        };
      }
    }

    fields.push(field);
  }

  return fields;
};

// 从 schema 同步到 JSON（标准 JSON Schema 格式）
const syncJsonFromSchema = () => {
  const schema = buildJsonSchema(localSchema.value);
  jsonContent.value = JSON.stringify(schema, null, 2);
};

// 从 JSON 同步到 schema（支持标准 JSON Schema 格式）
const syncSchemaFromJson = () => {
  try {
    const parsed = JSON.parse(jsonContent.value);
    // 支持标准 JSON Schema 格式（有 properties 字段）
    if (parsed.properties) {
      localSchema.value = parseJsonSchema(parsed);
      jsonError.value = '';
      return true;
    }
    // 也支持旧的数组格式（兼容）
    if (Array.isArray(parsed)) {
      localSchema.value = parsed;
      jsonError.value = '';
      return true;
    }
    jsonError.value = $t('ai-platform.workflow.editor.schemaConfigDialog.jsonFormatError');
    return false;
  } catch (e: any) {
    jsonError.value = $t('ai-platform.workflow.editor.schemaConfigDialog.jsonParseError', { message: e.message });
    return false;
  }
};

// 切换编辑模式
const switchEditMode = (mode: 'visual' | 'json') => {
  if (mode === 'json' && editMode.value === 'visual') {
    // 从可视化切换到 JSON，同步内容
    syncJsonFromSchema();
  } else if (mode === 'visual' && editMode.value === 'json') {
    // 从 JSON 切换到可视化，尝试解析
    if (!syncSchemaFromJson()) {
      return; // 解析失败，不切换
    }
  }
  editMode.value = mode;
};

// 生成唯一路径
const getNodePath = (parentPath: string, index: number): string => {
  return parentPath ? `${parentPath}.${index}` : `${index}`;
};

// 切换展开状态
const toggleExpand = (path: string) => {
  if (expandedNodes.value.has(path)) {
    expandedNodes.value.delete(path);
  } else {
    expandedNodes.value.add(path);
  }
};

// 添加根级字段
const addRootField = () => {
  localSchema.value.push({
    name: '',
    type: 'string',
    description: '',
    required: false,
  });
};

// 添加子属性（object类型）
const addChildProperty = (field: SchemaField, path: string) => {
  if (!field.properties) {
    field.properties = [];
  }
  field.properties.push({
    name: '',
    type: 'string',
    description: '',
    required: false,
  });
  expandedNodes.value.add(path);
};

// 设置数组元素类型
const setArrayItemType = (field: SchemaField, type: string) => {
  if (type === 'object') {
    field.items = {
      name: 'item',
      type: 'object',
      description: '',
      required: false,
      properties: [],
    };
  } else {
    field.items = {
      name: 'item',
      type: type,
      description: '',
      required: false,
    };
  }
};

// 删除字段
const removeField = (list: SchemaField[], index: number) => {
  list.splice(index, 1);
};

// 处理类型变更
const handleTypeChange = (field: SchemaField, newType: string) => {
  field.type = newType;
  if (newType === 'object') {
    field.properties = field.properties || [];
    delete field.items;
  } else if (newType === 'array') {
    field.items = field.items || {
      name: 'item',
      type: 'string',
      description: '',
      required: false,
    };
    delete field.properties;
  } else {
    delete field.properties;
    delete field.items;
  }
};

// 确认
const handleConfirm = () => {
  // 如果是 JSON 模式，先同步
  if (editMode.value === 'json') {
    if (!syncSchemaFromJson()) {
      return; // 解析失败，不关闭
    }
  }
  emit('confirm', deepClone(localSchema.value));
  emit('update:schema', deepClone(localSchema.value));
  visible.value = false;
};

// 取消
const handleCancel = () => {
  visible.value = false;
};

// 生成预览JSON Schema
const previewSchema = computed(() => {
  const buildSchema = (fields: SchemaField[]): any => {
    const properties: Record<string, any> = {};
    const required: string[] = [];

    for (const field of fields) {
      if (!field.name) continue;

      const prop: any = {
        type: field.type,
        description: field.description || undefined,
      };

      // 添加 enum 支持
      if (field.enum && field.enum.length > 0) {
        prop.enum = field.enum;
      }

      // 添加 default 支持
      if (field.default !== undefined && field.default !== '') {
        prop.default = field.default;
      }

      // 添加 minimum/maximum 支持
      if (field.minimum !== undefined && field.minimum !== null) {
        prop.minimum = field.minimum;
      }
      if (field.maximum !== undefined && field.maximum !== null) {
        prop.maximum = field.maximum;
      }

      if (field.type === 'object' && field.properties) {
        const nested = buildSchema(field.properties);
        prop.properties = nested.properties;
        if (nested.required?.length > 0) {
          prop.required = nested.required;
        }
      } else if (field.type === 'array' && field.items) {
        if (field.items.type === 'object' && field.items.properties) {
          const nested = buildSchema(field.items.properties);
          prop.items = {
            type: 'object',
            properties: nested.properties,
          };
          if (nested.required?.length > 0) {
            prop.items.required = nested.required;
          }
        } else {
          prop.items = { type: field.items.type };
        }
      }

      properties[field.name] = prop;
      if (field.required) {
        required.push(field.name);
      }
    }

    return { properties, required };
  };

  return buildSchema(localSchema.value);
});
</script>

<template>
  <ZqDialog
    v-model="visible"
    :title="$t('ai-platform.workflow.editor.schemaConfigDialog.title')"
    width="1000px"
    :show-footer="true"
    @confirm="handleConfirm"
    @cancel="handleCancel"
  >
    <div class="flex gap-4 h-[600px]">
      <!-- 左侧：字段配置 -->
      <div class="flex-1 h-[calc(100%-48px)]">
        <!-- 编辑模式切换 -->
        <div class="mb-3 flex items-center justify-between">
          <div class="flex items-center gap-2">
            <button
              type="button"
              class="flex items-center gap-1 rounded px-2 py-1 text-sm"
              :class="editMode === 'visual' ? 'bg-primary/10 text-primary' : 'hover:bg-muted text-muted-foreground'"
              @click="switchEditMode('visual')"
            >
              <List class="size-4" />
              {{ $t('ai-platform.workflow.editor.schemaConfigDialog.visual') }}
            </button>
            <button
              type="button"
              class="flex items-center gap-1 rounded px-2 py-1 text-sm"
              :class="editMode === 'json' ? 'bg-primary/10 text-primary' : 'hover:bg-muted text-muted-foreground'"
              @click="switchEditMode('json')"
            >
              <Code class="size-4" />
              JSON
            </button>
          </div>
          <ElButton v-if="editMode === 'visual'" type="primary" link :icon="CirclePlus" @click="addRootField">
            {{ $t('ai-platform.workflow.editor.schemaConfigDialog.addField') }}
          </ElButton>
        </div>

        <!-- JSON 编辑模式 -->
        <div v-if="editMode === 'json'" class="flex h-full flex-col">
          <ElInput
            v-model="jsonContent"
            type="textarea"
            resize="none"
            class="schema-json-textarea"
          />
          <div v-if="jsonError" class="mt-2 text-xs text-red-500">
            {{ jsonError }}
          </div>
          <!-- <div class="text-muted-foreground mt-2 text-xs">
            提示：JSON 格式为字段数组，每个字段包含 name, type, description, required 等属性。支持 enum 属性定义枚举值。
          </div> -->
        </div>

        <!-- 可视化编辑模式 -->
        <template v-else>
          <div
            v-if="localSchema.length === 0"
            class="text-muted-foreground rounded border border-dashed py-8 text-center text-sm h-full"
          >
            {{ $t('ai-platform.workflow.editor.schemaConfigDialog.emptyHint') }}
          </div>

        <!-- 递归渲染字段 -->
        <div v-else class="space-y-2">
          <template v-for="(field, index) in localSchema" :key="index">
            <div class="schema-field">
              <!-- 字段头部 -->
              <div
                class="bg-muted/30 flex items-center gap-2 rounded-t border p-2"
              >
                <!-- 展开/折叠按钮 -->
                <button
                  v-if="field.type === 'object' || field.type === 'array'"
                  type="button"
                  class="hover:bg-muted rounded p-1"
                  @click="toggleExpand(getNodePath('', index))"
                >
                  <component
                    :is="
                      expandedNodes.has(getNodePath('', index))
                        ? ChevronDown
                        : ChevronRight
                    "
                    class="h-4 w-4"
                  />
                </button>
                <div v-else class="w-6" />

                <!-- 字段名 -->
                <ElInput
                  v-model="field.name"
                  :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.fieldName')"
                  size="small"
                  style="width: 120px"
                />

                <!-- 类型 -->
                <ElSelect
                  :model-value="field.type"
                  size="small"
                  style="width: 140px"
                  @change="(val: string) => handleTypeChange(field, val)"
                >
                  <ElOption
                    v-for="opt in fieldTypeOptions"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </ElSelect>

                <!-- 描述 -->
                <ElInput
                  v-model="field.description"
                  :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.description')"
                  size="small"
                  class="flex-1"
                />

                <!-- 必填 -->
                <div class="flex items-center gap-1">
                  <ElSwitch v-model="field.required" size="small" />
                  <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.required') }}</span>
                </div>

                <!-- 删除 -->
                <ElButton
                  type="danger"
                  link
                  :icon="Trash2"
                  size="small"
                  @click="removeField(localSchema, index)"
                />
              </div>

              <!-- string 类型的额外配置（enum 和 default） -->
              <div
                v-if="field.type === 'string'"
                class="border-x border-b bg-white dark:bg-gray-900"
              >
                <button
                  type="button"
                  class="text-muted-foreground hover:text-foreground flex w-full items-center gap-1 px-3 py-2 text-xs"
                  @click="toggleAdvanced(`root-${index}`)"
                >
                  <ChevronRight v-if="!advancedExpanded.has(`root-${index}`)" class="size-3" />
                  <ChevronDown v-else class="size-3" />
                  {{ $t('ai-platform.workflow.editor.schemaConfigDialog.advancedConfigEnumDefault') }}
                </button>
                <div v-if="advancedExpanded.has(`root-${index}`)" class="space-y-3 px-3 pb-3">
                  <!-- 枚举值 -->
                  <div>
                    <div class="mb-1 flex items-center justify-between">
                      <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.enumValues') }}</span>
                      <ElButton
                        type="primary"
                        link
                        size="small"
                        @click="field.enum = field.enum || []; field.enum.push('')"
                      >
                        {{ $t('ai-platform.workflow.editor.schemaConfigDialog.addOption') }}
                      </ElButton>
                    </div>
                    <div v-if="field.enum && field.enum.length > 0" class="flex flex-wrap gap-2">
                      <div
                        v-for="(enumVal, enumIdx) in field.enum"
                        :key="enumIdx"
                        class="flex items-center gap-1"
                      >
                        <ElInput
                          :model-value="enumVal"
                          size="small"
                          style="width: 100px"
                          :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.optionValue')"
                          @update:model-value="(val: string) => field.enum![enumIdx] = val"
                        />
                        <ElButton
                          type="danger"
                          link
                          size="small"
                          :icon="Trash2"
                          @click="field.enum!.splice(enumIdx, 1)"
                        />
                      </div>
                    </div>
                    <div v-else class="text-muted-foreground text-xs">
                      {{ $t('ai-platform.workflow.editor.schemaConfigDialog.enumHint') }}
                    </div>
                  </div>
                  <!-- 默认值 -->
                  <div class="flex items-center gap-2">
                    <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.defaultValue') }}</span>
                    <ElInput
                      v-model="field.default"
                      size="small"
                      style="width: 150px"
                      :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.optional')"
                    />
                  </div>
                </div>
              </div>

              <!-- number/integer 类型的额外配置 -->
              <div
                v-if="field.type === 'number' || field.type === 'integer'"
                class="border-x border-b bg-white dark:bg-gray-900"
              >
                <button
                  type="button"
                  class="text-muted-foreground hover:text-foreground flex w-full items-center gap-1 px-3 py-2 text-xs"
                  @click="toggleAdvanced(`root-${index}`)"
                >
                  <ChevronRight v-if="!advancedExpanded.has(`root-${index}`)" class="size-3" />
                  <ChevronDown v-else class="size-3" />
                  {{ $t('ai-platform.workflow.editor.schemaConfigDialog.advancedConfigMinMaxDefault') }}
                </button>
                <div v-if="advancedExpanded.has(`root-${index}`)" class="flex flex-wrap items-center gap-4 px-3 pb-3">
                  <div class="flex items-center gap-2">
                    <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.minValue') }}</span>
                    <ElInputNumber
                      v-model="field.minimum"
                      size="small"
                      style="width: 100px"
                      :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.noLimit')"
                    />
                  </div>
                  <div class="flex items-center gap-2">
                    <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.maxValue') }}</span>
                    <ElInputNumber
                      v-model="field.maximum"
                      size="small"
                      style="width: 100px"
                      :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.noLimit')"
                    />
                  </div>
                  <div class="flex items-center gap-2">
                    <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.defaultValue') }}</span>
                    <ElInputNumber
                      v-model="field.default"
                      size="small"
                      style="width: 100px"
                      :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.optional')"
                    />
                  </div>
                </div>
              </div>

              <!-- object 类型的子属性 -->
              <div
                v-if="
                  field.type === 'object' &&
                  expandedNodes.has(getNodePath('', index))
                "
                class="border-x border-b bg-white p-3 dark:bg-gray-900"
              >
                <div class="mb-2 flex items-center justify-between">
                  <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.childProperties') }}</span>
                  <ElButton
                    type="primary"
                    link
                    size="small"
                    :icon="CirclePlus"
                    @click="addChildProperty(field, getNodePath('', index))"
                  >
                    {{ $t('ai-platform.workflow.editor.schemaConfigDialog.add') }}
                  </ElButton>
                </div>

                <div
                  v-if="!field.properties || field.properties.length === 0"
                  class="text-muted-foreground rounded border border-dashed py-4 text-center text-xs"
                >
                  {{ $t('ai-platform.workflow.editor.schemaConfigDialog.noChildProperties') }}
                </div>

                <!-- 递归渲染子属性 -->
                <div v-else class="space-y-2 pl-4">
                  <div
                    v-for="(child, childIndex) in field.properties"
                    :key="childIndex"
                    class="bg-muted/20 rounded border p-2"
                  >
                    <div class="flex items-center gap-2">
                      <ElInput
                        v-model="child.name"
                        :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.fieldName')"
                        size="small"
                        style="width: 100px"
                      />
                      <ElSelect
                        :model-value="child.type"
                        size="small"
                        style="width: 120px"
                        @change="(val: string) => handleTypeChange(child, val)"
                      >
                        <ElOption
                          v-for="opt in fieldTypeOptions"
                          :key="opt.value"
                          :label="opt.label"
                          :value="opt.value"
                        />
                      </ElSelect>
                      <ElInput
                        v-model="child.description"
                        :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.description')"
                        size="small"
                        class="flex-1"
                      />
                      <ElSwitch v-model="child.required" size="small" />
                      <ElButton
                        type="danger"
                        link
                        :icon="Trash2"
                        size="small"
                        @click="removeField(field.properties!, childIndex)"
                      />
                    </div>

                    <!-- string 类型的额外配置 -->
                    <div v-if="child.type === 'string'" class="mt-2 border-t">
                      <button
                        type="button"
                        class="text-muted-foreground hover:text-foreground flex items-center gap-1 py-1 text-xs"
                        @click="toggleAdvanced(`child-${index}-${childIndex}`)"
                      >
                        <ChevronRight v-if="!advancedExpanded.has(`child-${index}-${childIndex}`)" class="size-3" />
                        <ChevronDown v-else class="size-3" />
                        {{ $t('ai-platform.workflow.editor.schemaConfigDialog.advancedConfig') }}
                      </button>
                      <div v-if="advancedExpanded.has(`child-${index}-${childIndex}`)" class="space-y-2 pb-2">
                        <div class="flex items-center gap-2">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.enumValuesShort') }}</span>
                          <ElButton type="primary" link size="small" @click="child.enum = child.enum || []; child.enum.push('')">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.add') }}</ElButton>
                        </div>
                        <div v-if="child.enum && child.enum.length > 0" class="flex flex-wrap gap-1">
                          <div v-for="(ev, ei) in child.enum" :key="ei" class="flex items-center gap-1">
                            <ElInput :model-value="ev" size="small" style="width: 80px" @update:model-value="(v: string) => child.enum![ei] = v" />
                            <ElButton type="danger" link size="small" :icon="Trash2" @click="child.enum!.splice(ei, 1)" />
                          </div>
                        </div>
                        <div class="flex items-center gap-2">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.defaultShort') }}</span>
                          <ElInput v-model="child.default" size="small" style="width: 100px" :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.optional')" />
                        </div>
                      </div>
                    </div>

                    <!-- number/integer 类型的额外配置 -->
                    <div v-if="child.type === 'number' || child.type === 'integer'" class="mt-2 border-t">
                      <button
                        type="button"
                        class="text-muted-foreground hover:text-foreground flex items-center gap-1 py-1 text-xs"
                        @click="toggleAdvanced(`child-${index}-${childIndex}`)"
                      >
                        <ChevronRight v-if="!advancedExpanded.has(`child-${index}-${childIndex}`)" class="size-3" />
                        <ChevronDown v-else class="size-3" />
                        {{ $t('ai-platform.workflow.editor.schemaConfigDialog.advancedConfig') }}
                      </button>
                      <div v-if="advancedExpanded.has(`child-${index}-${childIndex}`)" class="flex flex-wrap items-center gap-3 pb-2">
                        <div class="flex items-center gap-1">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.minShort') }}</span>
                          <ElInputNumber v-model="child.minimum" size="small" style="width: 80px" />
                        </div>
                        <div class="flex items-center gap-1">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.maxShort') }}</span>
                          <ElInputNumber v-model="child.maximum" size="small" style="width: 80px" />
                        </div>
                        <div class="flex items-center gap-1">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.defaultShort') }}</span>
                          <ElInputNumber v-model="child.default" size="small" style="width: 80px" />
                        </div>
                      </div>
                    </div>

                    <!-- 嵌套 object -->
                    <div
                      v-if="child.type === 'object'"
                      class="mt-2 border-l-2 border-blue-300 pl-3"
                    >
                      <div class="mb-1 flex items-center justify-between">
                        <span class="text-muted-foreground text-xs"
                          >{{ $t('ai-platform.workflow.editor.schemaConfigDialog.nestedProperties') }}</span
                        >
                        <ElButton
                          type="primary"
                          link
                          size="small"
                          :icon="CirclePlus"
                          @click="
                            addChildProperty(
                              child,
                              getNodePath(getNodePath('', index), childIndex),
                            )
                          "
                        >
                          {{ $t('ai-platform.workflow.editor.schemaConfigDialog.add') }}
                        </ElButton>
                      </div>
                      <div
                        v-for="(
                          nested, nestedIndex
                        ) in child.properties || []"
                        :key="nestedIndex"
                        class="bg-muted/10 mb-1 rounded p-2"
                      >
                        <div class="flex items-center gap-2">
                          <ElInput
                            v-model="nested.name"
                            :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.fieldName')"
                            size="small"
                            style="width: 80px"
                          />
                          <ElSelect
                            :model-value="nested.type"
                            size="small"
                            style="width: 100px"
                            @change="(val: string) => handleTypeChange(nested, val)"
                          >
                            <ElOption
                              v-for="opt in fieldTypeOptions"
                              :key="opt.value"
                              :label="opt.label"
                              :value="opt.value"
                            />
                          </ElSelect>
                          <ElInput
                            v-model="nested.description"
                            :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.description')"
                            size="small"
                            class="flex-1"
                          />
                          <ElSwitch v-model="nested.required" size="small" />
                          <ElButton
                            type="danger"
                            link
                            :icon="Trash2"
                            size="small"
                            @click="removeField(child.properties!, nestedIndex)"
                          />
                        </div>
                        <!-- nested string -->
                        <div v-if="nested.type === 'string'" class="mt-2 border-t">
                          <button
                            type="button"
                            class="text-muted-foreground hover:text-foreground flex items-center gap-1 py-1 text-xs"
                            @click="toggleAdvanced(`nested-${index}-${childIndex}-${nestedIndex}`)"
                          >
                            <ChevronRight v-if="!advancedExpanded.has(`nested-${index}-${childIndex}-${nestedIndex}`)" class="size-3" />
                            <ChevronDown v-else class="size-3" />
                            {{ $t('ai-platform.workflow.editor.schemaConfigDialog.advancedConfig') }}
                          </button>
                          <div v-if="advancedExpanded.has(`nested-${index}-${childIndex}-${nestedIndex}`)" class="space-y-2 pb-2">
                            <div class="flex items-center gap-2">
                              <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.enumValuesShort') }}</span>
                              <ElButton type="primary" link size="small" @click="nested.enum = nested.enum || []; nested.enum.push('')">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.add') }}</ElButton>
                            </div>
                            <div v-if="nested.enum && nested.enum.length > 0" class="flex flex-wrap gap-1">
                              <div v-for="(ev, ei) in nested.enum" :key="ei" class="flex items-center gap-1">
                                <ElInput :model-value="ev" size="small" style="width: 80px" @update:model-value="(v: string) => nested.enum![ei] = v" />
                                <ElButton type="danger" link size="small" :icon="Trash2" @click="nested.enum!.splice(ei, 1)" />
                              </div>
                            </div>
                            <div class="flex items-center gap-2">
                              <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.defaultShort') }}</span>
                              <ElInput v-model="nested.default" size="small" style="width: 100px" :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.optional')" />
                            </div>
                          </div>
                        </div>
                        <!-- nested number/integer -->
                        <div v-if="nested.type === 'number' || nested.type === 'integer'" class="mt-2 border-t">
                          <button
                            type="button"
                            class="text-muted-foreground hover:text-foreground flex items-center gap-1 py-1 text-xs"
                            @click="toggleAdvanced(`nested-${index}-${childIndex}-${nestedIndex}`)"
                          >
                            <ChevronRight v-if="!advancedExpanded.has(`nested-${index}-${childIndex}-${nestedIndex}`)" class="size-3" />
                            <ChevronDown v-else class="size-3" />
                            {{ $t('ai-platform.workflow.editor.schemaConfigDialog.advancedConfig') }}
                          </button>
                          <div v-if="advancedExpanded.has(`nested-${index}-${childIndex}-${nestedIndex}`)" class="flex flex-wrap items-center gap-3 pb-2">
                            <div class="flex items-center gap-1">
                              <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.minShort') }}</span>
                              <ElInputNumber v-model="nested.minimum" size="small" style="width: 80px" />
                            </div>
                            <div class="flex items-center gap-1">
                              <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.maxShort') }}</span>
                              <ElInputNumber v-model="nested.maximum" size="small" style="width: 80px" />
                            </div>
                            <div class="flex items-center gap-1">
                              <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.defaultShort') }}</span>
                              <ElInputNumber v-model="nested.default" size="small" style="width: 80px" />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <!-- 嵌套 array -->
                    <div
                      v-if="child.type === 'array'"
                      class="mt-2 border-l-2 border-green-300 pl-3"
                    >
                      <div class="mb-1 flex items-center gap-2">
                        <span class="text-muted-foreground text-xs"
                          >{{ $t('ai-platform.workflow.editor.schemaConfigDialog.arrayItemType') }}</span
                        >
                        <ElSelect
                          :model-value="child.items?.type || 'string'"
                          size="small"
                          style="width: 120px"
                          @change="(val: string) => setArrayItemType(child, val)"
                        >
                          <ElOption
                            v-for="opt in fieldTypeOptions.filter(
                              (o) => o.value !== 'array',
                            )"
                            :key="opt.value"
                            :label="opt.label"
                            :value="opt.value"
                          />
                        </ElSelect>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- array 类型的元素定义 -->
              <div
                v-if="
                  field.type === 'array' &&
                  expandedNodes.has(getNodePath('', index))
                "
                class="border-x border-b bg-white p-3 dark:bg-gray-900"
              >
                <div class="mb-2 flex items-center gap-2">
                  <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.arrayItemType') }}</span>
                  <ElSelect
                    :model-value="field.items?.type || 'string'"
                    size="small"
                    style="width: 140px"
                    @change="(val: string) => setArrayItemType(field, val)"
                  >
                    <ElOption
                      v-for="opt in fieldTypeOptions.filter(
                        (o) => o.value !== 'array',
                      )"
                      :key="opt.value"
                      :label="opt.label"
                      :value="opt.value"
                    />
                  </ElSelect>
                </div>

                <!-- 如果数组元素是 object -->
                <div
                  v-if="field.items?.type === 'object'"
                  class="border-l-2 border-green-300 pl-3"
                >
                  <div class="mb-2 flex items-center justify-between">
                    <span class="text-muted-foreground text-xs"
                      >{{ $t('ai-platform.workflow.editor.schemaConfigDialog.objectPropertyDef') }}</span
                    >
                    <ElButton
                      type="primary"
                      link
                      size="small"
                      :icon="CirclePlus"
                      @click="
                        field.items!.properties = field.items!.properties || [];
                        field.items!.properties.push({
                          name: '',
                          type: 'string',
                          description: '',
                          required: false,
                        });
                      "
                    >
                      {{ $t('ai-platform.workflow.editor.schemaConfigDialog.addProperty') }}
                    </ElButton>
                  </div>

                  <div
                    v-for="(
                      itemProp, itemPropIndex
                    ) in field.items?.properties || []"
                    :key="itemPropIndex"
                    class="bg-muted/10 mb-1 rounded p-2"
                  >
                    <div class="flex items-center gap-2">
                      <ElInput
                        v-model="itemProp.name"
                        :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.fieldName')"
                        size="small"
                        style="width: 100px"
                      />
                      <ElSelect
                        :model-value="itemProp.type"
                        size="small"
                        style="width: 120px"
                        @change="(val: string) => handleTypeChange(itemProp, val)"
                      >
                        <ElOption
                          v-for="opt in fieldTypeOptions"
                          :key="opt.value"
                          :label="opt.label"
                          :value="opt.value"
                        />
                      </ElSelect>
                      <ElInput
                        v-model="itemProp.description"
                        :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.description')"
                        size="small"
                        class="flex-1"
                      />
                      <ElSwitch v-model="itemProp.required" size="small" />
                      <ElButton
                        type="danger"
                        link
                        :icon="Trash2"
                        size="small"
                        @click="removeField(field.items!.properties!, itemPropIndex)"
                      />
                    </div>
                    <!-- string 类型的额外配置 -->
                    <div v-if="itemProp.type === 'string'" class="mt-2 border-t">
                      <button
                        type="button"
                        class="text-muted-foreground hover:text-foreground flex items-center gap-1 py-1 text-xs"
                        @click="toggleAdvanced(`item-${index}-${itemPropIndex}`)"
                      >
                        <ChevronRight v-if="!advancedExpanded.has(`item-${index}-${itemPropIndex}`)" class="size-3" />
                        <ChevronDown v-else class="size-3" />
                        {{ $t('ai-platform.workflow.editor.schemaConfigDialog.advancedConfig') }}
                      </button>
                      <div v-if="advancedExpanded.has(`item-${index}-${itemPropIndex}`)" class="space-y-2 pb-2">
                        <div class="flex items-center gap-2">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.enumValuesShort') }}</span>
                          <ElButton type="primary" link size="small" @click="itemProp.enum = itemProp.enum || []; itemProp.enum.push('')">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.add') }}</ElButton>
                        </div>
                        <div v-if="itemProp.enum && itemProp.enum.length > 0" class="flex flex-wrap gap-1">
                          <div v-for="(ev, ei) in itemProp.enum" :key="ei" class="flex items-center gap-1">
                            <ElInput :model-value="ev" size="small" style="width: 80px" @update:model-value="(v: string) => itemProp.enum![ei] = v" />
                            <ElButton type="danger" link size="small" :icon="Trash2" @click="itemProp.enum!.splice(ei, 1)" />
                          </div>
                        </div>
                        <div class="flex items-center gap-2">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.defaultShort') }}</span>
                          <ElInput v-model="itemProp.default" size="small" style="width: 100px" :placeholder="$t('ai-platform.workflow.editor.schemaConfigDialog.optional')" />
                        </div>
                      </div>
                    </div>
                    <!-- number/integer 类型的额外配置 -->
                    <div v-if="itemProp.type === 'number' || itemProp.type === 'integer'" class="mt-2 border-t">
                      <button
                        type="button"
                        class="text-muted-foreground hover:text-foreground flex items-center gap-1 py-1 text-xs"
                        @click="toggleAdvanced(`item-${index}-${itemPropIndex}`)"
                      >
                        <ChevronRight v-if="!advancedExpanded.has(`item-${index}-${itemPropIndex}`)" class="size-3" />
                        <ChevronDown v-else class="size-3" />
                        {{ $t('ai-platform.workflow.editor.schemaConfigDialog.advancedConfig') }}
                      </button>
                      <div v-if="advancedExpanded.has(`item-${index}-${itemPropIndex}`)" class="flex flex-wrap items-center gap-3 pb-2">
                        <div class="flex items-center gap-1">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.minShort') }}</span>
                          <ElInputNumber v-model="itemProp.minimum" size="small" style="width: 80px" />
                        </div>
                        <div class="flex items-center gap-1">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.maxShort') }}</span>
                          <ElInputNumber v-model="itemProp.maximum" size="small" style="width: 80px" />
                        </div>
                        <div class="flex items-center gap-1">
                          <span class="text-muted-foreground text-xs">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.defaultShort') }}</span>
                          <ElInputNumber v-model="itemProp.default" size="small" style="width: 80px" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </div>
        </template>
      </div>

      <!-- 右侧：JSON 预览 -->
      <div class="w-[400px] h-[calc(100%-48px)] my-3">
        <div class="mb-3 font-medium">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.jsonPreview') }}</div>
        <pre
          class="bg-muted/30 overflow-auto rounded border p-3 text-xs h-full"
          >{{ JSON.stringify(previewSchema, null, 2) }}</pre
        >
      </div>
    </div>

    <template #footer>
      <div class="flex justify-end gap-2">
        <ElButton @click="handleCancel">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleConfirm">{{ $t('ai-platform.workflow.editor.schemaConfigDialog.confirm') }}</ElButton>
      </div>
    </template>
  </ZqDialog>
</template>

<style scoped>
.schema-field {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.schema-json-textarea),
:deep(.schema-json-textarea textarea) {
  height: 100%;
}

:deep(.schema-json-textarea textarea) {
  font-family:
    ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono',
    'Courier New', monospace;
  font-size: 12px;
  line-height: 1.6;
}
</style>
