<template>
  <view class="wrap">
    <view class="tabs">
      <view class="tab" :class="{ active: currentTab === 'pending' }" @click="switchTab('pending')">待付款</view>
      <view class="tab" :class="{ active: currentTab === 'completed' }" @click="switchTab('completed')">已完成</view>
    </view>
    <view v-if="error" class="error">{{ error }}</view>
    <view v-if="orders.length === 0 && !loading" class="empty">暂无订单</view>
    <view v-for="item in orders" :key="item.id || item.order_no" class="order">
      <view class="order-main">
        <view class="order-title">{{ item.title || item.subject || '订单' }}</view>
        <view class="order-sub">{{ formatTime(item.created_at || item.time) }}</view>
      </view>
      <view class="order-right">
        <view class="order-amount">{{ formatAmount(item.total_amount || item.amount || item.price) }}</view>
        <view class="order-status">{{ statusText(item.status || item.pay_status || item.state) }}</view>
      </view>
    </view>
    <view v-if="loadingMore" class="loading">加载中...</view>
    <view v-else-if="!hasMore && orders.length > 0" class="end">没有更多了</view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { getOrders } from '../../api/appUser'

const currentTab = ref('pending')
const orders = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const error = ref('')
const page = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)

function formatTime(t) {
  if (!t) return ''
  const d = typeof t === 'string' ? new Date(t) : new Date(t)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hh = String(d.getHours()).padStart(2, '0')
  const mm = String(d.getMinutes()).padStart(2, '0')
  return `${y}-${m}-${day} ${hh}:${mm}`
}

function formatAmount(a) {
  if (a === undefined || a === null) return ''
  const n = Number(a)
  if (Number.isNaN(n)) return String(a)
  return `¥${n.toFixed(2)}`
}

function statusText(s) {
  const v = String(s || '').toLowerCase()
  if (v.includes('pend')) return '待付款'
  if (v.includes('paid') || v.includes('complete') || v.includes('done')) return '已完成'
  return s || ''
}

function switchTab(tab) {
  if (currentTab.value === tab) return
  currentTab.value = tab
  fetchOrders(false)
}

function apiStatus() {
  return currentTab.value === 'pending' ? 'pending' : 'completed'
}

async function fetchOrders(append) {
  const user_id = uni.getStorageSync('user_id')
  const token = uni.getStorageSync('token')
  const phoneBound = !!uni.getStorageSync('phone_bound')
  if (!user_id || !token || !phoneBound) {
    uni.showModal({
      title: '提示',
      content: '请先登录并绑定手机号',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/login/index' })
        }
      }
    })
    return
  }
  if (append) {
    if (!hasMore.value || loadingMore.value) return
    loadingMore.value = true
    page.value = page.value + 1
  } else {
    loading.value = true
    page.value = 1
    hasMore.value = true
    orders.value = []
  }
  error.value = ''
  try {
    const list = await getOrders(user_id, apiStatus(), page.value, pageSize.value)
    const items = Array.isArray(list) ? list : (list && list.items) || []
    const total = (list && list.total) || 0
    orders.value = append ? orders.value.concat(items) : items
    if (total) {
      hasMore.value = orders.value.length < total
    } else {
      hasMore.value = items.length === pageSize.value
    }
  } catch (e) {
    error.value = e && (e.message || e.errMsg) || '获取订单失败'
  } finally {
    if (append) {
      loadingMore.value = false
    } else {
      loading.value = false
    }
  }
}

onLoad((opts) => {
  const s = (opts && opts.status) || ''
  if (s === 'completed' || s === 'pending') currentTab.value = s
  fetchOrders(false)
})

onReachBottom(() => {
  fetchOrders(true)
})
</script>

<style scoped>
.wrap { padding: 24rpx }
.tabs { display: flex; background: #fff; border-radius: 12rpx; padding: 8rpx; margin-bottom: 16rpx; box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04) }
.tab { flex: 1; text-align: center; padding: 16rpx 0; font-size: 28rpx; color: #666 }
.tab.active { color: #007AFF; font-weight: 600 }
.order { display: flex; justify-content: space-between; align-items: center; background: #fff; border-radius: 12rpx; padding: 20rpx; margin-bottom: 16rpx; box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04) }
.order-main { display: flex; flex-direction: column }
.order-title { font-size: 28rpx; color: #333 }
.order-sub { font-size: 24rpx; color: #999; margin-top: 6rpx }
.order-right { display: flex; flex-direction: column; align-items: flex-end }
.order-amount { font-size: 28rpx; color: #333 }
.order-status { font-size: 24rpx; color: #666; margin-top: 6rpx }
.empty { text-align: center; color: #999; margin-top: 40rpx }
.error { color: #e43; margin-bottom: 12rpx }
.loading { text-align: center; color: #666; margin: 20rpx 0 }
.end { text-align: center; color: #999; margin: 20rpx 0 }
</style>