<template>
  <div class="pay007-orders-page">
    <div class="page-toolbar">
      <div class="title-block">
        <div class="title-icon">
          <el-icon><Money /></el-icon>
        </div>
        <div>
          <h2>007pay 订单</h2>
          <p>查看 007pay 平台订单、到账金额、手续费与手工入账记录</p>
        </div>
      </div>
      <div class="toolbar-actions">
        <el-button :loading="loading" @click="fetchOrders">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <div class="summary-grid">
      <div v-for="item in summaryCards" :key="item.label" class="summary-item" :class="item.accent">
        <div class="summary-label">{{ item.label }}</div>
        <div class="summary-value">{{ item.value }}</div>
        <div class="summary-sub">{{ item.sub }}</div>
      </div>
    </div>

    <div class="table-panel">
      <div class="filter-section">
        <el-form :inline="true" :model="queryParams" class="filter-form">
          <el-form-item label="订单号">
            <el-input
              v-model.trim="queryParams.order_no"
              placeholder="平台订单号/商户订单号"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="全部状态" clearable style="width: 140px">
              <el-option label="待支付" :value="0" />
              <el-option label="已支付" :value="1" />
              <el-option label="已关闭" :value="2" />
              <el-option label="已退款" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="loading"
        :data="orderList"
        row-key="trade_no"
        style="width: 100%"
        :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
      >
        <el-table-column label="平台订单号" min-width="190" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="mono">{{ row.trade_no || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商户订单号" min-width="190" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link
              v-if="row.out_trade_no"
              type="primary"
              :underline="false"
              class="mono"
              @click.stop="goToLocalOrder(row.out_trade_no)"
            >
              {{ row.out_trade_no }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="subject" label="订单标题" min-width="180" show-overflow-tooltip />
        <el-table-column label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" effect="plain">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">{{ formatCurrency(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手续费" width="120" align="right">
          <template #default="{ row }">
            <span>{{ formatCurrency(row.fee) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="净到账" width="120" align="right">
          <template #default="{ row }">
            <span class="net-text">{{ formatCurrency(getNetAmount(row)) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户端" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="row.client_type === 'mobile' ? 'success' : 'info'">
              {{ getClientText(row.client_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入账类型" width="110">
          <template #default="{ row }">
            <el-tag v-if="row.is_manual" size="small" type="warning" effect="dark">手工入账</el-tag>
            <el-tag v-else size="small" effect="plain">在线支付</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="channel_id" label="通道ID" width="90" />
        <el-table-column prop="channel_trade_no" label="通道订单号" min-width="170" show-overflow-tooltip />
        <el-table-column label="创建时间" width="170">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="支付时间" width="170">
          <template #default="{ row }">
            {{ formatDate(row.paid_at) }}
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.page_size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Money, Refresh, Search } from '@element-plus/icons-vue'
import { getPay007Orders } from '@/api/admin/pay007'

const router = useRouter()
const loading = ref(false)
const orderList = ref([])
const total = ref(0)

const queryParams = reactive({
  order_no: '',
  status: '',
  page: 1,
  page_size: 20
})

const centToYuan = (value) => (Number(value) || 0) / 100
const formatCurrency = (value) => `¥${centToYuan(value).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
const getNetAmount = (row) => (Number(row?.amount) || 0) - (Number(row?.fee) || 0)

const pageStats = computed(() => {
  return orderList.value.reduce((stats, row) => {
    const amount = Number(row.amount) || 0
    const fee = Number(row.fee) || 0
    stats.amount += amount
    stats.fee += fee
    stats.net += amount - fee
    if (Number(row.status) === 1) stats.paid += 1
    if (row.is_manual) stats.manual += 1
    return stats
  }, { amount: 0, fee: 0, net: 0, paid: 0, manual: 0 })
})

const summaryCards = computed(() => [
  {
    label: '平台订单',
    value: `${total.value} 单`,
    sub: `当前页 ${orderList.value.length} 单`,
    accent: 'blue'
  },
  {
    label: '当前页到账',
    value: formatCurrency(pageStats.value.amount),
    sub: `已支付 ${pageStats.value.paid} 单`,
    accent: 'green'
  },
  {
    label: '当前页手续费',
    value: formatCurrency(pageStats.value.fee),
    sub: `净到账 ${formatCurrency(pageStats.value.net)}`,
    accent: 'amber'
  },
  {
    label: '手工入账',
    value: `${pageStats.value.manual} 单`,
    sub: '由后台手动记账产生',
    accent: 'violet'
  }
])

const getStatusText = (status) => {
  const map = {
    0: '待支付',
    1: '已支付',
    2: '已关闭',
    3: '已退款'
  }
  return map[Number(status)] || '未知'
}

const getStatusType = (status) => {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'info',
    3: 'danger'
  }
  return map[Number(status)] || 'info'
}

const getClientText = (clientType) => {
  const map = {
    pc: 'PC',
    mobile: '移动端'
  }
  return map[clientType] || clientType || '-'
}

const formatDate = (value) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return value
  return date.toLocaleString('zh-CN', { hour12: false })
}

const buildParams = () => {
  const params = {
    page: queryParams.page,
    page_size: queryParams.page_size
  }
  if (queryParams.order_no) params.order_no = queryParams.order_no
  if (queryParams.status !== '' && queryParams.status !== null && queryParams.status !== undefined) {
    params.status = Number(queryParams.status)
  }
  return params
}

const fetchOrders = async () => {
  loading.value = true
  try {
    const res = await getPay007Orders(buildParams())
    if (res.data.code === 200) {
      const data = res.data.data || {}
      orderList.value = Array.isArray(data.list) ? data.list : []
      total.value = Number(data.total) || 0
    } else {
      ElMessage.error(res.data.message || '获取 007pay 订单失败')
    }
  } catch (error) {
    console.error('获取 007pay 订单失败:', error)
    ElMessage.error(error.response?.data?.message || '获取 007pay 订单失败')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.page = 1
  fetchOrders()
}

const resetQuery = () => {
  Object.assign(queryParams, {
    order_no: '',
    status: '',
    page: 1,
    page_size: 20
  })
  fetchOrders()
}

const handleSizeChange = (size) => {
  queryParams.page_size = size
  queryParams.page = 1
  fetchOrders()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchOrders()
}

const goToLocalOrder = (orderNo) => {
  router.push({ path: '/order/list', query: { key: orderNo } })
}

onMounted(fetchOrders)
</script>

<style scoped>
.pay007-orders-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.page-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  padding: 18px 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.title-block {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.title-icon {
  width: 42px;
  height: 42px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ecf5ff;
  color: #409eff;
  font-size: 22px;
  flex-shrink: 0;
}

.title-block h2 {
  margin: 0;
  color: #1f2d3d;
  font-size: 18px;
  font-weight: 600;
}

.title-block p {
  margin: 4px 0 0;
  color: #909399;
  font-size: 13px;
}

.toolbar-actions {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 12px;
}

.summary-item {
  position: relative;
  padding: 16px;
  min-height: 112px;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
}

.summary-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: #409eff;
}

.summary-item.green::before { background: #67c23a; }
.summary-item.amber::before { background: #e6a23c; }
.summary-item.violet::before { background: #8b5cf6; }

.summary-label {
  color: #909399;
  font-size: 12px;
  margin-bottom: 10px;
}

.summary-value {
  color: #1f2d3d;
  font-size: 24px;
  font-weight: 700;
  line-height: 1.2;
  word-break: break-all;
}

.summary-sub {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.table-panel {
  padding: 16px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
}

.filter-form {
  width: 100%;
}

.mono {
  font-family: Consolas, Monaco, monospace;
}

.amount-text {
  color: #409eff;
  font-weight: 600;
}

.net-text {
  color: #67c23a;
  font-weight: 700;
}

.pagination {
  margin-top: 18px;
  justify-content: flex-end;
}

@media (max-width: 1200px) {
  .summary-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 768px) {
  .page-toolbar {
    align-items: flex-start;
    flex-direction: column;
  }

  .toolbar-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .summary-grid {
    grid-template-columns: 1fr;
  }

  .table-panel {
    padding: 12px;
  }
}
</style>
