<script setup lang="ts">
import { Document, Search } from '@element-plus/icons-vue'
import { computed, onMounted, reactive, ref } from 'vue'

import { fetchAdminPayments, type AdminPayment } from '@/features/admin/api/adminPayments'
import { adminPath } from '@/shared/utils/adminPath'
import { formatCentWithSymbol } from '@/shared/utils/money'
import { formatDateTime } from '@/shared/utils/time'
import AdminTablePagination from '../components/AdminTablePagination.vue'

const loading = ref(false)
const payments = ref<AdminPayment[]>([])
const currentPage = ref(1)
const currentPageSize = ref(20)
const total = ref(0)
const detailVisible = ref(false)
const activePayment = ref<AdminPayment | null>(null)
const filters = reactive({
  user_id: '',
  order_id: '',
  order_no: '',
  biz_type: '',
  status: '',
  provider: '',
})

const payAmount = computed(() =>
  payments.value
    .filter(item => item.biz_type === 'order_pay' || item.biz_type === 'wallet_recharge')
    .reduce((sum, item) => sum + Number(item.amount_cent || 0), 0)
)
const refundAmount = computed(() =>
  payments.value
    .filter(item => item.biz_type.includes('refund'))
    .reduce((sum, item) => sum + Number(item.amount_cent || 0), 0)
)

onMounted(loadPayments)

