<!-- 订单列表页 -->
<template>
	<view class="order-page">
		<view class="order-safe-top"></view>
		<!-- 顶部导航栏 -->
		<view class="navbar order-topbar">
			<view class="order-back" @tap="goBack">
				<text class="wlIcon-fanhui1"></text>
			</view>
			<scroll-view class="order-tabs" scroll-x show-scrollbar="false">
				<view class="order-tabs-track">
					<view class="nav-item text-df order-tab" v-for="(item, index) in navList" :key="item.state"
						:class="{ current: tabCurrentIndex === index }" @tap="tabClick(index)">
						{{ item.text }}
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 订单列表内容区 -->
		<swiper class="order-swiper" :style="{ height: swiperHeight > 0 ? swiperHeight + 'px' : '' }"
			:current="tabCurrentIndex" duration="300" @change="changeTab">
			<swiper-item class="tab-content order-swiper-item" v-for="(tag, key) in navList" :key="tag.state">
				<scroll-view class="list-scroll-content order-scroll" scroll-y @scrolltolower="loadData">
					<!-- 空状态 -->
					<wanl-empty v-if="tag.loaded === true && tag.orderList.length === 0" :text="$t('order.empty')" />

					<!-- 订单卡片 -->
					<view v-for="(order, okey) in tag.orderList" :key="order.id" class="order-item order-card">
						<!-- 店铺名 + 订单状态 -->
						<view class="head order-card-head">
							<view class="shop wanl-gray order-shop" @tap="onShop(order.shop_id)">
								<text class="wlIcon-dianpu1 wanl-black"></text>
								<text class="wanl-black margin-lr-xs text-30 text-cut order-shop-name">{{ order.shop.shopname }}</text>
								<text class="wlIcon-fanhuigengduo text-sm"></text>
							</view>
							<view class="margin-right-bj text-sm order-head-right">
								<text class="state order-state" :style="{ color: order.stateTipColor }">{{ order.stateTip }}</text>
								<text v-if="order.state === 7" class="margin-left-sm wlIcon-lajitong order-trash"
									@tap="deleteOrder(order.id, okey)">{{ $t('order.delete') }}</text>
							</view>
						</view>

						<!-- 商品列表 -->
						<view class="goods-box order-goods" v-for="(goods, gkey) in order.goods" :key="goods.id"
							@tap="orderDetails(order.id)">
							<view class="goods-row">
								<image class="order-goods-img" :src="$appKit.oss(goods.image, 140, 140, 1)" mode="aspectFill" lazy-load>
								</image>
								<view class="describe">
									<view class="text-cut-2">{{ goods.title }}</view>
									<view class="wanl_sku text-min">
										<text class="wanl-gray-dark">{{ goods.difference }}</text>
									</view>
								</view>
							</view>
							<view class="parameter order-goods-meta">
								<view class="text-price text-sm text-black">{{ goods.price }}</view>
								<view class="text-min wanl-gray">x {{ goods.number }}</view>
								<view class="text-min text-yellow" v-if="goods.refund_status != 0">{{ getRefund(goods.refund_status) }}
								</view>
							</view>
						</view>

						<!-- 价格汇总 -->
						<view class="price-box text-sm flex order-card-foot">
							<view v-if="order.pay.discount_price > 0" class="margin-right-sm wanl-gray">{{ $t('order.discount') }}<text class="text-price">{{
								order.pay.discount_price }}</text></view>
							<view v-if="order.pay.freight_price > 0" class="margin-right-sm wanl-gray">{{ $t('order.freight') }}<text class="text-price">{{
								order.pay.freight_price }}</text></view>
							<view>{{ $t('order.actualPay') }}<text class="text-price">{{ order.pay.price }}</text></view>
						</view>

						<!-- 待付款操作按钮 -->
						<view class="action-box padding-bottom-bj" v-if="order.state == 1">
							<button class="cu-btn round line-black margin-lr-bj order-btn" @tap="editAddress(order.id)">{{ $t('order.editAddress') }}</button>
							<button class="cu-btn round line-black order-btn" @tap="cancelOrder(order)">{{ $t('order.cancelOrder') }}</button>
							<button class="cu-btn round margin-lr-bj wanl-bg-orange order-btn-primary"
								@tap="paymentOrder(order.id)">{{ $t('order.payNow') }}</button>
						</view>
						<!-- 待发货操作按钮 -->
						<view class="action-box padding-bottom-bj" v-if="order.state == 2">
							<button class="cu-btn round line-black order-btn margin-lr-bj" @tap="editAddress(order.id)">{{ $t('order.editAddress') }}</button>
						</view>
						<!-- 待收货操作按钮 -->
						<view class="action-box padding-bottom-bj" v-if="order.state == 3">
							<button class="cu-btn round line-black order-btn" @tap="onLogistics(order.id)">{{ $t('order.viewLogistics') }}</button>
							<button class="cu-btn round margin-lr-bj wanl-bg-orange order-btn-primary"
								@tap="confirmOrder(order)">{{ $t('order.confirmReceipt') }}</button>
						</view>
						<!-- 待评价操作按钮 -->
						<view class="action-box padding-bottom-bj" v-if="order.state == 4">
							<button class="cu-btn round line-black order-btn" @tap="onLogistics(order.id)">{{ $t('order.viewLogistics') }}</button>
							<button class="cu-btn round margin-lr-bj line-black order-btn-primary-alt"
								@tap="commentOrder(order.id)">{{ $t('order.review') }}</button>
						</view>
					</view>

					<uni-load-more :status="tag.loadingType" />
					<view class="edgeInsetBottom"></view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
