<template>
  <el-form :model="form" label-position="top" label-width="120px" :rules="rules" ref="formRef">
    <!-- 默认API地址 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item prop="defaultUrl" label="默认API地址">
          <el-input
              v-model="form.defaultUrl"
              placeholder="请输入默认API地址，如：https://api.openai.com/v1"
          />
          <div class="input-tips">用于连接服务器的API基础地址</div>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 拓展配置 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item prop="extraConfig" label="拓展配置">
          <el-input
              v-model="form.extraConfig"
              type="textarea"
              :rows="4"
              placeholder="请输入拓展配置，例如：{ timeout: 5000, proxy: 'xxx' }"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { computed } from 'vue'

// ================== 表单数据定义 ==================
const model = defineModel()

// 响应式表单代理，便于访问和修改
const form = computed({
  get: () => model.value,
  set: (value) => (model.value = value)
})

// ================== 表单验证规则 ==================
const rules = {
  defaultUrl: [
    { required: true, message: '请输入默认 API 地址', trigger: 'blur' },
    { type: 'url', message: '请输入合法的 URL 地址', trigger: 'blur' }
  ],
  extraConfig: [
    {
      validator: (_rule: any, value: string, callback: (error?: Error) => void) => {
        if (value && !isValidJSON(value)) {
          callback(new Error('拓展配置必须是合法的 JSON 字符串'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// ================== JSON 校验工具函数 ==================
function isValidJSON(str: string): boolean {
  try {
    JSON.parse(str)
    return true
  } catch {
    return false
  }
}

// ================== 表单引用（可用于后续提交或验证） ==================
const formRef = ref()
</script>

<style scoped lang="scss">
.input-tips {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style>
