<template>
  <div class="payment-config">
    <el-alert title="密钥字段会由服务端脱敏。编辑时保留 ****** 可继续使用原密钥；保存前请先校验 JSON。" type="warning" :closable="false" class="mb-4" />
    <div class="kra-table-box">
      <div class="config-toolbar"><span>已配置 {{ configs.length }} 个支付渠道</span><el-button :loading="loading" icon="refresh" @click="load">刷新</el-button></div>
      <el-table v-loading="loading" :data="configs" row-key="provider" stripe>
        <el-table-column prop="provider" label="渠道" width="170" />
        <el-table-column label="启用" width="100"><template #default="scope"><el-switch v-model="scope.row.enabled" @change="save(scope.row)" /></template></el-table-column>
        <el-table-column label="配置 JSON" min-width="560"><template #default="scope"><el-input v-model="scope.row.editor" type="textarea" :rows="5" spellcheck="false" /></template></el-table-column>
        <el-table-column label="校验" width="100"><template #default="scope"><el-tag :type="scope.row.valid === false ? 'danger' : 'success'">{{ scope.row.valid === false ? '格式错误' : '可保存' }}</el-tag></template></el-table-column>
        <el-table-column label="操作" width="130"><template #default="scope"><el-button type="primary" link icon="check" @click="save(scope.row)">保存</el-button><el-button link @click="pretty(scope.row)">格式化</el-button></template></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getPaymentConfigs, savePaymentConfig } from '@/api/payment'

const configs = ref([]); const loading = ref(false)
const parseConfig = (row, notify = true) => { try { JSON.parse(row.editor || '{}'); row.valid = true; return true } catch { row.valid = false; if (notify) ElMessage.error(`${row.provider} 配置必须是合法 JSON`); return false } }
const load = async () => { loading.value = true; try { const res = await getPaymentConfigs(); if (res.code === 0) configs.value = (res.data || []).map((item) => ({ ...item, editor: JSON.stringify(item.config || {}, null, 2), valid: true })) } finally { loading.value = false } }
const pretty = (row) => { try { row.editor = JSON.stringify(JSON.parse(row.editor || '{}'), null, 2); row.valid = true } catch { parseConfig(row) } }
const save = async (row) => { if (!parseConfig(row)) return; const config = JSON.parse(row.editor || '{}'); const res = await savePaymentConfig({ provider: row.provider, enabled: row.enabled, config }); if (res.code === 0) { ElMessage.success(`${row.provider} 配置保存成功`); await load() } }
load()
</script>

<style scoped>
.config-toolbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; color: var(--el-text-color-secondary); }
.payment-config { min-width: 900px; }
</style>