import { pullOrderList, postOrderCancel, postOrderDelete, postOrderConfirm } from '@/features/mall/mall-gateway'

export default {
	data() {
		return {
			tabCurrentIndex: 0,
			swiperHeight: 0,
			navList: []
		}
	},
	onLoad(options) {
		this.navList = [
			{ state: 0, text: this.$t('order.all'), loadingType: 'more', current_page: 1, orderList: [] },
			{ state: 1, text: this.$t('order.pendingPayment'), loadingType: 'more', current_page: 1, orderList: [] },
			{ state: 2, text: this.$t('order.pendingShipment'), loadingType: 'more', current_page: 1, orderList: [] },
			{ state: 3, text: this.$t('order.pendingReceipt'), loadingType: 'more', current_page: 1, orderList: [] },
			{ state: 4, text: this.$t('order.pendingReview'), loadingType: 'more', current_page: 1, orderList: [] }
		]
		if (!options.state) options.state = 0
		this.tabCurrentIndex = +options.state
		this.calcSwiperHeight()
		this.loadData()
	},
	methods: {
		/**
		 * 加载订单列表数据
		 * source: 'tabChange' 表示切换标签页触发
		 */
		async loadData(source) {
			let index = this.tabCurrentIndex
			let navItem = this.navList[index]
			let state = navItem.state
			if (navItem.loadingType == 'noMore') return
			if (source === 'tabChange' && navItem.loaded === true) return
			if (navItem.loadingType === 'loading') return
			navItem.loadingType = 'loading'
			try {
				const res = await pullOrderList({ state, page: navItem.current_page })
				navItem.current_page = res.currentPage
				if (res.lastPage === res.currentPage) {
					navItem.loadingType = 'noMore'
				} else {
					navItem.loadingType = 'more'
					navItem.current_page++
				}
				let orderList = res.rows.filter(item => {
					item = Object.assign(item, this.orderStateExp(item.state))
					if (state === 0) return item
					return Number(item.state) === Number(state)
				})
				this.$set(navItem, 'orderList', navItem.orderList.concat(orderList))
				this.$set(navItem, 'loaded', true)
			} catch (e) {
				navItem.loadingType = 'more'
				this.$set(navItem, 'loaded', true)
				console.error('[order] loadData 失败:', JSON.stringify(e))
				uni.showToast({ title: this.$t('order.loadFailed'), icon: 'none' })
			}
		},

		/** swiper 切换触发 */
		changeTab(e) {
			this.tabCurrentIndex = e.detail.current
			this.loadData('tabChange')
		},

		/** 点击标签切换 */
		tabClick(index) {
			this.tabCurrentIndex = index
			this.loadData('tabChange')
		},

		/** 返回上一页 */
		goBack() {
			const pages = getCurrentPages()
			if (pages && pages.length > 1) {
				uni.navigateBack({ delta: 1 })
			} else {
				uni.switchTab({ url: '/pages/mine/index' })
			}
		},

		/** 删除已关闭的订单 */
		async deleteOrder(order_id, key) {
			uni.showLoading({ title: this.$t('order.pleaseWait') })
			try {
				await postOrderDelete({ id: order_id })
				this.navList[this.tabCurrentIndex].orderList.splice(key, 1)
			} catch (e) {
				uni.showToast({ title: this.$t('order.deleteFailed'), icon: 'none' })
			}
			uni.hideLoading()
		},

		/** 取消订单 */
		async cancelOrder(item) {
			uni.showLoading({ title: this.$t('order.pleaseWait') })
			try {
				await postOrderCancel({ id: item.id })
				let { stateTip, stateTipColor } = this.orderStateExp(7)
				Object.assign(item, { state: 7, stateTip, stateTipColor })
				// 从待付款列表移除
				let list = this.navList[1].orderList
				let index = list.findIndex(val => val.id === item.id)
				if (index !== -1) list.splice(index, 1)
				// 更新全部列表中的状态
				if (this.tabCurrentIndex == 1) {
					let allList = this.navList[0].orderList
					let idx = allList.findIndex(val => val.id === item.id)
					if (idx !== -1) allList[idx].state = 7
				}
			} catch (e) {
				uni.showToast({ title: this.$t('order.cancelFailed'), icon: 'none' })
			}
			uni.hideLoading()
		},

		/** 跳转评价页 */
		commentOrder(id) {
			uni.navigateTo({ url: '/pages/order/comment?order_id=' + id })
		},

		/** 跳转支付页 */
		paymentOrder(id) {
			uni.navigateTo({ url: `/pages/user/money/pay?order_id=${id}&order_type=goods` })
		},

		/** 确认收货（弹窗确认） */
		confirmOrder(item) {
			uni.showModal({
				title: this.$t('common.tip'),
				content: this.$t('order.confirmReceiptContent'),
				success: (res) => {
					if (!res.confirm) return
					this.doConfirmOrder(item)
				}
			})
		},

		/** 执行确认收货 */
		async doConfirmOrder(item) {
			uni.showLoading({ title: this.$t('order.pleaseWait') })
			try {
				await postOrderConfirm({ id: item.id })
				let { stateTip, stateTipColor } = this.orderStateExp(4)
				Object.assign(item, { state: 4, stateTip, stateTipColor })
			} catch (e) {
				uni.showToast({ title: this.$t('addressManage.operationFailed'), icon: 'none' })
			}
			uni.hideLoading()
		},

		/** 订单状态文字和颜色映射 */
		orderStateExp(state) {
			let stateTip = '', stateTipColor = '#333'
			switch (+state) {
				case 1: stateTip = this.$t('order.pendingPayment'); stateTipColor = '#f40'; break
				case 2: stateTip = this.$t('order.pendingShipment'); break
				case 3: stateTip = this.$t('order.shipped'); break
				case 4: stateTip = this.$t('order.tradeSuccess'); break
				case 5: stateTip = this.$t('order.tradeSuccess'); break
				case 6: stateTip = this.$t('order.completed'); break
				case 7: stateTip = this.$t('order.closed'); stateTipColor = '#777'; break
			}
			return { stateTip, stateTipColor }
		},

		/** 退款状态文字映射 */
		getRefund(status) {
			return [
				this.$t('order.refund'),
				this.$t('order.refunding'),
				this.$t('order.waitReturn'),
				this.$t('order.refundDone'),
				this.$t('order.refundClosed'),
				this.$t('order.refundRejected')
			][status]
		},

		/** 修改收货地址 */
		editAddress(id) {
			uni.navigateTo({ url: '/pages/user/address/address?source=2&order_id=' + id })
		},

		/** 跳转订单详情 */
		orderDetails(id) {
			uni.navigateTo({ url: '/pages/order/details?id=' + id })
		},

		/** 跳转店铺页 */
		onShop(shop_id) {
			uni.navigateTo({ url: '/pages/shop/index?id=' + shop_id })
		},

		/** 跳转物流页 */
		onLogistics(id) {
			uni.navigateTo({ url: '/pages/order/logistics?id=' + id })
		},

		/** 动态计算 swiper 高度，避免 APP 端 height: 0 导致内容不可见 */
		calcSwiperHeight() {
			const info = uni.getSystemInfoSync()
			const statusBarH = info.statusBarHeight || 0
			const rpxRatio = info.screenWidth / 750
			const topbarH = (18 + 68 + 12) * rpxRatio
			this.swiperHeight = info.windowHeight - statusBarH - topbarH
		}
	}
}
</script>

