<template>
  <div class="payment-page">
    <div class="page-header">
      <el-button type="primary" @click="openAdd">添加通道</el-button>
    </div>
    <div class="table-card">
      <el-table :data="channels" style="width: 100%">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column label="图标" width="60">
          <template #default="{ row }">
            <span class="channel-icon" v-html="getIconSvg(row.icon || row.type)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="通道名称" min-width="120" />
        <el-table-column prop="code" label="通道代码" width="120" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag size="small">{{ getTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="费率" width="100">
          <template #default="{ row }">
            {{ (row.fee_rate * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column label="金额限制" width="160">
          <template #default="{ row }">
            {{ row.min_amount }} - {{ row.max_amount || '∞' }} 元
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_enabled ? 'success' : 'info'" size="small">
              {{ row.is_enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="60" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="editChannel(row)">编辑</el-button>
            <el-button link :type="row.is_enabled ? 'warning' : 'success'" size="small" @click="toggleChannel(row)">
              {{ row.is_enabled ? '禁用' : '启用' }}
            </el-button>
            <el-button link type="danger" size="small" @click="deleteChannel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="showAdd" :title="editing ? '编辑支付通道' : '添加支付通道'" width="600px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="通道名称" required>
          <el-input v-model="form.name" placeholder="如：支付宝" />
        </el-form-item>
        <el-form-item label="通道代码" required>
          <el-input v-model="form.code" placeholder="如：alipay" :disabled="!!editing" />
        </el-form-item>
        <el-form-item label="支付类型" required>
          <el-select v-model="form.type" placeholder="选择支付类型" @change="onTypeChange">
            <el-option v-for="t in channelTypes" :key="t.value" :label="t.label" :value="t.value">
              <span style="display:flex;align-items:center;gap:8px">
                <span v-html="t.icon"></span>
                <span>{{ t.label }}</span>
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <div class="icon-selector">
            <div
              v-for="ic in availableIcons"
              :key="ic.name"
              class="icon-option"
              :class="{ active: form.icon === ic.name }"
              @click="form.icon = ic.name"
              :title="ic.label"
              v-html="ic.svg"
            ></div>
          </div>
        </el-form-item>
        <el-form-item label="手续费率">
          <el-input-number v-model="form.fee_rate" :min="0" :max="1" :step="0.001" :precision="4" />
          <span style="margin-left: 10px; color: rgba(255,255,255,0.5)">{{ (form.fee_rate * 100).toFixed(2) }}%</span>
        </el-form-item>
        <el-form-item label="最小金额">
          <el-input-number v-model="form.min_amount" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="最大金额">
          <el-input-number v-model="form.max_amount" :min="0" :precision="2" />
        </el-form-item>

        <el-divider content-position="left">通道配置</el-divider>

        <template v-if="form.type === 'alipay'">
          <el-form-item label="AppID">
            <el-input v-model="channelConfig.alipay_app_id" placeholder="支付宝应用ID" />
          </el-form-item>
          <el-form-item label="应用私钥">
            <el-input v-model="channelConfig.alipay_private_key" type="textarea" :rows="3" placeholder="RSA2私钥" />
          </el-form-item>
          <el-form-item label="支付宝公钥">
            <el-input v-model="channelConfig.alipay_public_key" type="textarea" :rows="3" placeholder="支付宝公钥" />
          </el-form-item>
          <el-form-item label="回调地址">
            <el-input v-model="channelConfig.alipay_notify_url" placeholder="支付结果通知URL" />
          </el-form-item>
        </template>

        <template v-else-if="form.type === 'wechat'">
          <el-form-item label="AppID">
            <el-input v-model="channelConfig.wechat_app_id" placeholder="公众号/小程序AppID" />
          </el-form-item>
          <el-form-item label="商户号">
            <el-input v-model="channelConfig.wechat_mch_id" placeholder="微信支付商户号" />
          </el-form-item>
          <el-form-item label="API密钥">
            <el-input v-model="channelConfig.wechat_api_key" type="password" show-password placeholder="APIv2/v3密钥" />
          </el-form-item>
          <el-form-item label="回调地址">
            <el-input v-model="channelConfig.wechat_notify_url" placeholder="支付结果通知URL" />
          </el-form-item>
        </template>

        <template v-else-if="form.type === 'bepusdt'">
          <el-form-item label="API地址">
            <el-input v-model="channelConfig.bepusdt_api_url" placeholder="如：https://pay.example.com" />
          </el-form-item>
          <el-form-item label="API认证Token">
            <el-input v-model="channelConfig.bepusdt_api_token" type="password" show-password placeholder="conf.toml中的payment.api_token" />
          </el-form-item>
          <el-form-item label="交易类型">
            <el-select v-model="channelConfig.bepusdt_trade_type" placeholder="选择交易类型">
              <el-option label="USDT-TRC20" value="usdt.trc20" />
              <el-option label="USDT-ERC20" value="usdt.erc20" />
              <el-option label="USDT-BEP20" value="usdt.bep20" />
              <el-option label="USDC-TRC20" value="usdc.trc20" />
              <el-option label="USDC-ERC20" value="usdc.erc20" />
              <el-option label="USDC-BEP20" value="usdc.bep20" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单超时(秒)">
            <el-input-number v-model="channelConfig.bepusdt_timeout" :min="60" :max="3600" :step="60" />
          </el-form-item>
          <el-form-item label="汇率浮动">
            <el-input v-model="channelConfig.bepusdt_rate" placeholder="如：~1.02表示上浮2%，留空取配置汇率" />
          </el-form-item>
        </template>

        <template v-else-if="form.type === 'bank'">
          <el-form-item label="银行名称">
            <el-input v-model="channelConfig.bank_name" placeholder="如：中国工商银行" />
          </el-form-item>
          <el-form-item label="开户人">
            <el-input v-model="channelConfig.bank_account_name" placeholder="持卡人姓名" />
          </el-form-item>
          <el-form-item label="银行卡号">
            <el-input v-model="channelConfig.bank_account_number" placeholder="银行卡号" />
          </el-form-item>
          <el-form-item label="开户行">
            <el-input v-model="channelConfig.bank_branch" placeholder="开户支行" />
          </el-form-item>
        </template>

        <template v-else>
          <el-form-item label="配置信息">
            <el-input v-model="form.config" type="textarea" :rows="4" placeholder="JSON格式的配置信息" />
          </el-form-item>
        </template>

        <el-form-item label="排序">
          <el-input-number v-model="form.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch v-model="form.is_enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAdd = false">取消</el-button>
        <el-button type="primary" @click="saveChannel" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminApi } from '../../api'

const channels = ref<any[]>([])
const showAdd = ref(false)
const editing = ref<any>(null)
const saving = ref(false)

const form = reactive({
  name: '',
  code: '',
  type: 'alipay',
  icon: '',
  fee_rate: 0,
  min_amount: 0,
  max_amount: 0,
  config: '',
  is_enabled: true,
  sort_order: 0
})

const channelConfig = reactive<Record<string, string>>({})

const channelTypes = [
  { value: 'alipay', label: '支付宝', icon: '<svg viewBox="0 0 24 24" width="16" height="16" fill="#1677ff"><rect rx="4" width="24" height="24" fill="#1677ff"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="12" font-weight="bold">支</text></svg>' },
  { value: 'wechat', label: '微信支付', icon: '<svg viewBox="0 0 24 24" width="16" height="16"><rect rx="4" width="24" height="24" fill="#07c160"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="12" font-weight="bold">微</text></svg>' },
  { value: 'bepusdt', label: 'BepUsdt', icon: '<svg viewBox="0 0 24 24" width="16" height="16"><rect rx="4" width="24" height="24" fill="#26a17b"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="11" font-weight="bold">₮</text></svg>' },
  { value: 'bank', label: '银行卡', icon: '<svg viewBox="0 0 24 24" width="16" height="16"><rect rx="4" width="24" height="24" fill="#e6a23c"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="12" font-weight="bold">卡</text></svg>' },
  { value: 'other', label: '其他', icon: '<svg viewBox="0 0 24 24" width="16" height="16"><rect rx="4" width="24" height="24" fill="#909399"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="14" font-weight="bold">…</text></svg>' },
]

const typeNames: Record<string, string> = {}
channelTypes.forEach(t => { typeNames[t.value] = t.label })

const availableIcons = [
  { name: 'alipay', label: '支付宝', svg: '<svg viewBox="0 0 24 24" width="28" height="28"><rect rx="4" width="24" height="24" fill="#1677ff"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="12" font-weight="bold">支</text></svg>' },
  { name: 'wechat', label: '微信', svg: '<svg viewBox="0 0 24 24" width="28" height="28"><rect rx="4" width="24" height="24" fill="#07c160"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="12" font-weight="bold">微</text></svg>' },
  { name: 'usdt', label: 'USDT', svg: '<svg viewBox="0 0 24 24" width="28" height="28"><rect rx="4" width="24" height="24" fill="#26a17b"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="11" font-weight="bold">₮</text></svg>' },
  { name: 'bank', label: '银行卡', svg: '<svg viewBox="0 0 24 24" width="28" height="28"><rect rx="4" width="24" height="24" fill="#e6a23c"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="12" font-weight="bold">卡</text></svg>' },
  { name: 'visa', label: 'VISA', svg: '<svg viewBox="0 0 24 24" width="28" height="28"><rect rx="4" width="24" height="24" fill="#1a1f71"/><text x="12" y="16" text-anchor="middle" fill="#fff" font-size="8" font-weight="bold">VISA</text></svg>' },
  { name: 'mastercard', label: 'MasterCard', svg: '<svg viewBox="0 0 24 24" width="28" height="28"><rect rx="4" width="24" height="24" fill="#252525"/><circle cx="9" cy="12" r="6" fill="#eb001b" opacity="0.8"/><circle cx="15" cy="12" r="6" fill="#f79e1b" opacity="0.8"/></svg>' },
  { name: 'crypto', label: '加密货币', svg: '<svg viewBox="0 0 24 24" width="28" height="28"><rect rx="4" width="24" height="24" fill="#f7931a"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="14" font-weight="bold">₿</text></svg>' },
]

const iconSvgMap: Record<string, string> = {}
availableIcons.forEach(ic => { iconSvgMap[ic.name] = ic.svg })

function getIconSvg(icon: string) {
  return iconSvgMap[icon] || iconSvgMap[icon] || `<svg viewBox="0 0 24 24" width="28" height="28"><rect rx="4" width="24" height="24" fill="#909399"/><text x="12" y="17" text-anchor="middle" fill="#fff" font-size="12">?</text></svg>`
}

function getTypeName(type: string) {
  return typeNames[type] || type
}

function onTypeChange(type: string) {
  const iconMap: Record<string, string> = {
    alipay: 'alipay',
    wechat: 'wechat',
    bepusdt: 'usdt',
    bank: 'bank',
  }
  form.icon = iconMap[type] || ''
  Object.keys(channelConfig).forEach(k => delete channelConfig[k])
}

async function fetchChannels() {
  try {
    const res: any = await adminApi.getPaymentChannels()
    channels.value = res.data || []
  } catch (e) {
    console.error(e)
  }
}

function openAdd() {
  editing.value = null
  Object.assign(form, {
    name: '', code: '', type: 'alipay', icon: 'alipay',
    fee_rate: 0, min_amount: 0, max_amount: 0, config: '',
    is_enabled: true, sort_order: 0
  })
  Object.keys(channelConfig).forEach(k => delete channelConfig[k])
  showAdd.value = true
}

function editChannel(row: any) {
  editing.value = row
  Object.assign(form, {
    name: row.name, code: row.code, type: row.type, icon: row.icon || '',
    fee_rate: row.fee_rate || 0, min_amount: row.min_amount || 0, max_amount: row.max_amount || 0,
    config: row.config || '', is_enabled: row.is_enabled, sort_order: row.sort_order || 0
  })
  Object.keys(channelConfig).forEach(k => delete channelConfig[k])
  if (row.config) {
    try {
      const parsed = JSON.parse(row.config)
      Object.assign(channelConfig, parsed)
    } catch {}
  }
  showAdd.value = true
}

async function saveChannel() {
  if (!form.name || !form.code || !form.type) {
    ElMessage.warning('请填写必填项')
    return
  }
  saving.value = true
  try {
    const payload: any = { ...form }
    if (form.type !== 'other' && Object.keys(channelConfig).length > 0) {
      payload.config = JSON.stringify(channelConfig)
    }
    if (editing.value) {
      await adminApi.updatePaymentChannel(editing.value.id, payload)
    } else {
      await adminApi.createPaymentChannel(payload)
    }
    ElMessage.success('保存成功')
    showAdd.value = false
    editing.value = null
    await fetchChannels()
  } catch (error: any) {
    const msg = error.response?.data?.error || '保存失败'
    ElMessage.error(msg)
  } finally {
    saving.value = false
  }
}

async function toggleChannel(row: any) {
  try {
    await adminApi.togglePaymentChannel(row.id)
    ElMessage.success(row.is_enabled ? '已禁用' : '已启用')
    await fetchChannels()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '操作失败')
  }
}

async function deleteChannel(id: number) {
  await ElMessageBox.confirm('确定删除此支付通道？', '确认删除')
  await adminApi.deletePaymentChannel(id)
  ElMessage.success('删除成功')
  await fetchChannels()
}

onMounted(fetchChannels)
</script>

<style scoped lang="scss">
.payment-page { padding: 0; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.table-card { background: #2d2d44; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 20px; }

.channel-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
}

.icon-selector {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.icon-option {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid rgba(255, 255, 255, 0.08);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s;
  background: rgba(255, 255, 255, 0.03);

  &:hover {
    border-color: rgba(78, 110, 242, 0.4);
    background: rgba(78, 110, 242, 0.08);
  }

  &.active {
    border-color: #4e6ef2;
    background: rgba(78, 110, 242, 0.15);
  }
}

:deep(.el-table) {
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: rgba(255, 255, 255, 0.03);
  --el-table-row-hover-bg-color: rgba(255, 255, 255, 0.06);
  --el-table-border-color: rgba(255, 255, 255, 0.06);
  background: transparent;
}

:deep(.el-table th) {
  background: rgba(255, 255, 255, 0.03);
  color: rgba(255, 255, 255, 0.7);
  font-weight: 500;
}

:deep(.el-table td) {
  color: rgba(255, 255, 255, 0.9);
}

:deep(.el-tag) {
  background: rgba(78, 110, 242, 0.15);
  color: #4e6ef2;
  border: none;
}

:deep(.el-tag--success) {
  background: rgba(67, 207, 124, 0.15);
  color: #43cf7c;
}

:deep(.el-tag--warning) {
  background: rgba(230, 162, 60, 0.15);
  color: #e6a23c;
}

:deep(.el-tag--info) {
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.5);
}

:deep(.el-dialog) {
  background: #2d2d44;
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  padding: 16px 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: #fff;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: rgba(255, 255, 255, 0.5);
  &:hover { color: #fff; }
}

:deep(.el-dialog__footer) {
  border-top: 1px solid rgba(255, 255, 255, 0.06);
  padding: 16px 20px;
}

:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.7);
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner),
:deep(.el-select .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.08);
  box-shadow: none;
  &:hover, &:focus { border-color: #4e6ef2; }
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  color: #fff;
  &::placeholder { color: rgba(255, 255, 255, 0.3); }
}

:deep(.el-divider__text) {
  color: rgba(255, 255, 255, 0.6);
  background: #2d2d44;
}
</style>
