<!--
  组件名称：ErpConfig.vue
  组件描述：安全测试 ERP 配置管理页面

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

<template>
  <div class="erp-config-page">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>ERP 配置</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="140px"
        label-position="right"
        style="max-width: 600px"
      >
        <el-form-item label="API Key" prop="api_key">
          <el-input
            v-model="form.api_key"
            type="password"
            show-password
            placeholder="请输入 ERP API 密钥"
            clearable
          />
        </el-form-item>

        <el-form-item label="Base URL" prop="base_url">
          <el-input
            v-model="form.base_url"
            placeholder="请输入 ERP 基础 URL"
            clearable
          />
        </el-form-item>

        <el-form-item label="测试单 ID" prop="developtesting_id">
          <el-input-number
            v-model="form.developtesting_id"
            :min="0"
            :max="999999"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="Type ID" prop="type_id">
          <el-input-number
            v-model="form.type_id"
            :min="0"
            :max="999"
            :step="1"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="图片 URL 前缀" prop="image_url_prefix">
          <el-input
            v-model="form.image_url_prefix"
            placeholder="请输入图片 URL 前缀"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="saving" @click="handleSave">
            {{ saving ? '保存中...' : '保存配置' }}
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
/**
 * 安全测试 ERP 配置管理页面
 *
 * 功能：
 * 1. 加载时自动获取当前 ERP 配置（从数据库 / 环境变量回退）
 * 2. 修改后保存到数据库，重启后持久化
 * 3. 与功能测试报告模块共用同一套 ERP 配置（erp_configs 表）
 */

import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { securityErpApi } from '@/api/securityErp'

// ==================== 类型定义 ====================

interface ErpConfigForm {
  api_key: string
  base_url: string
  developtesting_id: number
  type_id: number
  image_url_prefix: string
}

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

const formRef = ref()
const saving = ref(false)

const form = reactive<ErpConfigForm>({
  api_key: '',
  base_url: '',
  developtesting_id: 397,
  type_id: 2,
  image_url_prefix: '',
})

/** 原始数据快照，用于重置 */
let originalSnapshot = ''

// ==================== 表单校验规则 ====================

const rules = {
  api_key: [{ required: true, message: '请输入 ERP API 密钥', trigger: 'blur' }],
  base_url: [{ required: true, message: '请输入 ERP 基础 URL', trigger: 'blur' }],
}

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

/** 加载配置 */
async function loadConfig() {
  try {
    const res = await securityErpApi.getConfig()
    Object.assign(form, res)
    originalSnapshot = JSON.stringify(res)
  } catch (err: any) {
    ElMessage.error('加载 ERP 配置失败：' + (err?.message || '未知错误'))
  }
}

/** 保存配置 */
async function handleSave() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  saving.value = true
  try {
    await securityErpApi.updateConfig({
      api_key: form.api_key,
      base_url: form.base_url,
      developtesting_id: form.developtesting_id,
      type_id: form.type_id,
      image_url_prefix: form.image_url_prefix,
    })
    ElMessage.success('ERP 配置已保存')
    originalSnapshot = JSON.stringify({ ...form })
  } catch (err: any) {
    ElMessage.error('保存 ERP 配置失败：' + (err?.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

/** 重置表单到加载时的值 */
function handleReset() {
  const snapshot = JSON.parse(originalSnapshot)
  Object.assign(form, snapshot)
  formRef.value?.clearValidate()
}

// ==================== 生命周期 ====================

onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.erp-config-page {
  max-width: 800px;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
}
</style>