<style scoped>
page {
	height: 100%;
}

.order-safe-top {
	height: var(--status-bar-height);
}

.order-page {
	background: #f3f5f7;
	height: 100%;
	min-height: 100vh;
	display: flex;
	flex-direction: column;
}

/* 顶部导航栏 */
.order-topbar {
	flex-shrink: 0;
	background: #f3f5f7;
	display: flex;
	align-items: center;
	padding: 18rpx 20rpx 12rpx;
	gap: 16rpx;
}

.order-back {
	width: 68rpx;
	height: 68rpx;
	flex-shrink: 0;
	border-radius: 999rpx;
	background: #ffffff;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #1f2937;
	box-shadow: 0 6rpx 18rpx rgba(15, 23, 42, 0.06);
	border: 1px solid rgba(15, 23, 42, 0.06);
}

.order-back text {
	font-size: 28rpx;
}

.order-tabs {
	flex: 1;
	min-width: 0;
}

.order-tabs-track {
	display: inline-flex;
	align-items: center;
	white-space: nowrap;
	padding-right: 10rpx;
}

.order-tab {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	min-width: 132rpx;
	height: 68rpx;
	background: #ffffff;
	border-radius: 999rpx;
	padding: 0 24rpx;
	margin-right: 14rpx;
	color: #667085;
	font-size: 26rpx;
	border: 1px solid rgba(15, 23, 42, 0.06);
	box-shadow: 0 6rpx 18rpx rgba(15, 23, 42, 0.04);
}

