<template>
	<u-popup
		v-model="show"
		mode="bottom"
		length="90%"
		:mask-close-able="false"
		closeable
		@close="handleClose"
	>
		<view>
			<view
				style="width: 90%; height: 50px; position: fixed; top: 0; z-index: 1; background-color: #fff;"
			>
				<uni-search-bar
					v-model="searchQuery.keyword"
					placeholder="输入搜索商品"
					bgColor="#EEEEEE"
					clearButton="auto"
					cancelButton="none"
					@confirm="search"
				/>
			</view>
			<view style="height: 120rpx"></view>
			<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)"
				/>
				<view style="padding-bottom: 40rpx;">
					<u-loadmore :status="status" icon-type="flower" @loadmore="loadMore" />
				</view>
			</view>
			<view v-else><u-loadmore status="nomore" icon-type="flower" /></view>
		</view>
	</u-popup>
</template>

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

let props = defineProps({
	show: {
		type: Boolean,
		default: false,
	},
});

let emits = defineEmits(['search-close', 'cateGoryGoods']);

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();
};

let searchGoods = (item: any) => {
	emits('search-close', false);
	emits('cateGoryGoods', item);
};

// 点击加载更多 status = loadmore 时生效
let loadMore = () => {
	// 判断是否还有下一页数据
	if (searchQuery.page * searchQuery.limit >= total.value) return (status.value = 'nomore');
	// // 判断是否正在请求其它数据，如果是，则不发起额外的请求
	if (status.value === 'loading') return;
	searchQuery.page += 1;
	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];
		}
	});
};

let handleClose = () => {
	searchList.value = [];
	emits('search-close', false);
};

defineExpose({
	searchQuery,
	initList,
});
</script>

<style></style>
