<!--
  组件名称：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-divider v-if="form.authRequired" style="margin: 8px 0" />
      <template v-if="form.authRequired">
        <div class="credential-section-label" style="font-size: 13px; color: #909399; margin-bottom: 8px;">登录凭据（可选，留空使用默认值）</div>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="凭据名称">
              <el-input v-model="form.credentialName" placeholder="如：超级管理员" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登录用户名">
              <el-input v-model="form.loginUsername" placeholder="留空使用默认" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登录密码">
              <el-input v-model="form.loginPassword" type="password" show-password placeholder="留空使用默认" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 描述 -->
      <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
  credentialName: string
  loginUsername: string
  loginPassword: string
}

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

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'
    form.credentialName = p.credentialName || ''
    form.loginUsername = p.loginUsername || ''
    form.loginPassword = p.loginPassword || ''
  } 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,
      credentialName: form.credentialName || null,
      loginUsername: form.loginUsername || null,
      loginPassword: form.loginPassword || 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>