/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from 'react'

import { View, Image } from '@tarojs/components'

import Taro from '@tarojs/taro'

import './index.scss'

import { getRecord } from '../../api/qrcode'

import Tip from '../../utils/tip'

type recordsListType = {
    id: string,
    imgUrl: string,
    hasGot: number,
    name: string,
    [key: string]: any
}

const QueryRecord: React.FC = () => {

    const [page , setPage] = useState<number>(1)

    const [recordsList, setRecordsList] = useState<recordsListType[]>([])

    // 请求一次之后, 如果记录已经全部请求到了, 将不会再次请求， 不会再次请求
    const [stopRequest, setStopRequest] = useState<boolean>(false)

    // 获取查询记录

    const GetRecord = async (): Promise<void> => {

        Tip.loading('努力加载记录中~')

        const data = await getRecord({page})
        
        Tip.loaded()

        // 当当前返回数组为空时
        if(data.entityList.length === 0) {
            Tip.toast('没有更多记录了')
            setStopRequest(true)
            return 
        }

        const oldRecords = [...recordsList]
        const newRecords = oldRecords.concat(...data.entityList)
        setRecordsList(newRecords)
    }

    Taro.useReachBottom(() => setPage(page + 1))

    useEffect( () => {
        if(stopRequest) return
        GetRecord()
    }, [ page])

    return (
        <View className='QueryRecord'>
            {
                recordsList?.map(item => (
                    <View className='QueryRecord-item' key={item.id}>
                        <Image src={item.imgUrl} mode='aspectFill' />
                        <View className='shop-info'>
                            <View className='shop-version'>
                                {item.name}
                            </View>
                            <View className='shop-cate'>
                                3-4岁第一阶段
                            </View>
                        </View>

                        <View className='button'>
                            未领取
                        </View>
                    </View>
                ))
            }
        </View>
    )
}

export default QueryRecord
