<template>
  <a-card :bordered="false" class="content-card">
    <template #title>
      <a-space>
        <span>订单管理</span>
        <a-tag color="blue">共 {{ orders.length }} 个订单</a-tag>
      </a-space>
    </template>
    <template #extra>
      <a-button @click="loadOrders">
        <template #icon><icon-refresh /></template>
        刷新
      </a-button>
    </template>
    <a-table :columns="orderColumns" :data="orders" :pagination="{ pageSize: 8 }" :bordered="false">
      <template #status="{ record }">
        <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
      </template>
      <template #actions="{ record }">
        <a-space>
          <a-button size="mini" type="primary" shape="round" @click="openOrderModal(record)">修改</a-button>
          <a-button size="mini" v-if="record.status === 'REFUND_REQUESTED'" @click="auditRefund(record, true)">通过退款</a-button>
          <a-button size="mini" status="danger" v-if="record.status === 'REFUND_REQUESTED'" @click="auditRefund(record, false)">驳回退款</a-button>
          <a-button size="mini" v-if="record.status === 'SHIPPED' || record.status === 'PAID'" @click="auditShipment(record, true)">发货审核</a-button>
        </a-space>
      </template>
    </a-table>
  </a-card>

  <a-modal v-model:visible="orderModalVisible" title="修改订单" :ok-text="'保存'" cancel-text="取消" @ok="submitOrderModal">
    <a-form :model="orderForm" layout="vertical">
      <a-form-item label="订单状态">
        <a-select v-model="orderForm.status">
          <a-option value="PENDING_PAYMENT">待支付</a-option>
          <a-option value="PAID">已支付</a-option>
          <a-option value="SHIPPED">已发货</a-option>
          <a-option value="COMPLETED">已完成</a-option>
          <a-option value="REFUND_REQUESTED">退款中</a-option>
          <a-option value="REFUNDED">已退款</a-option>
          <a-option value="CANCELLED">已取消</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="物流信息">
        <a-input v-model="orderForm.logisticsInfo" placeholder="请输入物流信息" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { api } from '../../api'
import { IconRefresh } from '@arco-design/web-vue/es/icon'

const orders = ref([])
const orderModalVisible = ref(false)
const orderForm = reactive({ id: null, status: 'PAID', logisticsInfo: '' })

const orderColumns = [
  { title: '订单号', dataIndex: 'orderNo', width: 180 },
  { title: '金额', dataIndex: 'totalAmount', render: ({ record }) => `¥${record.totalAmount}`, width: 100 },
  { title: '状态', slotName: 'status', width: 100 },
  { title: '物流信息', dataIndex: 'logisticsInfo', ellipsis: true },
  { title: '下单时间', dataIndex: 'createdAt', render: ({ record }) => formatDate(record.createdAt), width: 160 },
  { title: '操作', slotName: 'actions', width: 280 }
]

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

const getStatusColor = (status) => {
  const colors = { 'PENDING_PAYMENT': 'orange', 'PAID': 'blue', 'SHIPPED': 'cyan', 'COMPLETED': 'green', 'REFUND_REQUESTED': 'orange', 'REFUNDED': 'purple', 'CANCELLED': 'gray' }
  return colors[status] || 'gray'
}

const getStatusText = (status) => {
  const texts = { 'PENDING_PAYMENT': '待支付', 'PAID': '已支付', 'SHIPPED': '已发货', 'COMPLETED': '已完成', 'REFUND_REQUESTED': '退款中', 'REFUNDED': '已退款', 'CANCELLED': '已取消' }
  return texts[status] || status
}

const loadOrders = async () => {
  orders.value = await api.adminOrders()
}

const openOrderModal = (row) => {
  orderForm.id = row.id
  orderForm.status = row.status
  orderForm.logisticsInfo = row.logisticsInfo || ''
  orderModalVisible.value = true
}

const submitOrderModal = async () => {
  await api.adminUpdateOrder(orderForm.id, { status: orderForm.status, logisticsInfo: orderForm.logisticsInfo })
  Message.success('订单已更新')
  orderModalVisible.value = false
  await loadOrders()
}

const auditRefund = async (row, approve) => {
  const remark = window.prompt(approve ? '请输入退款通过备注（可为空）' : '请输入驳回原因（可为空）', '') || ''
  await api.adminAuditRefund(row.id, { approve, remark })
  Message.success(approve ? '退款审核已通过' : '退款审核已驳回')
  await loadOrders()
}

const auditShipment = async (row, approve) => {
  const remark = window.prompt(approve ? '请输入发货审核备注（可为空）' : '请输入驳回原因（可为空）', '') || ''
  await api.adminAuditShipment(row.id, { approve, remark })
  Message.success(approve ? '发货审核已通过' : '发货审核已驳回')
  await loadOrders()
}

onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.content-card {
  border-radius: 12px;
}

:deep(.arco-btn-primary) {
  background: linear-gradient(135deg, #722ed1 0%, #9254de 100%);
  border-color: transparent;
}

:deep(.arco-card-header) {
  border-bottom: 1px solid #f0f0f0;
}
</style>
