<template>
	<view class="order-list-page">
		<view class="order-list-tabs">
			<scroll-view scroll-x class="order-list-tabs__scroll">
				<view
					v-for="tab in tabs"
					:key="tab.key"
					class="order-list-tabs__item"
					:class="{ 'order-list-tabs__item--on': activeTab === tab.key }"
					@click="onTabChange(tab.key)"
				>
					{{ tab.label }}
				</view>
			</scroll-view>
			<view class="order-list-links">
				<text class="order-list-links__item" @click="goReviewList()">评价</text>
				<text class="order-list-links__item" @click="goAftersaleList()">退款/售后</text>
			</view>
		</view>

		<scroll-view
			class="order-list-scroll"
			scroll-y
			:style="{ height: scrollHeight }"
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onPullRefresh"
			@scrolltolower="onLoadMore"
		>
			<view v-if="loading && !list.length" class="order-list-state">
				<u-loading-icon mode="circle" />
			</view>

			<view v-else-if="loadFailed && !list.length" class="order-list-state">
				<u-empty mode="list" text="加载失败" icon-size="80" />
				<text class="order-list-retry" @click="reloadList(true)">点击重试</text>
			</view>

			<view v-else-if="!list.length" class="order-list-state">
				<u-empty mode="list" text="暂无相关订单" icon-size="80" />
				<button class="order-list-btn" @click="goHome">去逛逛</button>
			</view>

			<template v-else>
				<view
					v-for="card in list"
					:key="card.orderId"
					class="order-card"
					@click="onCardClick(card)"
				>
					<view class="order-card__head">
						<image class="order-card__shop-avatar" :src="card.shopAvatar" mode="aspectFill" />
						<text class="order-card__shop-name">{{ card.shopName }}</text>
						<text
							class="order-card__status"
							:class="{ 'order-card__status--aftersale': card.statusIsAftersale }"
						>{{ card.statusText }}</text>
					</view>

					<view v-if="card.items && card.items.length" class="order-card__goods">
						<order-goods-row
							v-for="(item, idx) in card.items"
							:key="item.orderItemId || `${card.orderId}-${idx}`"
							:item="item"
							:review-action="getItemReviewAction(item)"
							@review="(code) => onItemReview(card, item, code)"
						/>
					</view>

					<view class="order-card__sum">
						<text class="order-card__time">{{ card.createTime }}</text>
						<text class="order-card__amount">
							{{ card.amountLabel }}
							<text class="order-card__price">¥{{ card.payAmountText }}</text>
						</text>
					</view>

					<text
						v-if="card.payRemainSeconds > 0"
						class="order-card__countdown"
					>
						支付剩余 {{ formatPayCountdown(card.payRemainSeconds) }}
					</text>

					<order-action-bar
						:actions="card.actions"
						:disabled="actionLoading"
						@action="(code) => onAction(code, card)"
					/>
				</view>

				<view class="order-list-footer">
					<text v-if="loadingMore">加载中...</text>
					<text v-else-if="finished">没有更多了</text>
				</view>
			</template>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { listOrders } from '@/api/order'
import { mapOrderListRow, formatPayCountdown, getItemReviewAction } from '@/utils/orderDisplay'
import { ORDER_LIST_TABS, ORDER_PAGE_SIZE, ORDER_ACTION } from '@/constants/order'
import { ensureApiToken } from '@/utils/apiAuth'
import { goOrderDetail, goReviewList, goAftersaleList, goReviewEdit, goReviewView } from '@/utils/orderNav'
import { runOrderAction, openPayModal } from '@/utils/orderAction'
import { PAGE_HOME } from '@/utils/pageRoute'
import { useActionGuard } from '@/utils/actionGuard'
import OrderGoodsRow from '@/components/order/OrderGoodsRow.vue'
import OrderActionBar from '@/components/order/OrderActionBar.vue'

const actionGuard = useActionGuard()

const tabs = ORDER_LIST_TABS
const activeTab = ref('ALL')
const list = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const finished = ref(false)
const loadFailed = ref(false)
const refreshing = ref(false)
const actionLoading = actionGuard.locked
const pageNum = ref(1)
const scrollHeight = ref('600px')

function calcScrollHeight() {
	try {
		const sys = uni.getSystemInfoSync()
		scrollHeight.value = `${(sys.windowHeight || 600) - 100}px`
	} catch (e) {
		scrollHeight.value = '600px'
	}
}

