<template>
	<view class="logistics-container">
		<!-- 头部快递信息 -->
		<view class="logistics-header">
			<image class="logo" src="/static/img/icon-logo-jd.png"></image>
			<view class="company-info">
				<text class="company-name">京东物流</text>
				<view class="tracking-number">
					<text class="number">{{ orderNo }}</text>
					<text class="copy-btn" @click="copyTrackingNumber(orderNo)">复制</text>
				</view>
			</view>
		</view>

		<!-- 当前最新物流状态 -->
		<view v-if="currentTrace" class="current-status">
			<view class="status-icon">
				<text class="icon">{{ getStatusIcon(currentTrace.title) }}</text>
			</view>
			<view class="status-info">
				<text class="status-text">{{ currentTrace.title }}</text>
				<text class="status-desc">{{ currentTrace.desc }}</text>
				<view class="courier-info" v-if="currentTrace.courier">
					<text class="courier-text">快递员：{{ currentTrace.courier.name }}</text>
					<text class="contact-text" @click="contactCourier(currentTrace.courier.phone)">联系</text>
				</view>
				<text class="status-time">{{ currentTrace.time }}</text>
			</view>
		</view>

		<!-- 物流轨迹时间轴（滚动区域） -->
		<scroll-view class="timeline-scroll" :style="{ height: scrollHeight + 'px' }" scroll-y>
			<view class="timeline-container">
				<TimelineItem 
					v-for="(item, index) in deliverTraceList" 
					:key="index"
					:title="item.title"
					:desc="item.desc"
					:time="item.time"
					:is-active="item.isActive"
					:show-line="index < deliverTraceList.length - 1"
					:show-dot-bg="index === 0"
				/>
				<view v-if="deliverTraceList.length === 0 && !loading" class="empty-trace">
					暂无物流轨迹
				</view>
			</view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="bottom-actions">
			<button class="action-btn" @click="viewDetails">查看详情</button>
			<button class="action-btn" @click="copyAllInfo">复制全部信息</button>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted, computed } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import TimelineItem from '@/components/TimelineItem.vue'
	import { queryDeliverTrace } from '@/api/order'

	// 响应式数据
	const orderNo = ref('')
	const scrollHeight = ref(600)
	const deliverTraceList = ref([])
	const loading = ref(false)

	// 当前最新一条物流（用于头部状态展示）
	const currentTrace = computed(() => {
		return deliverTraceList.value.length > 0 ? deliverTraceList.value[0] : null
	})

	// 从路由参数获取运单号
	onLoad((options) => {
		if (options.orderNo) {
			orderNo.value = options.orderNo
			getDeliverTrace()
		} else {
			// 无参数时使用模拟数据（仅用于演示）
			loadMockData()
		}
	})

	// 计算滚动区域高度（减去头部、当前状态、底部等固定高度）
	onMounted(() => {
		uni.getSystemInfo({
			success: (res) => {
				// 64px 约等于 128rpx，根据实际布局调整
				const headerHeight = 140   // 头部高度（rpx）
				const statusHeight = 200   // 当前状态高度（rpx）
				const bottomHeight = 120   // 底部按钮高度（rpx）
				const pxRatio = res.windowWidth / 750
				scrollHeight.value = res.windowHeight - (headerHeight + statusHeight + bottomHeight) * pxRatio - 40
			}
		})
	})

	// 获取真实物流轨迹
	const getDeliverTrace = () => {
		if (!orderNo.value) return
		loading.value = true
		const params = {
			number: orderNo.value,
			company: ''  // 可传入快递公司编码
		}
		queryDeliverTrace(params).then(response => {
			if (response.code === 200 && response.data) {
				// 按时间倒序排列（最新的在前）
				const list = response.data.sort((a, b) => 
					new Date(b.time) - new Date(a.time)
				).map((item, index) => ({
					...item,
					isActive: index === 0
				}))
				deliverTraceList.value = list
			} else {
				uni.showToast({ title: '未查询到物流信息', icon: 'none' })
				deliverTraceList.value = []
			}
		}).catch(error => {
			console.error('查询物流轨迹失败:', error)
			uni.showToast({ title: '查询物流信息失败', icon: 'error' })
			deliverTraceList.value = []
		}).finally(() => {
			loading.value = false
		})
	}

	// 模拟数据（用于无参数时演示）
	const loadMockData = () => {
		orderNo.value = 'JDVA40141037033'
		deliverTraceList.value = [
			{ title: '已代收', desc: '您的快件已由[门卫]代收，快递员:马新宽、联系...', time: '2026-01-11 17:32:32', isActive: true, courier: { name: '马新宽', phone: '13800138000' } },
			{ title: '派送中', desc: '快件已投递至【北京海淀区北京大学菜鸟驿站】...', time: '2026-01-11 15:20:10', isActive: false },
			{ title: '运输中', desc: '快件已到达【北京转运中心】', time: '2026-01-10 08:45:22', isActive: false },
			{ title: '运输中', desc: '快件已从【上海转运中心】发出', time: '2026-01-09 20:12:05', isActive: false },
			{ title: '已揽件', desc: '快件已被【上海浦东营业部】揽收', time: '2026-01-09 14:30:00', isActive: false }
		]
	}

	// 复制运单号
	const copyTrackingNumber = (text) => {
		uni.setClipboardData({
			data: text,
			success: () => uni.showToast({ title: '已复制', icon: 'success' })
		})
	}

	// 联系快递员
	const contactCourier = (phone) => {
		uni.showModal({
			title: '联系快递员',
			content: `拨打 ${phone} ？`,
			success: (res) => {
				if (res.confirm) uni.makePhoneCall({ phoneNumber: phone })
			}
		})
	}

	// 查看详情（示例）
	const viewDetails = () => {
		uni.showToast({ title: '功能开发中', icon: 'none' })
	}

	// 复制全部物流信息
	const copyAllInfo = () => {
		let info = `京东物流\n运单号：${orderNo.value}\n`
		if (currentTrace.value) {
			info += `状态：${currentTrace.value.title}\n`
			if (currentTrace.value.courier) info += `快递员：${currentTrace.value.courier.name}\n`
			info += `\n物流轨迹：\n`
		}
		deliverTraceList.value.forEach(item => {
			info += `${item.time} ${item.title} ${item.desc}\n`
		})
		uni.setClipboardData({
			data: info,
			success: () => uni.showToast({ title: '已复制全部信息', icon: 'success' })
		})
	}

	// 根据状态显示图标（可根据实际需求扩展）
	const getStatusIcon = (title) => {
		const map = {
			'已代收': '📦',
			'派送中': '🚚',
			'运输中': '🚛',
			'已揽件': '📦',
			'已签收': '✅'
		}
		return map[title] || '●'
	}