async function loadPayments() {
  loading.value = true
  try {
    const result = await fetchAdminPayments({
      ...filters,
      page: currentPage.value,
      page_size: currentPageSize.value,
    })
    payments.value = result.items
    total.value = result.total
  } catch {
    payments.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  filters.user_id = ''
  filters.order_id = ''
  filters.order_no = ''
  filters.biz_type = ''
  filters.status = ''
  filters.provider = ''
  currentPage.value = 1
  void loadPayments()
}

async function handlePageChange() {
  await loadPayments()
}

function moneyCent(value: number) {
  return formatCentWithSymbol(value)
}

function paymentStatusType(status: string) {
  if (['paid', 'refunded'].includes(status)) return 'success'
  if (status === 'failed') return 'danger'
  if (['paying', 'refunding'].includes(status)) return 'warning'
  return 'info'
}

function paymentStatusLabel(status: string) {
  const map: Record<string, string> = {
    created: '已创建',
    paying: '支付中',
    paid: '已支付',
    refunding: '退款中',
    refunded: '已退款',
    failed: '失败',
    closed: '已关闭',
  }
  return map[status] || status
}

function bizTypeLabel(type: string) {
  const map: Record<string, string> = {
    order_pay: '订单支付',
    wallet_recharge: '钱包充值',
    cancel_refund: '取消退款',
    admin_close_refund: '客服关闭退款',
    admin_refund: '人工退款',
    checkout_refund: '结账退款',
    deposit_refund: '押金退款',
    rent_refund: '租金退款',
    arbitration_refund: '仲裁退款',
  }
  return map[type] || type
}

function openDetail(row: AdminPayment) {
  activePayment.value = row
  detailVisible.value = true
}

function jsonText(value: unknown) {
  if (!value) return '{}'
  try {
    return JSON.stringify(value, null, 2)
  } catch {
    return String(value)
  }
}
</script>

<template>
  <section class="page">
    <div class="page-header-row">
      <div class="page-header">
        <p class="eyebrow">Payment Ledger</p>
        <h1>支付流水</h1>
        <p>查看第三方支付、退款请求、渠道单号、状态和失败原因。</p>
      </div>
      <div class="toolbar-actions">
        <el-button @click="resetFilters">重置</el-button>
        <el-button type="primary" :icon="Search" :loading="loading" @click="loadPayments"
          >查询</el-button
        >
      </div>
    </div>

    <div class="metric-grid">
      <div class="metric-card">
        <span>总条数</span>
        <strong>{{ total }} 笔</strong>
      </div>
      <div class="metric-card">
        <span>本页支付额</span>
        <strong>{{ moneyCent(payAmount) }}</strong>
      </div>
      <div class="metric-card">
        <span>本页退款额</span>
        <strong>{{ moneyCent(refundAmount) }}</strong>
      </div>
    </div>

    <el-form class="filter-panel" label-position="top">
      <el-form-item label="用户 ID">
        <el-input v-model="filters.user_id" clearable placeholder="按用户筛选" />
      </el-form-item>
      <el-form-item label="订单 ID">
        <el-input v-model="filters.order_id" clearable placeholder="按订单筛选" />
      </el-form-item>
      <el-form-item label="订单号">
        <el-input v-model="filters.order_no" clearable placeholder="按订单号筛选" />
      </el-form-item>
      <el-form-item label="业务类型">
        <el-select v-model="filters.biz_type" clearable placeholder="全部业务" class="full-control">
          <el-option label="订单支付" value="order_pay" />
          <el-option label="结账退款" value="checkout_refund" />
          <el-option label="仲裁退款" value="arbitration_refund" />
          <el-option label="人工退款" value="admin_refund" />
          <el-option label="取消退款" value="cancel_refund" />
          <el-option label="钱包充值" value="wallet_recharge" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filters.status" clearable placeholder="全部状态" class="full-control">
          <el-option label="已支付" value="paid" />
          <el-option label="支付中" value="paying" />
          <el-option label="退款中" value="refunding" />
          <el-option label="已退款" value="refunded" />
          <el-option label="失败" value="failed" />
        </el-select>
      </el-form-item>
      <el-form-item label="渠道">
        <el-select v-model="filters.provider" clearable placeholder="全部渠道" class="full-control">
          <el-option label="拉卡拉" value="lakala" />
          <el-option label="乐刷" value="leshua" />
          <el-option label="Mock" value="mock" />
        </el-select>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" class="table-panel" :data="payments">
      <el-table-column prop="payment_no" label="支付单号" min-width="220" />
      <el-table-column label="订单" min-width="180">
        <template #default="{ row }">
          <RouterLink v-if="row.order_id" :to="adminPath(`orders/${row.order_id}`)">{{
            row.order_no || row.order_id
          }}</RouterLink>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="用户" min-width="130">
        <template #default="{ row }">{{ row.user_phone || `用户 ${row.user_id}` }}</template>
      </el-table-column>
      <el-table-column label="业务" width="120">
        <template #default="{ row }">{{ bizTypeLabel(row.biz_type) }}</template>
      </el-table-column>
      <el-table-column label="渠道" width="90">
        <template #default="{ row }">{{ row.provider || '-' }}</template>
      </el-table-column>
      <el-table-column label="金额" width="110">
        <template #default="{ row }">{{ moneyCent(row.amount_cent) }}</template>
      </el-table-column>
      <el-table-column label="状态" width="110">
        <template #default="{ row }">
          <el-tag :type="paymentStatusType(row.status)">{{
            paymentStatusLabel(row.status)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="失败原因" min-width="180">
        <template #default="{ row }">
          <span v-if="row.status === 'failed' && row.error_message"
            >{{ row.error_code }} {{ row.error_message }}</span
          >
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="third_order_id" label="平台单号" min-width="230" />
      <el-table-column prop="provider_order_id" label="渠道单号" min-width="220" />
      <el-table-column label="创建时间" min-width="180">
        <template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
      </el-table-column>
      <el-table-column label="操作" width="90" fixed="right">
        <template #default="{ row }">
          <el-button size="small" :icon="Document" @click="openDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <AdminTablePagination
      v-if="total > 0"
      v-model:current-page="currentPage"
      v-model:page-size="currentPageSize"
      :total="total"
      :loading="loading"
      @page-change="handlePageChange"
    />

    <el-dialog v-model="detailVisible" title="支付流水详情" width="820px">
      <div v-if="activePayment" class="payment-detail">
        <div class="detail-grid">
          <p>
            <span>业务类型</span><strong>{{ bizTypeLabel(activePayment.biz_type) }}</strong>
          </p>
          <p>
            <span>状态</span><strong>{{ paymentStatusLabel(activePayment.status) }}</strong>
          </p>
          <p>
            <span>金额</span><strong>{{ moneyCent(activePayment.amount_cent) }}</strong>
          </p>
          <p>
            <span>渠道</span><strong>{{ activePayment.provider || '-' }}</strong>
          </p>
        </div>
        <h3>请求参数</h3>
        <pre>{{ jsonText(activePayment.raw_request) }}</pre>
        <h3>响应结果</h3>
        <pre>{{ jsonText(activePayment.raw_response) }}</pre>
      </div>
    </el-dialog>
  </section>
</template>

<style scoped>
.payment-detail h3 {
  margin: 18px 0 8px;
  font-size: 15px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 10px;
}

.detail-grid p {
  margin: 0;
  padding: 10px 12px;
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.detail-grid span {
  display: block;
  color: #64748b;
  font-size: 12px;
}

.detail-grid strong {
  display: block;
  margin-top: 4px;
}

pre {
  max-height: 260px;
  overflow: auto;
  margin: 0;
  padding: 12px;
  background: #0f172a;
  color: #e2e8f0;
  border-radius: 8px;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
