<template>
	<view>
		<!-- 顶部导航栏 -->
		<u-navbar :title="title" placeholder :autoBack="false" @leftClick="leftClick" leftIconSize='35' bgColor='#d3832a'
			leftIconColor='#ffffff' titleStyle='color:#ffffff'></u-navbar>
	</view>

	<!-- 头部 -->
	<slot name="head"></slot>
	<!-- 插槽 -->
	<template v-if="haveData">
		<slot name="body"></slot>
		<!-- 		<view v-show="isEnd" class="footer-end">
			到底啦 ~
		</view> -->
	</template>

	<template v-else>
		<view class="footer-end">暂时没有数据哦 ~</view>
	</template>
</template>

<script setup lang="ts">
	import {
		defineProps,
		ref,
		toRefs
	} from 'vue';

	import {
		onLoad,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'

	const props = defineProps({
		option: {
			type: Object,
			default: {

			}
		},
		title: {
			type: String
		},
		leftClick: {
			type: Function,
		}
	})

	let { title, isEnd, haveData } = toRefs(props.option)

	if (!title) title = ref('货无忧')

	// 是否请求完毕数据
	if (isEnd === undefined) isEnd = ref(false)

	// 下拉刷新请求页面
	const pullDownRefreshInitPage = props.option.pullDownRefreshInitPage || function () { console.log('刷新'); }
	// 触底加载请求页面
	const reachBottomInitPage = props.option.reachBottomInitPage || function () { }
	const leftClick = props.leftClick || function () { uni.navigateBack() }

	// 初始化执行
	onLoad(() => {
		// 初始化刷新
		// uni.startPullDownRefresh()
	})

	// 添加防抖函数
	let antiShake : any = null
	// 触底加载
	onReachBottom(() => {
		// 数据请求完毕, 不再请求
		if (isEnd.value) {
			return uni.showToast({
				icon: 'success',
				title: '数据已加载完毕'
			})
		}
		console.log('antiShake :>> ', antiShake);
		if (antiShake) {
			uni.hideLoading()
			// 清空定时器
			clearTimeout(antiShake)
			return antiShake = null
		}
		// 显示Loading, 并阻止点击屏幕
		uni.showLoading({
			title: '正在加载',
			mask: true
		})
		antiShake = setTimeout(async () => {
			// 触发触底回调
			await reachBottomInitPage()
			// 关闭Loading效果
			uni.hideLoading()
			// 清空定时器
			antiShake = null
		}, 500)
	})


	// 下拉刷新
	onPullDownRefresh(() => {
		const timer = setTimeout(async () => {
			// 触发下拉回调
			await pullDownRefreshInitPage()
			uni.stopPullDownRefresh()
			// 清除定时器
			clearTimeout(timer)
		}, 500)
	})

	// 触发下拉刷新
	function startPullDownRefresh() {
		console.log('触发下拉')
		uni.startPullDownRefresh()
	}

	defineExpose({ startPullDownRefresh })
</script>

<style>
	.footer-end {
		padding: 20upx 0;
		text-align: center;
	}
</style>