<template>
	<view>
		<slot></slot>
		<fs-empty v-if="!state.loading && !state.dataList.length"></fs-empty>
		<template v-else>
			<fs-divider v-if="!state.hasMore">{{ nomore }}</fs-divider>
		</template>
	</view>
</template>

<script>
/**
 * 加载更多组件
 * @description 加载更多组件
 * @property {Function} fetchList 获取数据的方法
 * @property {Number} pageSize 分页大小
 * @property {Boolean} pullDownRefresh 是否开启下拉刷新
 * @property {Boolean} autoCall 是否自动调用查询方法
 * @property {String} nomore 没有更多文字
 */
export default {
	name: 'fs-loadmore'
}
</script>

<script setup>
import { reactive, toRef } from 'vue'

const props = defineProps({
	modelValue: {
		type: Array,
		default() {
			return []
		}
	},
	fetchList: Function,
	pageSize: {
		type: Number,
		default: 20
	},
	pullDownRefresh: Boolean,
	autoCall: {
		type: Boolean,
		default: true
	},
	nomore: {
		type: String,
		default: '没有更多了～'
	}
})
const emits = defineEmits(['update:modelValue'])

const state = reactive({
	loading: true,
	dataList: props.modelValue,
	pageNo: 1,
	pageSize: props.pageSize,
	hasMore: true
})

const query = loadmore => {
	state.loading = true
	if (loadmore) {
		state.pageNo++
	} else {
		state.pageNo = 1
	}
	return props
		.fetchList({
			pageNo: state.pageNo,
			pageSize: props.pageSize
		})
		.then(res => {
			state.hasMore = res.length >= state.pageSize
			state.dataList = loadmore ? [...state.dataList, ...res] : res
			emits('update:modelValue', state.dataList)
		})
		.finally(() => {
			state.loading = false
		})
}
props.autoCall && query()

const refresh = () => {
	state.dataList = []
	emits('update:modelValue', state.dataList)
	return query()
}

defineExpose({
	query,
	refresh,
	hasMore: toRef(state, 'hasMore'),
	pullDownRefresh: props.pullDownRefresh
})
</script>

<style></style>
