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

import { fetchAdminWalletLedger, type AdminWalletLedger } from '@/features/admin/api/adminWallet'
import { balanceTypeLabel, ledgerDirectionLabel } from '@/utils/statusLabels'
import { formatDateTime } from '@/utils/time'

const loading = ref(false)
const ledger = ref<AdminWalletLedger[]>([])
const currentPage = ref(1)
const currentPageSize = ref(20)
const total = ref(0)
const filters = reactive({
  user_id: '',
  order_id: '',
  biz_type: '',
})

const inAmount = computed(() =>
  ledger.value.filter((item) => item.direction === 'in').reduce((sum, item) => sum + Number(item.amount || 0), 0),
)
const outAmount = computed(() =>
  ledger.value.filter((item) => item.direction === 'out').reduce((sum, item) => sum + Number(item.amount || 0), 0),
)

onMounted(loadLedger)

async function loadLedger() {
  loading.value = true
  try {
    const query = {
      ...filters,
      page: currentPage.value,
      page_size: currentPageSize.value,
    }
    const result = await fetchAdminWalletLedger(query)
    ledger.value = result.items
    total.value = result.total
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  filters.user_id = ''
  filters.order_id = ''
  filters.biz_type = ''
  currentPage.value = 1
  void loadLedger()
}

function handleSizeChange() {
  currentPage.value = 1
  loadLedger()
}

function money(value: number) {
  return `¥${Math.round(Number(value || 0))}`
}

function directionType(direction: string) {
  if (direction === 'in') return 'success'
  if (direction === 'out') return 'danger'
  return 'warning'
}

function directionLabel(direction: string) {
  return ledgerDirectionLabel(direction)
}
</script>

<template>
  <section class="page">
    <div class="page-header-row">
      <div class="page-header">
        <p class="eyebrow">Wallet 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="loadLedger">查询</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>{{ money(inAmount) }}</strong>
      </div>
      <div class="metric-card">
        <span>出账合计</span>
        <strong>{{ money(outAmount) }}</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-select v-model="filters.biz_type" clearable placeholder="全部业务" class="full-control">
          <el-option label="订单冻结" value="order_freeze" />
          <el-option label="订单取消释放" value="order_cancel_release" />
          <el-option label="订单结算" value="order_settlement" />
          <el-option label="押金退回" value="deposit_refund" />
        </el-select>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" class="table-panel" :data="ledger">
      <el-table-column prop="ledger_no" label="流水号" min-width="230" />
      <el-table-column label="用户" min-width="130">
        <template #default="{ row }">
          <strong>{{ row.user_phone || `用户 ${row.user_id}` }}</strong>
        </template>
      </el-table-column>
      <el-table-column label="订单" min-width="160">
        <template #default="{ row }">
          <RouterLink v-if="row.order_id" :to="`/admin/orders/${row.order_id}`">{{ row.order_no || row.order_id }}</RouterLink>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="biz_type" label="业务类型" width="150" />
      <el-table-column label="方向" width="90">
        <template #default="{ row }">
          <el-tag :type="directionType(row.direction)">{{ directionLabel(row.direction) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="金额" width="110">
        <template #default="{ row }">{{ money(Number(row.amount)) }}</template>
      </el-table-column>
      <el-table-column label="余额类型" width="110">
        <template #default="{ row }">{{ balanceTypeLabel(row.balance_type) }}</template>
      </el-table-column>
      <el-table-column label="变化后余额" width="130">
        <template #default="{ row }">{{ money(Number(row.balance_after)) }}</template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="180">
        <template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
      </el-table-column>
    </el-table>

    <div class="pagination-wrap" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="currentPageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @current-change="loadLedger"
        @size-change="handleSizeChange"
      />
    </div>
  </section>
</template>
