<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.paidAmount || order.totalAmount || 0).toFixed(2) }}</text>
            </view>
            <view class="quantity-info">共{{ getQuantity(order) }}件</view>
          </view>
        </view>
        <view class="order-footer">
          <!-- 退款状态指示器 -->
          <view v-if="order.refundStatus === 'PENDING'" class="refund-indicator pending">
            <view class="indicator-dot"></view>
            <text class="indicator-text">退款审核中</text>
          </view>
          <view v-else-if="order.refundAmount > 0 && order.refundAmount < (order.paidAmount || order.totalAmount || 0)" class="refund-indicator partial">
            <view class="indicator-dot"></view>
            <text class="indicator-text">已退 <text class="indicator-amount">¥{{ order.refundAmount.toFixed(2) }}</text></text>
          </view>
          <view v-else-if="order.refundAmount > 0 && order.refundAmount >= (order.paidAmount || order.totalAmount || 0)" class="refund-indicator full">
            <view class="indicator-dot"></view>
            <text class="indicator-text">已全额退款</text>
          </view>
          <button v-else-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 { onShow } from '@dcloudio/uni-app';
import { getOrderList } from '../../api/order';
import type { OrderInfo } from '../../api/order';
import { checkAuth } from '../../utils/auth';
import { getStatusText, canRefund } from '../../utils/order';
import { logger } from '../../utils/logger';

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

const getQuantity = (order: OrderInfo) => {
  if (!order.products) return 0;
  return order.products.reduce((acc: number, p: any) => acc + p.quantity, 0);
};

const loadOrders = async () => {
  if (loading.value) return;

  loading.value = true;

  try {
    uni.showLoading({ title: '加载中...' });
    const orderList = await getOrderList();
    orders.value = orderList;
    uni.hideLoading();
  } catch (error: any) {
    uni.hideLoading();
    logger.error('加载订单列表失败:', error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  if (!checkAuth('/pages/orders/orders')) {
    return;
  }
  loadOrders();
});

// 每次页面显示时刷新（从退款页/详情页返回时更新退款状态）
onShow(() => {
  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=' + String(order.id)
  });
};
</script>

<style scoped lang="scss">
.container {
  min-height: 100vh;
  background: $color-bg-secondary;
}

/* 无数据提示 */
.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;

  svg {
    width: 100%;
    height: 100%;
  }
}

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

.empty-tip {
  font-size: 28rpx;
  color: $color-text-secondary;
}

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

/* 订单项 */
.order-item {
  background-color: $color-bg-primary;
  border-radius: $radius-lg;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: $shadow-sm;

  &:active {
    transform: scale(0.98);
  }
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 32rpx;
  border-bottom: 1rpx solid $color-bg-secondary;
}

.order-time {
  font-size: 24rpx;
  color: $color-text-secondary;
}

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

.invoice-status {
  font-size: 22rpx;
  color: $color-error;
  margin-left: 16rpx;
  padding: 4rpx 12rpx;
  background: #FFF0F0;
  border-radius: 8rpx;
}

.order-status {
  font-size: 26rpx;
  font-weight: 600;

  &.paid,
  &.completed {
    color: $color-success;
  }

  &.refunded {
    color: $color-text-secondary;
  }

  &.pending {
    color: $color-warning;
  }
}

/* 订单内容 */
.order-content {
  display: flex;
  padding: 32rpx;
  border-bottom: 1rpx solid $color-bg-secondary;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
  background: $color-bg-tertiary;
  border-radius: $radius-md;
  overflow: hidden;

  image {
    width: 100%;
    height: 100%;
  }
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background: $color-bg-tertiary;
}

.order-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-width: 0;
}

.product-name {
  font-size: 28rpx;
  color: $color-text-primary;
  font-weight: 600;
  margin-bottom: 12rpx;
  line-height: 1.5;
  word-break: break-all;
}

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

.price-label {
  color: $color-text-secondary;
}

.price-value {
  color: $color-warning;
  font-weight: 700;
  font-size: 32rpx;
}

.quantity-info {
  font-size: 24rpx;
  color: $color-text-tertiary;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: flex-end;
  padding: 24rpx 32rpx;
  box-sizing: border-box;
  gap: 16rpx;
}

.action-btn {
  background-color: $color-bg-primary;
  color: $color-text-secondary;
  border: 2rpx solid $color-border;
  padding: 16rpx 32rpx;
  border-radius: $radius-xl;
  font-size: 26rpx;
  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;
  width: auto;

  &::after {
    border: none;
  }

  &:active {
    transform: scale(0.95);
  }
}

.detail-btn {
  background: linear-gradient(135deg, $color-primary-light, $color-primary);
  border-color: $color-primary;
  color: $color-text-primary;
  font-weight: 600;
  box-shadow: $shadow-primary;
}

.refund-btn {
  color: $color-text-secondary;

  &:active {
    background-color: $color-bg-secondary;
  }
}

/* 退款状态指示器 */
.refund-indicator {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 10rpx 20rpx;
  border-radius: $radius-xl;
  margin-right: auto;
  font-size: 24rpx;
  font-weight: 500;
  line-height: 1;

  .indicator-dot {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    flex-shrink: 0;
  }

  .indicator-amount {
    font-weight: 700;
    letter-spacing: 0.5rpx;
  }

  &.pending {
    background-color: $color-primary-bg;
    color: $color-primary-dark;

    .indicator-dot {
      background-color: $color-warning;
      animation: dot-pulse 1.5s ease-in-out infinite;
    }
  }

  &.partial {
    background-color: #E3F2FD;
    color: #1565C0;

    .indicator-dot {
      background-color: $color-info;
    }
  }

  &.full {
    background-color: $color-bg-tertiary;
    color: $color-text-secondary;

    .indicator-dot {
      background-color: $color-text-tertiary;
    }
  }
}

@keyframes dot-pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.4; }
}
</style>
