<template>
	<view class="container">
		<!-- 顶部标签页 -->
		<u-subsection :list="tabList" :current="curNow" @change="sectionChange" mode="subsection"></u-subsection>

		<!-- 列表区域 -->
		<scroll-view scroll-y class="list-container" @scrolltolower="loadMore" refresher-enabled
			@refresherrefresh="onRefresh" :refresher-triggered="isRefreshing">
			<exception-item v-for="item in exceptionList" :key="item.orderNo" :order="item"  />

			<!-- 加载更多 -->
			<u-loadmore :status="loadMoreStatus" @loadmore="loadMore" />
		</scroll-view>

		<!-- 底部搜索框 -->
		<view class="search-bar fixed-bottom">
			<u-search v-model="searchKeyword" placeholder="请输入物流单号/订单编号" :show-action="false" @search="handleSearch"
				height="80rpx" shape="round">
			</u-search>
			<u-icon name="scan" size="28" color="#19be6b" @click="handleScan" />
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import ExceptionItem from './components/ExceptionItem.vue';

	// 标签页配置
	const tabList = ['待处理订单', '历史异常签收'];
	const curNow = ref(0);

	// 定义方法，注意在 setup 中不需要 this，直接访问响应式引用  
	function sectionChange(index) {
		curNow.value = index;
	}

	// 列表数据
	const exceptionList = ref([]);
	const page = ref(1);
	const loadMoreStatus = ref('loadmore'); // loadmore, loading, nomore
	const isRefreshing = ref(false);

	// 搜索相关
	const searchKeyword = ref('');

	// 初始化数据
	onMounted(() => {
		loadData();
	});

	// 加载数据
	const loadData = async (reset = false) => {
		if (reset) {
			page.value = 1;
			exceptionList.value = [];
		}

		// 模拟数据
		const mockData = [{
			orderNo: '5698542',
			expressNo: 'JDX0010258745151',
			estimatedPrice: '16.8',
			pusher: '涨涨涨',
			pushTime: '2024-06-15 15:00:00'
		}];

		// 这里替换为实际的API调用
		setTimeout(() => {
			exceptionList.value = [...exceptionList.value, ...mockData];
			loadMoreStatus.value = 'nomore';
		}, 1000);
	};

	// 下拉刷新
	const onRefresh = async () => {
		isRefreshing.value = true;
		await loadData(true);
		isRefreshing.value = false;
	};

	// 加载更多
	const loadMore = () => {
		if (loadMoreStatus.value === 'nomore') return;
		loadMoreStatus.value = 'loading';
		page.value++;
		loadData();
	};

	// 搜索处理
	const handleSearch = () => {
		loadData(true);
	};

	// 扫码处理
	const handleScan = () => {
		uni.scanCode({
			success: (res) => {
				searchKeyword.value = res.result;
				handleSearch();
			}
		});
	};
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		box-sizing: border-box;
	}

	.list-container {
		flex: 1;
		padding: 12px;
		box-sizing: border-box;
	}

	.search-bar {
		padding: 12px;
		box-sizing: border-box;
		background-color: #fff;
		border-top: 1px solid #eee;

		:deep(.u-search) {
			background-color: #f5f5f5;
		}
	}
</style>