<template>
  <div class="orders-page">
    <BackNav />
    <div class="table-card">
      <el-table :data="orders" style="width: 100%">
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="total_amount" :label="$t('order.totalAmount')" min-width="100">
          <template #default="{ row }">¥{{ row.total_amount }}</template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('order.status')" min-width="100">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">{{ statusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="160">
          <template #default="{ row }">{{ formatDate(row.created_at) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="$router.push(`/orders/${row.id}`)">查看</el-button>
            <el-button v-if="row.status === 'pending_payment'" link type="success" size="small" @click="goPay(row)">去支付</el-button>
            <el-button v-if="row.status === 'pending_payment' || row.status === 'pending_confirm'" link type="warning" size="small" @click="cancelOrder(row.id)">取消</el-button>
            <el-button v-if="row.status === 'shipped'" link type="success" size="small" @click="confirmReceipt(row.id)">确认收货</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderApi } from '../../api'
import BackNav from '../../components/BackNav.vue'

const router = useRouter()
const orders = ref<any[]>([])

const statusMap: Record<string, string> = {
  pending_payment: '待支付', pending_confirm: '待确认', pending_ship: '待发货',
  shipped: '已发货', completed: '已完成', refunding: '退款中', refunded: '已退款', cancelled: '已取消',
}
const statusTypeMap: Record<string, string> = {
  pending_payment: 'warning', pending_confirm: 'info', pending_ship: 'info',
  shipped: 'primary', completed: 'success', refunding: 'danger', refunded: 'danger', cancelled: 'info',
}
function statusText(s: string) { return statusMap[s] || s }
function statusType(s: string) { return statusTypeMap[s] || 'info' }

function formatDate(date: string) {
  if (!date) return '-'
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

async function fetchOrders() {
  try {
    const res: any = await orderApi.list()
    orders.value = res.data || []
  } catch {
    ElMessage.error('获取订单失败')
  }
}

function goPay(row: any) {
  router.push(`/checkout/${row.id}`)
}

async function cancelOrder(id: number) {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', { type: 'warning' })
    await orderApi.cancel(id)
    ElMessage.success('订单已取消')
    fetchOrders()
  } catch {}
}

async function confirmReceipt(id: number) {
  try {
    await ElMessageBox.confirm('确认已收到商品？', '提示', { type: 'info' })
    await orderApi.confirmReceipt(id)
    ElMessage.success('已确认收货')
    fetchOrders()
  } catch {}
}

onMounted(fetchOrders)
</script>

<style scoped lang="scss">
.orders-page { padding: 0; }
.table-card { background: #2d2d44; border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 20px; }

@media (max-width: 768px) {
  .table-card {
    padding: 12px;
    border-radius: 8px;
  }

  :deep(.el-table) {
    font-size: 12px;

    .el-table__cell {
      padding: 8px 4px;
    }

    .el-table__header th {
      padding: 8px 4px;
    }
  }

  :deep(.el-button) {
    padding: 4px 8px;
    font-size: 12px;
  }
}
</style>
