<template>
  <view :class="['orders-page', elderClass]">
    <view class="status-tabs">
      <view v-for="tab in STATUS_TABS" :key="tab.key"
        :class="['status-tab', activeTab === tab.key ? 'active' : '']"
        @tap="handleTabChange(tab.key)">
        <text class="status-tab-text">{{ tab.label }}</text>
      </view>
    </view>

    <view v-if="orders.length === 0 && !loading" class="empty-wrap">
      <EmptyState icon="" title="暂无订单" hint="去商城兑换心仪商品吧" />
    </view>

    <scroll-view v-else scroll-y class="orders-scroll" @scrolltolower="loadMore">
      <view class="order-card" v-for="order in orders" :key="order.id">
        <view class="order-header">
          <text class="order-product">商品 {{ order.product_id.slice(0, 8) }}</text>
          <view :class="['order-status-tag', getStatusConfig(order.status).cls]">
            <text class="order-status-text">{{ getStatusConfig(order.status).label }}</text>
          </view>
        </view>
        <view class="order-body">
          <view class="order-row">
            <text class="order-row-label">消耗积分</text>
            <text class="order-row-value order-cost">{{ order.points_cost.toLocaleString() }}</text>
          </view>
          <view class="order-row">
            <text class="order-row-label">兑换时间</text>
            <text class="order-row-value">{{ formatDate(order.created_at) }}</text>
          </view>
          <view v-if="order.status === 'pending'" class="order-qrcode" @tap="handleShowQrCode(order.qr_code)">
            <text class="qrcode-label">核销码</text>
            <text class="qrcode-value">{{ order.qr_code }}</text>
            <text class="qrcode-tap">查看</text>
          </view>
        </view>
      </view>
      <Loading v-if="loading" text="加载中..." />
      <view v-if="!loading && orders.length >= total && total > 0" class="no-more"><text class="no-more-text">没有更多了</text></view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { listMyOrders, type PointsOrder } from '@/services/points'
import EmptyState from '@/components/EmptyState.vue'
import Loading from '@/components/Loading.vue'
import { useElderClass } from '@/composables/useElderClass'

const STATUS_TABS = [
  { key: '', label: '全部' }, { key: 'pending', label: '待核销' },
  { key: 'verified', label: '已核销' }, { key: 'expired', label: '已过期' },
]
const STATUS_CONFIG: Record<string, { label: string; cls: string }> = {
  pending: { label: '待核销', cls: 'order-status-tag--pending' },
  verified: { label: '已核销', cls: 'order-status-tag--verified' },
  cancelled: { label: '已取消', cls: 'order-status-tag--cancelled' },
  expired: { label: '已过期', cls: 'order-status-tag--expired' },
}

const { elderClass } = useElderClass()
const orders = ref<PointsOrder[]>([])
const activeTab = ref('')
const page = ref(1)
const total = ref(0)
const loading = ref(false)
let loadingGuard = false

const getStatusConfig = (status: string) => STATUS_CONFIG[status] || { label: status, cls: 'order-status-tag--expired' }

const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}

const fetchOrders = async (pageNum: number, status: string, isRefresh = false) => {
  if (loadingGuard) return
  loadingGuard = true; loading.value = true
  try {
    const res = await listMyOrders({ page: pageNum, page_size: 10 })
    let list = res.data || []
    if (status) list = list.filter(o => o.status === status)
    orders.value = isRefresh ? list : [...orders.value, ...list]
    total.value = res.total; page.value = pageNum
  } catch { uni.showToast({ title: '加载失败', icon: 'none' }) }
  finally { loadingGuard = false; loading.value = false }
}

const handleTabChange = (key: string) => { activeTab.value = key; fetchOrders(1, key, true) }
const loadMore = () => { if (!loading.value && orders.value.length < total.value) fetchOrders(page.value + 1, activeTab.value) }
const handleShowQrCode = (qrCode: string) => uni.showModal({ title: '核销码', content: qrCode, showCancel: false, confirmText: '知道了' })

onShow(() => { uni.setNavigationBarTitle({ title: '我的订单' }); fetchOrders(1, activeTab.value, true) })
onPullDownRefresh(() => { fetchOrders(1, activeTab.value, true).finally(() => uni.stopPullDownRefresh()) })
</script>

<style lang="scss" scoped>
.orders-page { min-height: 100vh; background: $bg; }
.status-tabs { display: flex; padding: 12px 24px; gap: 8px; background: $card; }
.status-tab { padding: 6px 16px; min-height: $touch-min; display: flex; align-items: center; border-radius: 20px; background: rgba(0,0,0,0.04); }
.status-tab.active { background: $pri; }
.status-tab-text { font-size: var(--tk-font-cap); color: $tx2; }
.status-tab.active .status-tab-text { color: $white; }
.orders-scroll { height: calc(100vh - 52px); padding: 16px 24px; }
.order-card { @include card; margin-bottom: 12px; }
.order-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.order-product { font-size: var(--tk-font-body); color: $tx; font-weight: 500; }
.order-status-tag { padding: 2px 10px; border-radius: 4px; }
.order-status-tag--pending { background: rgba($pri, 0.1); }
.order-status-tag--verified { background: rgba(82,196,26,0.1); }
.order-status-tag--cancelled { background: rgba(0,0,0,0.05); }
.order-status-tag--expired { background: rgba(0,0,0,0.05); }
.order-status-text { font-size: var(--tk-font-micro); color: $tx2; }
.order-body { }
.order-row { display: flex; justify-content: space-between; padding: 6px 0; }
.order-row-label { font-size: var(--tk-font-cap); color: $tx3; }
.order-row-value { font-size: var(--tk-font-cap); color: $tx; }
.order-cost { color: $wrn; font-weight: 500; }
.order-qrcode { display: flex; align-items: center; gap: 8px; margin-top: 8px; padding: 8px 12px; background: rgba($pri, 0.05); border-radius: $r; }
.qrcode-label { font-size: var(--tk-font-cap); color: $tx2; }
.qrcode-value { flex: 1; font-size: var(--tk-font-cap); color: $pri; font-weight: 500; }
.qrcode-tap { font-size: var(--tk-font-cap); color: $pri; }
.empty-wrap { padding-top: 120px; }
.no-more { @include flex-center; padding: 20px; }
.no-more-text { font-size: var(--tk-font-cap); color: $tx3; }
</style>
