<script setup lang="ts">
import { ref, watch } from 'vue'
import { Modal, Form, Input, Select, Switch, InputNumber, message } from 'ant-design-vue'

interface Parameter {
  id: string
  name: string
  type: string
  defaultValue?: any
  description?: string
  required?: boolean
}

interface Props {
  visible: boolean
  parameter: Parameter | null
  isInput: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(['update:visible', 'save', 'cancel'])

// 表单数据
const formData = ref<Parameter>({
  id: '',
  name: '',
  type: 'string',
  defaultValue: undefined,
  description: '',
  required: false
})

// 参数类型选项
const typeOptions = [
  { label: 'String (文本)', value: 'string' },
  { label: 'Number (数字)', value: 'number' },
  { label: 'Boolean (布尔)', value: 'boolean' },
  { label: 'Object (对象)', value: 'object' },
  { label: 'Array (数组)', value: 'array' },
  { label: 'Any (任意)', value: 'any' },
  { label: 'File (文件)', value: 'file' },
  { label: 'JSON (JSON)', value: 'json' }
]

// 监听参数变化
watch(() => props.parameter, (newParam) => {
  if (newParam) {
    formData.value = { ...newParam }
  } else {
    formData.value = {
      id: `param_${Date.now()}`,
      name: '',
      type: 'string',
      defaultValue: undefined,
      description: '',
      required: false
    }
  }
}, { immediate: true })

// 关闭弹窗
function handleCancel() {
  emit('update:visible', false)
  emit('cancel')
}

// 保存参数
function handleSave() {
  if (!formData.value.name.trim()) {
    message.error('参数名称不能为空')
    return
  }
  
  // 验证参数名称格式
  if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(formData.value.name)) {
    message.error('参数名称只能包含字母、数字和下划线，且不能以数字开头')
    return
  }
  
  emit('save', { ...formData.value })
  emit('update:visible', false)
}

// 获取默认值占位符
function getDefaultValuePlaceholder() {
  switch (formData.value.type) {
    case 'string':
      return '输入默认文本值'
    case 'number':
      return '输入默认数字值'
    case 'object':
      return '{"key": "value"}'
    case 'array':
      return '["item1", "item2"]'
    case 'json':
      return '{"data": {}}'
    case 'file':
      return '文件路径或URL'
    default:
      return '输入默认值'
  }
}
</script>

<template>
  <Modal
    :open="visible"
    :title="`${parameter ? '编辑' : '添加'}${isInput ? '输入' : '输出'}参数`"
    width="600px"
    @ok="handleSave"
    @cancel="handleCancel"
  >
    <Form layout="vertical" style="margin-top: 16px;">
      <Form.Item label="参数名称" required>
        <Input 
          v-model:value="formData.name" 
          placeholder="请输入参数名称（如：user_name, file_data）"
        />
        <div style="font-size: 11px; color: #999; margin-top: 4px;">
          只能包含字母、数字和下划线，且不能以数字开头
        </div>
      </Form.Item>
      
      <Form.Item label="参数类型" required>
        <Select 
          v-model:value="formData.type" 
          :options="typeOptions"
          placeholder="选择参数类型"
        />
      </Form.Item>
      
      <Form.Item label="参数描述">
        <Input.TextArea 
          v-model:value="formData.description" 
          placeholder="描述此参数的用途和含义"
          :rows="3"
        />
      </Form.Item>
      
      <Form.Item v-if="isInput" label="是否必需">
        <Switch 
          v-model:checked="formData.required" 
          checked-children="必需" 
          un-checked-children="可选"
        />
      </Form.Item>
      
      <Form.Item label="默认值">
        <!-- 数字类型 -->
        <InputNumber 
          v-if="formData.type === 'number'"
          v-model:value="formData.defaultValue"
          :placeholder="getDefaultValuePlaceholder()"
          style="width: 100%;"
        />
        
        <!-- 布尔类型 -->
        <Switch 
          v-else-if="formData.type === 'boolean'"
          v-model:checked="formData.defaultValue"
          checked-children="True" 
          un-checked-children="False"
        />
        
        <!-- 对象/数组/JSON类型 -->
        <Input.TextArea
          v-else-if="['object', 'array', 'json'].includes(formData.type)"
          v-model:value="formData.defaultValue"
          :placeholder="getDefaultValuePlaceholder()"
          :rows="4"
        />
        
        <!-- 其他类型 -->
        <Input 
          v-else
          v-model:value="formData.defaultValue"
          :placeholder="getDefaultValuePlaceholder()"
        />
        
        <div style="font-size: 11px; color: #999; margin-top: 4px;">
          <span v-if="formData.type === 'object'">输入有效的JSON对象格式</span>
          <span v-else-if="formData.type === 'array'">输入有效的JSON数组格式</span>
          <span v-else-if="formData.type === 'json'">输入有效的JSON格式</span>
          <span v-else>此参数的默认值（可选）</span>
        </div>
      </Form.Item>
    </Form>
    
    <div style="padding: 12px; background: #f8f9fa; border-radius: 4px; margin-top: 16px;">
      <div style="font-size: 12px; font-weight: 600; margin-bottom: 8px; color: #333;">
        参数预览
      </div>
      <div style="font-size: 11px; color: #666; line-height: 1.4;">
        <div><strong>名称:</strong> {{ formData.name || '(未设置)' }}</div>
        <div><strong>类型:</strong> {{ formData.type }}</div>
        <div v-if="formData.description"><strong>描述:</strong> {{ formData.description }}</div>
        <div v-if="isInput"><strong>必需:</strong> {{ formData.required ? '是' : '否' }}</div>
        <div v-if="formData.defaultValue !== undefined"><strong>默认值:</strong> {{ formData.defaultValue }}</div>
      </div>
    </div>
  </Modal>
</template>