<template>
  <div class="kra-table-box">
    <el-alert title="支付密钥只用于保存和调用渠道，列表接口会自动脱敏。提交 ****** 会保留原密钥。" type="warning" :closable="false" class="mb-4" />
    <el-table :data="configs" row-key="provider" stripe>
      <el-table-column prop="provider" label="渠道" width="160" />
      <el-table-column label="状态" width="110"><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="520"><template #default="scope"><el-input v-model="scope.row.editor" type="textarea" :rows="4" spellcheck="false" /></template></el-table-column>
      <el-table-column label="操作" width="110"><template #default="scope"><el-button type="primary" link icon="check" @click="save(scope.row)">保存</el-button></template></el-table-column>
    </el-table>
  </div>
</template>

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

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