.nav-item.current.order-tab {
	background: linear-gradient(135deg, #ff7a45, #ff5b2d);
	color: #ffffff;
	font-weight: 600;
	border-color: transparent;
	box-shadow: 0 10rpx 22rpx rgba(255, 91, 45, 0.24);
}

/* 内容区 */
.order-swiper {
	flex: 1
}

.order-swiper-item {
	height: 100%;
}

.order-scroll {
	height: 100%;
	padding: 18rpx 20rpx 0;
	box-sizing: border-box;
}

/* 订单卡片 */
.order-card {
	background: #fff;
	border-radius: 18rpx;
	box-shadow: 0 8rpx 28rpx rgba(17, 24, 39, 0.06);
	margin-bottom: 18rpx;
	overflow: hidden;
}

.order-card-head {
	padding: 22rpx 22rpx 14rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.order-shop {
	display: flex;
	align-items: center;
	min-width: 0;
}

.order-shop-name {
	max-width: 360rpx;
}

.order-head-right {
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.order-trash {
	color: #9ca3af;
}

/* 商品行 */
.order-goods {
	padding: 0 22rpx 18rpx;
}

.goods-row {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.order-goods-img {
	width: 140rpx;
	height: 140rpx;
	flex-shrink: 0;
	border-radius: 8rpx;
}

.order-goods-content {
	min-width: 0;
}

.order-goods-meta {
	display: flex;
	justify-content: space-between;
	align-items: flex-end;
	margin-top: 10rpx;
}

/* 价格汇总 */
.order-card-foot {
	padding: 10rpx 22rpx 18rpx;
	justify-content: flex-end;
	gap: 14rpx;
	border-top: 1px solid rgba(0, 0, 0, 0.04);
}

/* 操作按钮 */
.order-btn {
	border-color: rgba(0, 0, 0, 0.18) !important;
}

.order-btn-primary {
	background: linear-gradient(135deg, #ff6b35, #ff3d2e);
	color: #fff !important;
}

.order-btn-primary-alt {
	border-color: rgba(255, 107, 53, 0.55) !important;
	color: #ff6b35 !important;
}

.wanl-bg-orange {
	background: linear-gradient(135deg, #ff6b35, #ff3d2e) !important;
	color: #fff !important;
}

.edgeInsetBottom {
	height: 30rpx;
}
</style>