async function fetchPage(isReset) {
	if (isReset) {
		loading.value = true
		loadFailed.value = false
		pageNum.value = 1
		finished.value = false
	} else if (finished.value || loadingMore.value) {
		return
	} else {
		loadingMore.value = true
	}
	try {
		const res = await listOrders({
			tab: activeTab.value,
			pageNum: pageNum.value,
			pageSize: ORDER_PAGE_SIZE
		})
		const rows = (res.rows || []).map(mapOrderListRow).filter(Boolean)
		const total = Number(res.total) || 0
		if (isReset) {
			list.value = rows
		} else {
			list.value = list.value.concat(rows)
		}
		finished.value = list.value.length >= total || rows.length < ORDER_PAGE_SIZE
		if (!finished.value) {
			pageNum.value += 1
		}
	} catch (e) {
		if (isReset) {
			loadFailed.value = true
		}
	} finally {
		loading.value = false
		loadingMore.value = false
		refreshing.value = false
	}
}

function reloadList(isReset) {
	return fetchPage(isReset !== false)
}

function onTabChange(key) {
	if (activeTab.value === key) return
	activeTab.value = key
	reloadList(true)
}

function onPullRefresh() {
	refreshing.value = true
	reloadList(true)
}

function onLoadMore() {
	reloadList(false)
}

function onCardClick(card) {
	goOrderDetail(card.orderId, card.aftersaleStatus)
}

function onItemReview(card, item, code) {
	actionGuard.run(() => {
		if (code === ORDER_ACTION.REVIEW) {
			goReviewEdit(card.orderId, item.orderItemId)
			return
		}
		if (code === ORDER_ACTION.VIEW_REVIEW) {
			goReviewView(card.orderId, item.orderItemId)
		}
	})
}

function onAction(code, card) {
	actionGuard.run(async () => {
		if (code === ORDER_ACTION.PAY) {
			const result = await openPayModal(card.orderId, card.orderNo, card.payAmountText)
			if (result && result.status) {
				await reloadList(true)
			}
			return
		}
		await runOrderAction(code, {
			orderId: card.orderId,
			firstItem: card.firstItem,
			items: card.items,
			onRefresh: () => reloadList(true)
		})
	})
}

function goHome() {
	uni.switchTab({ url: PAGE_HOME })
}

onLoad((options) => {
	calcScrollHeight()
	if (options.tab) {
		activeTab.value = options.tab
	}
})

onShow(() => {
	if (!ensureApiToken(false)) return
	reloadList(true)
})
</script>

<style lang="scss" scoped>
.order-list-page {
	height: calc(100vh - 88rpx);
	background: #f5f6f8;
}
.order-list-tabs {
	background: #fff;
	border-bottom: 1rpx solid #eee;
}
.order-list-tabs__scroll {
	white-space: nowrap;
	padding: 0 12rpx;
}
.order-list-tabs__item {
	display: inline-block;
	padding: 24rpx 20rpx;
	font-size: 28rpx;
	color: #666;
}
.order-list-tabs__item--on {
	color: #2e7d32;
	font-weight: 600;
	border-bottom: 4rpx solid #2e7d32;
}
.order-list-links {
	display: flex;
	justify-content: flex-end;
	gap: 24rpx;
	padding: 8rpx 24rpx 16rpx;
}
.order-list-links__item {
	font-size: 24rpx;
	color: #2e7d32;
}
.order-list-scroll {
	padding: 16rpx 24rpx;
	box-sizing: border-box;
}
.order-list-state {
	padding: 120rpx 48rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.order-list-retry {
	margin-top: 24rpx;
	font-size: 28rpx;
	color: #2e7d32;
}
.order-list-btn {
	margin-top: 32rpx;
	width: 280rpx;
	height: 72rpx;
	line-height: 72rpx;
	background: linear-gradient(135deg, #43a047 0%, #2e7d32 100%);
	color: #fff;
	font-size: 28rpx;
	border-radius: 36rpx;
	border: none;
}
.order-card {
	margin-bottom: 16rpx;
	padding: 20rpx 24rpx;
	background: #fff;
	border-radius: 12rpx;
}
.order-card__head {
	display: flex;
	align-items: center;
	margin-bottom: 8rpx;
}
.order-card__shop-avatar {
	width: 40rpx;
	height: 40rpx;
	border-radius: 8rpx;
	background: #eee;
}
.order-card__shop-name {
	flex: 1;
	margin-left: 12rpx;
	font-size: 28rpx;
	color: #333;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}
.order-card__status {
	font-size: 26rpx;
	color: #e65100;
}
.order-card__status--aftersale {
	color: #1976d2;
}
.order-card__goods :deep(.order-goods-row + .order-goods-row) {
	border-top: 1rpx solid #f5f5f5;
}
.order-card__sum {
	margin-top: 12rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.order-card__time {
	font-size: 24rpx;
	color: #999;
}
.order-card__amount {
	font-size: 24rpx;
	color: #666;
}
.order-card__price {
	font-size: 30rpx;
	color: #e53935;
	font-weight: 600;
}
.order-card__countdown {
	display: block;
	margin-top: 8rpx;
	font-size: 24rpx;
	color: #e65100;
	text-align: right;
}
.order-list-footer {
	padding: 24rpx;
	text-align: center;
	font-size: 24rpx;
	color: #999;
}
</style>
