<template>
  <div class="orders-container">
    <div class="orders-header">
      <div class="header-left">
        <a-avatar :size="48" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
          <icon-file :size="24" />
        </a-avatar>
        <div class="header-title">
          <h1>我的订单</h1>
          <span class="order-count">共 {{ orders.length }} 个订单</span>
        </div>
      </div>
      <div class="header-actions">
        <a-button shape="round" @click="goProducts">
          <template #icon><icon-apps /></template>
          继续购物
        </a-button>
        <a-button shape="round" @click="goCart">
          <template #icon><icon-apps /></template>
          购物车
        </a-button>
        <a-button shape="round" @click="loadOrders">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </div>
    </div>

    <a-card :bordered="false" class="orders-content">
      <a-empty v-if="orders.length === 0" description="暂无订单记录">
        <template #image>
          <icon-file :size="80" style="color: #e0e0e0" />
        </template>
        <a-button type="primary" shape="round" @click="goProducts">去下单</a-button>
      </a-empty>

      <div v-else class="orders-list">
        <div v-for="order in orders" :key="order.id" class="order-card">
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单号：{{ order.orderNo }}</span>
              <span class="order-date">{{ formatDate(order.createdAt) }}</span>
            </div>
            <a-tag :color="getStatusColor(order.status)" size="large">{{ getStatusText(order.status) }}</a-tag>
          </div>

          <div class="order-items">
            <div v-if="order.items && order.items.length > 0" class="order-items-list">
              <div v-for="item in order.items" :key="item.id" class="order-item">
                <img :src="item.productImage || 'https://via.placeholder.com/60x60?text=商品'" class="item-image" alt="商品图片">
                <div class="item-details">
                  <div class="item-name">{{ item.productName }}</div>
                  <div class="item-meta">
                    <span class="item-quantity">x{{ item.quantity }}</span>
                    <span class="item-price">¥{{ item.unitPrice }}</span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="order-item-preview">
              <span class="item-label">商品信息</span>
              <span class="item-value">暂无商品信息</span>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-address">
              <icon-location :size="16" />
              <span>{{ order.address }}</span>
            </div>
            <div class="order-total">
              <span class="total-label">实付金额</span>
              <span class="total-value">¥{{ order.totalAmount }}</span>
            </div>
            <div class="order-actions">
              <a-space>
                <a-button size="small" shape="round" @click="openLogistics(order.id)">
                  <template #icon><icon-send /></template>
                  物流
                </a-button>
                <a-button size="small" shape="round" @click="openAddress(order)" v-if="canModifyAddress(order.status)">
                  <template #icon><icon-edit /></template>
                  修改地址
                </a-button>
                <a-button size="small" shape="round" type="primary" @click="openReview(order.id)" v-if="canReview(order.status)">
                  <template #icon><icon-message /></template>
                  评价
                </a-button>
                <a-button size="small" shape="round" status="warning" @click="refund(order.id)" v-if="canRefund(order.status)">
                  <template #icon><icon-history /></template>
                  退款
                </a-button>
                <a-popconfirm content="确定删除此订单吗？" @ok="deleteOrder(order.id)">
                  <a-button size="small" shape="round" status="danger">
                    <template #icon><icon-delete /></template>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </div>
          </div>
        </div>
      </div>
    </a-card>

    <a-modal v-model:visible="addressModalVisible" title="修改收货地址" :ok-text="'保存'" cancel-text="取消" @ok="submitAddress">
      <a-form :model="addressForm" layout="vertical">
        <a-form-item label="收货地址">
          <a-input v-model="addressForm.address" placeholder="请输入详细的收货地址" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="logisticsModalVisible" title="物流跟踪" :footer="null" width="600">
      <a-timeline v-if="logistics.length > 0">
        <a-timeline-item v-for="(log, index) in logistics" :key="index" :color="index === 0 ? 'green' : 'gray'">
          <div class="log-item">
            <div class="log-status">{{ log.status }}</div>
            <div class="log-note">{{ log.note }}</div>
            <div class="log-time">{{ log.createdAt }}</div>
          </div>
        </a-timeline-item>
      </a-timeline>
      <a-empty v-else description="暂无物流信息" />
    </a-modal>

    <a-modal v-model:visible="reviewModalVisible" title="发表评价" :ok-text="'提交评价'" cancel-text="取消" @ok="submitReview">
      <a-form :model="reviewForm" layout="vertical">
        <a-form-item label="选择商品">
          <a-select v-model="reviewForm.productId" placeholder="请选择要评价的商品">
            <a-option v-for="item in orderItems" :key="item.productId" :value="item.productId">
              <template #icon><icon-thumb-up /></template>
              {{ item.productName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="评分">
          <div class="rating-section">
            <a-rate v-model="reviewForm.rating" :count="5" />
            <span class="rating-text">{{ ratingText }}</span>
          </div>
        </a-form-item>
        <a-form-item label="评价内容">
          <a-textarea v-model="reviewForm.content" placeholder="请分享您的使用体验..." :rows="4" show-word-limit :max-length="500" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { api } from '../api'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()
const orders = ref([])

const goProducts = () => router.push('/products')
const goCart = () => router.push('/cart')

const loadOrders = async () => {
  const orderList = await api.customerOrders()
  // 为每个订单加载商品详情
  for (const order of orderList) {
    try {
      const items = await api.orderItems(order.id)
      order.items = items
    } catch (e) {
      console.error('加载订单商品失败:', order.id, e)
      order.items = []
    }
  }
  orders.value = orderList
}

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 canModifyAddress = (status) => {
  return ['PENDING_PAYMENT', 'PAID'].includes(status)
}

const canReview = (status) => {
  return ['PAID', 'SHIPPED', 'COMPLETED', 'REFUNDED'].includes(status)
}

const canRefund = (status) => {
  return ['PAID', 'SHIPPED'].includes(status)
}

const addressModalVisible = ref(false)
const logisticsModalVisible = ref(false)
const reviewModalVisible = ref(false)
const addressForm = reactive({ id: null, address: '' })
const logistics = ref([])
const orderItems = ref([])
const reviewForm = reactive({ orderId: null, productId: null, rating: 5, content: '' })

const ratingText = computed(() => {
  const texts = ['', '非常差', '较差', '一般', '满意', '非常满意']
  return texts[reviewForm.rating] || ''
})

const refund = async (id) => {
  await api.refundOrder(id, { reason: '不想要了' })
  Message.success('已提交退款申请')
  await loadOrders()
}

const deleteOrder = async (id) => {
  await api.deleteOrder(id)
  Message.success('订单已删除')
  await loadOrders()
}

const openAddress = (order) => {
  addressForm.id = order.id
  addressForm.address = order.address || ''
  addressModalVisible.value = true
}

const submitAddress = async () => {
  if (!addressForm.address.trim()) return Message.warning('请输入收货地址')
  await api.updateOrderAddress(addressForm.id, { address: addressForm.address })
  Message.success('地址已更新')
  addressModalVisible.value = false
  await loadOrders()
}

const openLogistics = async (orderId) => {
  logistics.value = await api.orderLogistics(orderId)
  logisticsModalVisible.value = true
}

const openReview = async (orderId) => {
  orderItems.value = await api.orderItems(orderId)
  if (orderItems.value.length > 0) {
    reviewForm.productId = orderItems.value[0].productId
  }
  reviewForm.orderId = orderId
  reviewForm.rating = 5
  reviewForm.content = ''
  reviewModalVisible.value = true
}

const submitReview = async () => {
  if (!reviewForm.productId) return Message.warning('请选择商品')
  await api.addReview({ orderId: reviewForm.orderId, productId: reviewForm.productId, rating: reviewForm.rating, content: reviewForm.content })
  Message.success({ content: '评价已提交，感谢您的反馈！', icon: () => h(IconCheckCircle, { status: 'success' }) })
  reviewModalVisible.value = false
}

import { h } from 'vue'
import { IconFile, IconApps, IconRefresh, IconLocation, IconSend, IconEdit, IconMessage, IconHistory, IconDelete, IconThumbUp, IconCheckCircle } from '@arco-design/web-vue/es/icon'

onMounted(async () => {
  try {
    await userStore.fetchMe()
    if (userStore.role !== 'CUSTOMER') return router.replace('/login')
    await loadOrders()
  } catch {
    router.replace('/login')
  }
})
</script>

<style scoped>
.orders-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f0f5ff 0%, #fff5f8 100%);
  padding: 24px;
}

.orders-header {
  max-width: 1200px;
  margin: 0 auto 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-title h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.order-count {
  color: #888;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.orders-content {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  background: linear-gradient(135deg, #fafafa 0%, #fff 100%);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.order-card:hover {
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
  border-color: #667eea;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.order-no {
  font-weight: 600;
  color: #333;
}

.order-date {
  color: #888;
  font-size: 13px;
}

.order-items {
  margin-bottom: 16px;
}

.order-items-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f9f9f9;
  border-radius: 8px;
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
  background: #fff;
}

.item-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.item-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-quantity {
  color: #666;
  font-size: 13px;
}

.item-price {
  color: #ff4d4f;
  font-weight: 600;
  font-size: 14px;
}

.order-item-preview {
  display: flex;
  justify-content: space-between;
  padding: 8px 12px;
  background: #f9f9f9;
  border-radius: 8px;
}

.item-label {
  color: #666;
}

.item-value {
  color: #667eea;
  font-weight: 500;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.order-address {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 13px;
  flex: 1;
}

.order-total {
  text-align: right;
  margin: 0 24px;
}

.total-label {
  color: #666;
  font-size: 13px;
  margin-right: 8px;
}

.total-value {
  font-size: 22px;
  font-weight: 700;
  color: #ff4d4f;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
}

.log-item {
  padding: 8px 0;
}

.log-status {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.log-note {
  color: #666;
  font-size: 14px;
}

.log-time {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.rating-text {
  color: #ff758c;
  font-weight: 500;
}

:deep(.arco-btn-primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: transparent;
}

:deep(.arco-rate) {
  font-size: 28px;
}
</style>
