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 ArticleCard from 'Indepth/components/ArticleCard'
import styles from '../css/PersonalIndex.module.scss'

/**我的收藏 */
const CollectionComponent: 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.getMyCollectionList, {
    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.splice(findIndex, 1)
    setListData(newList)
  }

  const handleGetMore = () => {
    console.log(listLoading, hasMore)
    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) => (
              <ArticleCard
                key={item.ArticleId}
                articleItem={item}
                jumpType="theme"
                sizeType="smcard"
                className="m-b-sm"
                onCollect={handleCancelCollection}
              />
            )}
          />
        </InfiniteScroll>
      </div>
    </Spin>
  )
}

export default CollectionComponent
