<template>
    <PullRefresh v-model="refreshing" @refresh="onRefresh">
        <slot name="header"></slot>
        <List v-model:loading="showLoading" :finished="finished" :finished-text="finishedText" @load="onLoad">
            <template v-for="(item, index) in tableSource" :key="index">
                <slot :item="item" :index="index"></slot>
            </template>
        </List>
        <slot name="footer"></slot>
    </PullRefresh>
</template>

<script lang="ts" setup>
import { shallowRef, computed, PropType } from 'vue'
import { List, PullRefresh } from 'vant'

const props = defineProps({
    loading: {
        type: Boolean,
    },
    total: {
        type: Number,
        default: 0,
    },
    dataList: {
        // eslint-disable-next-line
        type: Array as PropType<any>,
        required: true
    },
    finishedText: {
        type: String,
        default: '没有更多了',
    }
})

const emit = defineEmits(['update:loading', 'update:dataList', 'refresh'])
const refreshing = shallowRef(false) // 是否处于加载中状态
const finished = shallowRef(false) // 是否已加载完成所有数据

const showLoading = computed({
    get: () => props.loading,
    set: (val) => emit('update:loading', val)
})

const tableSource = computed({
    get: () => props.dataList,
    set: (val) => {
        emit('update:dataList', val)
    }
})

// 上拉加载
const onLoad = () => {
    const resolve = (data?: unknown[]) => {
        const list = tableSource.value
        if (refreshing.value) {
            list.length = 0
            refreshing.value = false
        }
        if (data) {
            list.push(...data)
        }
        if (list.length >= props.total) {
            finished.value = true
        }
        tableSource.value = list
    }
    emit('refresh', resolve)
}

// 下拉刷新
const onRefresh = () => {
    finished.value = false
    onLoad()
}
</script>