<template>
  <a-card title="订单管理">
    <a-table :dataSource="orders" :columns="columns" rowKey="id">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-select v-model:value="record.status" style="width: 120px" @change="val => updateStatus(record, val)">
            <a-select-option value="PENDING_PAYMENT">待付款</a-select-option>
            <a-select-option value="PENDING_SHIPMENT">待发货</a-select-option>
            <a-select-option value="SHIPPED">已发货</a-select-option>
            <a-select-option value="COMPLETED">已完成</a-select-option>
          </a-select>
        </template>
        <template v-else-if="column.key === 'logistics'">
          <a-input v-model:value="record.logisticsNo" @blur="saveLogistics(record)" />
        </template>
      </template>
    </a-table>
  </a-card>
</template>

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

const orders = ref([])
const columns = [
  { title: '订单号', dataIndex: 'orderNo' },
  { title: '金额', dataIndex: 'totalAmount' },
  { title: '状态', key: 'status' },
  { title: '物流单号', key: 'logistics' }
]

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

const updateStatus = async (record, val) => {
  await api.put('/api/admin/orders/status', { orderId: record.id, status: val, logisticsNo: record.logisticsNo })
}

const saveLogistics = async (record) => {
  await api.put('/api/admin/orders/status', { orderId: record.id, status: record.status, logisticsNo: record.logisticsNo })
}

onMounted(load)
</script>
