<template>
	<view style="padding: 24rpx;">
		<uni-search-bar
			v-model="searchQuery.keyword"
			placeholder="输入搜索商品"
			bgColor="#EEEEEE"
			clearButton="auto"
			cancelButton="none"
			@confirm="search"
		/>
		<view v-if="searchList.length !== 0">
			<goodsItem
				v-for="item in searchList"
				:src="item.picUrl"
				:name="item.name"
				:brief="item.brief"
				:counterPrice="item.counterPrice"
				:retailPrice="item.retailPrice"
				@tap="searchGoods(item)"
			/>
			<u-loadmore :status="status" icon-type="flower" />
		</view>
		<view v-else><u-loadmore status="nomore" icon-type="flower" /></view>
	</view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive } from 'vue';
import { getGoodsList } from '@/api/category';
import { onReachBottom } from '@dcloudio/uni-app';
import goodsItem from '@/components/goodsItem.vue';

let searchQuery = reactive({
	keyword: '',
	page: 1,
	limit: 10,
	categoryId: 0,
});

let status = ref('loadmore');
let total = ref(0);
let searchList = ref([] as any);

let search = (val: any) => {
	searchList.value = [];
	searchQuery.page = 1
	searchQuery.keyword = val.value;
	initList();
};

// 上拉加载数据
onReachBottom(() => {
	// 判断是否还有下一页数据
	if (searchQuery.page * searchQuery.limit >= total.value) return (status.value = 'nomore');
	// // 判断是否正在请求其它数据，如果是，则不发起额外的请求
	if (status.value === 'loading') return;
	searchQuery.page += 1;
	initList();
});

const searchGoods = (row: any) => {
	uni.navigateTo({ url: '/pages/goods/index?id=' + row.id });
};

onLoad((options: any) => {
	searchQuery.keyword = options.keyword;
	initList();
});

let initList = () => {
	status.value = 'loading';
	getGoodsList(searchQuery).then((res: any) => {
		if (res.data.data.total > 10) status.value = 'loadmore';
		else status.value = 'nomore';
		if (res.data.code === 200) {
			total.value = res.data.data.total;
			searchList.value = [...searchList.value, ...res.data.data.list];
		}
	});
};
</script>

<style lang="scss" scoped>
page {
	background-color: #fff;
}
</style>
