import { BaseTableProps } from '@/components/Table/src/types';
import { reactive, Ref, watchEffect, nextTick } from 'vue';
/**
 * 用于加载明细的更多数据 ==> 表格展示
 */
function useLoadMoreData(detailsList: Ref, feesetSetingDetailTable: BaseTableProps) {
    // 加载的数据的容器
    const stateMore = reactive({
        startStatus: true,
        allData: false,//加载全部数据状态
        loading: false,//加载的load状态
        pageNum: 0,//当前的页数
        tempTableLayerData: [],//暂时存储的表格数据
    })
    let timer: any = null

    // 加载数据
    function loadMore() {
        stateMore.loading = true
        // 全部数据
        const layerList = detailsList.value;
        // 数据总量
        const total = layerList.length;
        // 每页条数
        const pageSize = 9;
        // 如果加载结束就返回
        console.log(stateMore.pageNum, pageSize, ":页数 * 页码");
        if (stateMore.pageNum * pageSize > total) return stateMore.loading = false;
        clearTimeout(timer)
        timer = setTimeout(() => {
            stateMore.loading = false
        }, 1000)
        // 计算每页的数据
        const OnePageData = layerList.slice(
            stateMore.pageNum * pageSize,
            (stateMore.pageNum + 1) * pageSize
        );
        // 每下拉一页之后merge到前面的数据中
        const mergeData = stateMore.tempTableLayerData.concat(OnePageData);
        // 起始渲染数据
        if (stateMore.startStatus && mergeData.length > 5) {
            let currentIndex = 0
            while (currentIndex < mergeData.length) {
                let timer2_
                const currentData = mergeData[currentIndex]
                timer2_ = setTimeout(() => {
                    feesetSetingDetailTable.dataSource.push(currentData)
                    clearTimeout(timer2_)
                }, 500);
                currentIndex++
            }
            stateMore.tempTableLayerData = mergeData;
            stateMore.startStatus = false
        } else {
            stateMore.tempTableLayerData = mergeData;
            //形成最后的数据给table组件使用
            feesetSetingDetailTable.dataSource = stateMore.tempTableLayerData;
        }
        if (stateMore.tempTableLayerData.length === total) stateMore.allData = true;
        stateMore.pageNum++;
    }


    // 重置数据
    function resetMore() {
        stateMore.loading = false
        stateMore.allData = false
        stateMore.startStatus = true
        stateMore.pageNum = 0
        stateMore.tempTableLayerData = []
    }

    return {
        loadMore,
        resetMore,
        stateMore
    }
}

export {
    useLoadMoreData
}