<!--
  组件名称：ApiPresetDialog.vue
  组件描述：API 接口预设编辑对话框，支持创建/编辑预设

  @author czj
  @date 2026-08-13
-->

<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑接口预设' : '新建接口预设'"
    width="680px"
    top="3vh"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-position="top" :rules="formRules">
      <!-- 基本信息 -->
      <el-row :gutter="16">
        <el-col :span="16">
          <el-form-item label="预设名称" prop="name">
            <el-input v-model="form.name" placeholder="例如：新建会议V3" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="HTTP 方法" prop="method">
            <el-select v-model="form.method" style="width: 100%">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="DELETE" value="DELETE" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="目标 URL" prop="targetUrl">
        <el-input v-model="form.targetUrl" placeholder="https://192.168.5.44/platform/api/..." />
      </el-form-item>

      <!-- 请求头与请求体 -->
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="请求头(JSON)" prop="headers">
            <el-input
              v-model="form.headers"
              type="textarea"
              :rows="3"
              placeholder='{"Content-Type": "application/json"}'
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="请求体类型">
            <el-radio-group v-model="form.bodyType">
              <el-radio value="static">静态</el-radio>
              <el-radio value="template">模板</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item v-if="form.bodyType === 'static'" label="请求体(JSON)" prop="body">
            <el-input
              v-model="form.body"
              type="textarea"
              :rows="4"
              placeholder='{"key": "value"}'
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.bodyType === 'template'" label="请求体模板" prop="bodyTemplate">
            <el-input
              v-model="form.bodyTemplate"
              type="textarea"
              :rows="4"
              placeholder='{"__NOW__": "datetime", "name": "会议名称"}'
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 认证配置 -->
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="需要登录认证">
            <el-switch v-model="form.authRequired" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="请求需要签名">
            <el-switch v-model="form.signRequest" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="form.authRequired" label="账号" prop="accountKey">
            <el-select v-model="form.accountKey" style="width: 100%">
              <el-option label="超级管理员" value="superadmin" />
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 描述 -->
      <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" :rows="2" placeholder="预设描述（可选）" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="saving" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * API 接口预设编辑对话框
 *
 * 功能：创建/编辑接口预设，包含接口配置、认证配置等字段
 */

import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { createPreset, updatePreset } from '@/api/performance'
import type { ApiPreset } from '@/types/performance'

// ==================== Props & Emits ====================

const props = defineProps<{
  modelValue: boolean
  preset?: ApiPreset | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', val: boolean): void
  (e: 'saved'): void
}>()

// ==================== 响应式数据 ====================

const visible = ref(props.modelValue)
const isEdit = ref(false)
const saving = ref(false)
const formRef = ref()

interface PresetForm {
  name: string
  description: string
  method: string
  targetUrl: string
  headers: string
  bodyType: 'static' | 'template'
  body: string
  bodyTemplate: string
  authRequired: boolean
  signRequest: boolean
  accountKey: string
}

const defaultForm = (): PresetForm => ({
  name: '',
  description: '',
  method: 'GET',
  targetUrl: '',
  headers: '',
  bodyType: 'static',
  body: '',
  bodyTemplate: '',
  authRequired: true,
  signRequest: false,
  accountKey: 'superadmin',
})

const form = reactive<PresetForm>(defaultForm())

const formRules = {
  name: [{ required: true, message: '请输入预设名称', trigger: 'blur' }],
  targetUrl: [{ required: true, message: '请输入目标 URL', trigger: 'blur' }],
  method: [{ required: true, message: '请选择 HTTP 方法', trigger: 'change' }],
}

// ==================== 监听 modelValue ====================

watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    initForm()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// ==================== 方法 ====================

/** 初始化表单：编辑时填充预设值，新建时重置 */
function initForm() {
  if (props.preset) {
    isEdit.value = true
    const p = props.preset
    form.name = p.name
    form.description = p.description || ''
    form.method = p.method
    form.targetUrl = p.targetUrl
    form.headers = p.headers ? JSON.stringify(p.headers, null, 2) : ''
    if (p.bodyTemplate) {
      form.bodyType = 'template'
      form.bodyTemplate = typeof p.bodyTemplate === 'string' ? p.bodyTemplate : JSON.stringify(p.bodyTemplate, null, 2)
      form.body = ''
    } else {
      form.bodyType = 'static'
      form.body = p.body ? (typeof p.body === 'string' ? p.body : JSON.stringify(p.body, null, 2)) : ''
      form.bodyTemplate = ''
    }
    form.authRequired = p.authRequired
    form.signRequest = p.signRequest
    form.accountKey = p.accountKey || 'superadmin'
  } else {
    isEdit.value = false
    Object.assign(form, defaultForm())
  }
}

/** 关闭弹窗 */
function handleClose() {
  visible.value = false
}

/** 保存 */
async function handleSave() {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  saving.value = true
  try {
    const data: any = {
      name: form.name,
      description: form.description || '',
      method: form.method,
      targetUrl: form.targetUrl,
      headers: form.headers ? JSON.parse(form.headers) : {},
      authRequired: form.authRequired,
      signRequest: form.signRequest,
      accountKey: form.authRequired ? form.accountKey : null,
    }

    if (form.bodyType === 'static' && form.body) {
      data.body = JSON.parse(form.body)
      data.bodyTemplate = null
    } else if (form.bodyType === 'template' && form.bodyTemplate) {
      data.bodyTemplate = JSON.parse(form.bodyTemplate)
      data.body = null
    }

    if (isEdit.value && props.preset) {
      await updatePreset(props.preset.id, data)
      ElMessage.success('预设已更新')
    } else {
      await createPreset(data)
      ElMessage.success('预设已创建')
    }

    visible.value = false
    emit('saved')
  } catch (e: any) {
    ElMessage.error('保存失败: ' + (e.response?.data?.detail || e.message || ''))
  } finally {
    saving.value = false
  }
}
</script>