<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="80%" @close="handleDialogClose">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="api-form"
      :disabled="isDetailMode"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="接口名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入接口名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="接口Key" prop="apiKey">
            <el-input v-model="formData.apiKey" placeholder="自动生成" :disabled="isEditOrDetailMode" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="接口地址" prop="url">
            <el-input v-model="formData.url" placeholder="请输入接口地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="请求方式" prop="method">
            <el-select v-model="formData.method" placeholder="请选择请求方式" 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-option label="PATCH" value="PATCH" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="状态" prop="status" v-if="isDetailMode">
        <el-tag :type="statusConfig.type" size="large">
          {{ statusConfig.text }}
        </el-tag>
      </el-form-item>

      <el-form-item label="Header信息">
        <div class="json-editor">
          <el-input
            v-model="formData.headers"
            type="textarea"
            :rows="4"
            placeholder='请输入Header信息，JSON格式，例如：{"Content-Type": "application/json"}'
          />
        </div>
      </el-form-item>

      <el-form-item label="入参信息">
        <div class="json-editor">
          <el-input
            v-model="formData.requestParams"
            type="textarea"
            :rows="4"
            placeholder='请输入入参信息，JSON格式，例如：{"param1": "value1"}'
          />
        </div>
      </el-form-item>

      <el-form-item label="出参信息">
        <div class="json-editor">
          <el-input
            v-model="formData.responseParams"
            type="textarea"
            :rows="4"
            placeholder='请输入出参信息，JSON格式，例如：{"code": 200, "data": {}}'
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer v-if="!isDetailMode">
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button @click="handleSave" :loading="submitLoading">
          保存
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          提交
        </el-button>
      </div>
    </template>

    <template #footer v-else>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Dialog } from '@/components/Dialog'

interface ApiFormData {
  id?: number
  name: string
  apiKey: string
  url: string
  method: string
  headers: string
  requestParams: string
  responseParams: string
  status: 'draft' | 'active' | 'inactive'
}

interface Props {
  visible: boolean
  mode: 'add' | 'edit' | 'detail'
  data?: ApiFormData
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'success': [type: 'save' | 'submit', data: ApiFormData]
}>()

// 表单引用
const formRef = ref()

// 弹窗可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 弹窗标题
const dialogTitle = computed(() => {
  switch (props.mode) {
    case 'add':
      return '新增接口'
    case 'edit':
      return '编辑接口'
    case 'detail':
      return '接口详情'
    default:
      return '接口信息'
  }
})

// 是否为详情模式
const isDetailMode = computed(() => props.mode === 'detail')

// 是否为编辑或详情模式（Key不可编辑）
const isEditOrDetailMode = computed(() => props.mode === 'edit' || props.mode === 'detail')

// 状态配置
const statusConfig = computed(() => {
  const statusConfigMap: Record<string, { type: string; text: string }> = {
    draft: { type: 'info', text: '草稿' },
    active: { type: 'success', text: '生效' },
    inactive: { type: 'warning', text: '失效' }
  }
  return statusConfigMap[formData.status] || { type: 'info', text: '未知' }
})

// 提交加载状态
const submitLoading = ref(false)

// 表单数据
const formData = reactive<ApiFormData>({
  id: undefined,
  name: '',
  apiKey: '',
  url: '',
  method: 'GET',
  headers: '',
  requestParams: '',
  responseParams: '',
  status: 'draft'
})

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
  url: [{ required: true, message: '请输入接口地址', trigger: 'blur' }],
  method: [{ required: true, message: '请选择请求方式', trigger: 'change' }]
}

// 生成接口Key
const generateApiKey = () => {
  const timestamp = Date.now().toString(36)
  const random = Math.random().toString(36).substring(2, 7)
  return `API${timestamp.toUpperCase()}${random.toUpperCase()}`
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    name: '',
    apiKey: '',
    url: '',
    method: 'GET',
    headers: '',
    requestParams: '',
    responseParams: '',
    status: 'draft'
  })
  formRef.value?.clearValidate()
}

// 初始化表单数据
const initFormData = () => {
  resetForm()
  
  if (props.mode === 'add') {
    formData.apiKey = generateApiKey()
  } else if (props.data) {
    Object.assign(formData, props.data)
  }
}

// 保存表单（草稿状态）
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    formData.status = 'draft' // 保存为草稿状态

    emit('success', 'save', { ...formData })
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 提交表单（生效状态）
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    formData.status = 'active' // 提交为生效状态

    emit('success', 'submit', { ...formData })
    ElMessage.success('提交成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  resetForm()
}

// 监听弹窗显示变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initFormData()
  }
})
</script>

<style scoped>
.api-form {
  padding: 20px 0;
}

.json-editor {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  font-family: 'Courier New', monospace;
  resize: vertical;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 8px 16px;
  font-weight: 500;
}
</style>