<template>
  <view class="container">
    <!-- 无数据提示 -->
    <view v-if="!loading && orders.length === 0" class="empty-container">
      <view class="empty-icon">
        <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
          <!-- 空箱子 -->
          <rect x="60" y="80" width="80" height="70" rx="4" fill="#E8E8E8" stroke="#CCCCCC" stroke-width="2"/>
          <!-- 箱子盖子 -->
          <path d="M 55 80 L 100 60 L 145 80" fill="#F5F5F5" stroke="#CCCCCC" stroke-width="2"/>
          <!-- 箱子细节线 -->
          <line x1="100" y1="80" x2="100" y2="150" stroke="#CCCCCC" stroke-width="1" stroke-dasharray="3,3"/>
          <!-- 表情 -->
          <circle cx="85" cy="110" r="3" fill="#999999"/>
          <circle cx="115" cy="110" r="3" fill="#999999"/>
          <path d="M 85 125 Q 100 120 115 125" stroke="#999999" stroke-width="2" fill="none" stroke-linecap="round"/>
        </svg>
      </view>
      <text class="empty-text">暂无订单记录</text>
      <text class="empty-tip">快去购物吧~</text>
    </view>
    
    <!-- 订单列表 -->
    <view v-else class="order-list">
      <view v-for="order in orders" :key="order.id" class="order-item">
        <view class="order-header">
          <view class="time-invoice-container">
            <text class="order-time">{{ order.createTime }}</text>
            <text class="invoice-status">未开票</text>
          </view>
          <text :class="['order-status', order.status]">{{ getStatusText(order.status) }}</text>
        </view>
        <view class="order-content">
          <view class="product-image">
            <image v-if="order.products && order.products[0] && order.products[0].image" :src="order.products[0].image" mode="aspectFill"></image>
            <view v-else class="image-placeholder"></view>
          </view>
          <view class="order-info">
            <view class="product-name" v-if="order.products && order.products[0]">
              {{ order.products[0].name }}{{ order.products.length > 1 ? ' 等' : '' }}
            </view>
            <view class="price-info">
              <text class="price-label">实付：</text>
              <text class="price-value">¥{{ order.totalAmount.toFixed(2) }}</text>
            </view>
            <view class="quantity-info">共{{ getQuantity(order) }}件</view>
          </view>
        </view>
        <view class="order-footer">
          <button v-if="canRefund(order)" class="action-btn refund-btn" @click.stop="applyRefund(order)">申请退款</button>
          <button class="action-btn detail-btn" @click.stop="viewOrderDetail(order)">订单详情</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getOrderList } from '../../api/order';
import type { OrderInfo } from '../../api/order';
import { checkAuth } from '../../utils/auth';

const orders = ref<OrderInfo[]>([]);
const loading = ref(false);

/**
 * 获取订单状态文本
 */
const getStatusText = (status: number) => {
  const statusMap: any = {
    0: '待支付',
    1: '已完成',
    2: '已取消'
  };
  return statusMap[status] || '未知';
};

/**
 * 计算订单商品总数量
 */
const getQuantity = (order: OrderInfo) => {
  if (!order.products) return 0;
  return order.products.reduce((acc: number, p: any) => acc + p.quantity, 0);
};

/**
 * 判断是否可以申请退款
 * 只有已完成的订单可以退款
 */
const canRefund = (order: OrderInfo) => {
  return order.status === 1; // 1-已完成
};

/**
 * 加载订单列表
 */
const loadOrders = async () => {
  if (loading.value) return;
  
  loading.value = true;
  
  try {
    uni.showLoading({
      title: '加载中...',
      mask: true
    });
    
    // 调用真实接口获取订单列表
    const orderList = await getOrderList();
    orders.value = orderList;
    
    uni.hideLoading();
    
    // 无数据时不显示toast，由空状态提示展示
    // if (orderList.length === 0) {
    //   uni.showToast({
    //     title: '暂无订单',
    //     icon: 'none'
    //   });
    // }
  } catch (error: any) {
    uni.hideLoading();
    console.error('加载订单列表失败:', error);
    // 错误已在request工具中显示
  } finally {
    loading.value = false;
  }
};

/**
 * 页面加载时检查登录状态并获取订单列表
 */
onMounted(() => {
  // 检查登录状态，未登录会自动跳转到登录页
  if (!checkAuth('/pages/orders/orders')) {
    return;
  }
  
  // 已登录，加载订单列表
  loadOrders();
});

/**
 * 申请退款
 */
const applyRefund = (order: OrderInfo) => {
  uni.navigateTo({
    url: '/pages/refund/refund?orderId=' + order.id
  });
};

/**
 * 查看订单详情
 */
const viewOrderDetail = (order: OrderInfo) => {
  uni.navigateTo({
    url: '/pages/orderDetail/orderDetail?orderId=' + order.id
  });
};
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  padding-top: 0;
}

/* 无数据提示 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 80vh;
  padding: 40rpx;
}

.empty-icon {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 40rpx;
}

.empty-icon svg {
  width: 100%;
  height: 100%;
}

.empty-text {
  font-size: 32rpx;
  color: #666666;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.empty-tip {
  font-size: 28rpx;
  color: #999999;
}

/* 订单列表 */
.order-list {
  padding: 10rpx 0 30rpx;
}

/* 订单项 */
.order-item {
  background-color: #ffffff;
  border-radius: 0;
  margin-bottom: 10rpx;
  overflow: hidden;
  box-shadow: none;
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.order-time {
  font-size: 24rpx;
  color: #666666;
}

.time-invoice-container {
  display: flex;
  align-items: center;
  flex: 1;
}

.invoice-status {
  font-size: 24rpx;
  color: #ff6666;
  margin-left: 20rpx;
}

.order-status {
  font-size: 24rpx;
}

.order-status.paid,
.order-status.completed {
  color: #00cc66;
}

.order-status.refunded {
  color: #999999;
}

.order-status.pending {
  color: #FF9100;
}

/* 订单内容 */
.order-content {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.product-image {
  width: 100rpx;
  height: 100rpx;
  margin-right: 20rpx;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

.order-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
}

.product-name {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
  width: 100%;
  text-align: left;
  margin-bottom: 10rpx;
}

.price-info {
  font-size: 28rpx;
}

.price-label {
  color: #666666;
}

.price-value {
  color: #333333;
  font-weight: 500;
}

.quantity-info {
  font-size: 24rpx;
  color: #999999;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: flex-end;
  padding: 20rpx;
  width: 100%;
  box-sizing: border-box;
}

/* 重置按钮默认样式 */
.action-btn {
  background-color: #ffffff;
  color: #333333;
  border: 1rpx solid #dddddd;
  padding: 12rpx 24rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  flex-shrink: 0;
  text-align: center;
  white-space: nowrap;
  min-width: 160rpx;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0; /* 彻底移除默认 margin */
  width: auto;
}

/* 按钮之间的间距 */
.action-btn + .action-btn {
  margin-left: 20rpx;
}

.action-btn::after {
  border: none;
}

/* 详情按钮高亮 */
.detail-btn {
  background-color: #FFD700;
  border-color: #FFD700;
  color: #000000;
  font-weight: 500;
}

.refund-btn {
  color: #666666;
}
</style>