<template>
  <a-card title="我的订单">
    <a-table :dataSource="orders" :columns="columns" rowKey="id">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          {{ statusMap[record.status] || record.status }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button type="link" @click="viewDetail(record)">详情</a-button>
          <a-button type="link" v-if="record.status === 'PENDING_PAYMENT'" @click="pay(record)">去支付</a-button>
        </template>
      </template>
    </a-table>
  </a-card>

  <a-modal v-model:open="detailVisible" title="订单详情" footer={null}>
    <a-descriptions bordered :column="1">
      <a-descriptions-item label="订单号">{{ detail.order?.orderNo }}</a-descriptions-item>
      <a-descriptions-item label="金额">￥{{ detail.order?.totalAmount }}</a-descriptions-item>
      <a-descriptions-item label="状态">{{ statusMap[detail.order?.status] }}</a-descriptions-item>
      <a-descriptions-item label="收货人">{{ detail.order?.receiverName }}</a-descriptions-item>
      <a-descriptions-item label="联系电话">{{ detail.order?.receiverPhone }}</a-descriptions-item>
      <a-descriptions-item label="地址">{{ detail.order?.receiverAddress }}</a-descriptions-item>
      <a-descriptions-item label="物流单号">{{ detail.order?.logisticsNo || '-' }}</a-descriptions-item>
    </a-descriptions>

    <a-table
      :dataSource="detail.items"
      :columns="itemColumns"
      rowKey="id"
      style="margin-top: 16px"
      size="small"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'product'">
          {{ record.product.name }}
        </template>
      </template>
    </a-table>
  </a-modal>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import api from '../../api'

const orders = ref([])
const detailVisible = ref(false)
const detail = ref({ order: null, items: [] })
const columns = [
  { title: '订单号', dataIndex: 'orderNo' },
  { title: '金额', dataIndex: 'totalAmount' },
  { title: '状态', key: 'status' },
  { title: '操作', key: 'action' }
]

const itemColumns = [
  { title: '商品', key: 'product' },
  { title: '数量', dataIndex: 'quantity' },
  { title: '单价', dataIndex: 'price' }
]

const statusMap = {
  PENDING_PAYMENT: '待付款',
  PENDING_SHIPMENT: '待发货',
  SHIPPED: '已发货',
  COMPLETED: '已完成'
}

const load = async () => {
  const res = await api.get('/api/user/orders')
  if (res.success) orders.value = res.data
}

const pay = async (record) => {
  await api.post(`/api/user/orders/${record.id}/pay`)
  load()
}

const viewDetail = async (record) => {
  const res = await api.get(`/api/user/orders/${record.id}`)
  if (res.success) {
    detail.value = res.data
    detailVisible.value = true
  }
}

onMounted(load)
</script>