</script>

<style lang="scss" scoped>
	.logistics-container {
		display: flex;
		flex-direction: column;
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
		box-sizing: border-box;
	}

	/* 头部快递信息 */
	.logistics-header {
		height: 140rpx;
		background: #fff;
		border-radius: 32rpx;
		padding: 20rpx;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.logo {
			width: 100rpx;
			height: 100rpx;
			flex-shrink: 0;
		}

		.company-info {
			margin-left: 20rpx;
			flex: 1;

			.company-name {
				font-size: 32rpx;
				font-weight: bold;
				display: block;
				margin-bottom: 8rpx;
			}

			.tracking-number {
				display: flex;
				align-items: center;

				.number {
					font-size: 28rpx;
					color: #666;
				}

				.copy-btn {
					font-size: 28rpx;
					color: #1B64F0;
					margin-left: 16rpx;
					padding: 0 8rpx;
					background: #f0f6ff;
					border-radius: 8rpx;
				}
			}
		}
	}

	/* 当前状态卡片 */
	.current-status {
		background: #fff;
		border-radius: 24rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		display: flex;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);

		.status-icon {
			width: 80rpx;
			height: 80rpx;
			background: #1aad19;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 20rpx;
			flex-shrink: 0;

			.icon {
				color: #fff;
				font-size: 44rpx;
			}
		}

		.status-info {
			flex: 1;

			.status-text {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				display: block;
				margin-bottom: 8rpx;
			}

			.status-desc {
				font-size: 26rpx;
				color: #666;
				line-height: 1.4;
				margin-bottom: 12rpx;
			}

			.courier-info {
				background: #f8f8f8;
				border-radius: 12rpx;
				padding: 16rpx;
				margin-bottom: 12rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.courier-text {
					font-size: 26rpx;
					color: #333;
				}

				.contact-text {
					font-size: 26rpx;
					color: #1aad19;
					padding: 0 12rpx;
				}
			}

			.status-time {
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	/* 时间轴滚动区域 */
	.timeline-scroll {
		background: #fff;
		border-radius: 32rpx;
		margin-bottom: 20rpx;
		overflow: hidden;
	}

	.timeline-container {
		padding: 20rpx 30rpx;
		box-sizing: border-box;
	}

	.empty-trace {
		text-align: center;
		padding: 60rpx 0;
		color: #999;
		font-size: 28rpx;
	}

	/* 底部操作栏 */
	.bottom-actions {
		display: flex;
		justify-content: space-around;
		padding: 20rpx 0;
		background: #fff;
		border-radius: 32rpx;
		margin-top: auto;

		.action-btn {
			width: 300rpx;
			height: 80rpx;
			line-height: 80rpx;
			background: #f0f6ff;
			color: #1B64F0;
			border-radius: 40rpx;
			font-size: 28rpx;
			border: none;
			padding: 0;
			margin: 0;

			&::after {
				border: none;
			}
		}
	}
</style>