import React, { useEffect, useState } from 'react'
import useRequest from '@ahooksjs/use-request/es'
import InfiniteScroll from 'react-infinite-scroll-component'

import { List, Spin } from 'antd'

import { IMyCollectionItem, PersonalService } from 'Personal/Personal.service'

import styles from '../css/PersonalIndex.module.scss'
import ArticleCard from 'Indepth/components/ArticleCard'

/**我的足迹 */
const FootPrintComponent: React.FC = () => {
  const pageSize = 10
  const [currentPage, setCurrentPage] = useState<number>(1)
  const [hasMore, setHasMore] = useState<boolean>(false) // 列表加载更多
  const [listData, setListData] = useState<IMyCollectionItem[]>([])

  const { loading: listLoading, run } = useRequest(PersonalService.getFootPrintList, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      setListData([...listData, ...(res?.List || [])])
      setHasMore(res ? !res?.Paging?.IsEnd : false)
    }
  })

  useEffect(() => {
    setListData([])
    run(pageSize, currentPage)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const handleCancelCollection = (articleID: number) => {
    const findIndex = listData.findIndex(item => item.ArticleId === articleID)
    if (findIndex === -1) return
    const newList = JSON.parse(JSON.stringify(listData))
    newList[findIndex].IsCollect = !newList[findIndex].IsCollect
    newList[findIndex].CollectNum = newList[findIndex].IsCollect
      ? newList[findIndex].CollectNum + 1
      : newList[findIndex].CollectNum - 1
    setListData(newList)
  }

  const handleGetMore = () => {
    if (listLoading || !hasMore) return
    setCurrentPage(currentPage + 1)
    run(pageSize, currentPage + 1)
  }
  return (
    <Spin spinning={listLoading}>
      <div className={`${styles['collection-wrapper']}`}>
        <InfiniteScroll
          dataLength={listData?.length || 0}
          next={handleGetMore}
          hasMore={hasMore}
          loader={null}
          scrollableTarget="scrollableDiv"
        >
          <List
            dataSource={listData || []}
            renderItem={(item: IMyCollectionItem, index) => (
              <ArticleCard
                key={item.ArticleId}
                articleItem={item}
                jumpType="theme"
                sizeType="smcard"
                className="m-b-sm"
                onCollect={handleCancelCollection}
              />
            )}
          />
        </InfiniteScroll>
      </div>
    </Spin>
  )
}

export default FootPrintComponent
