import {FC, useEffect, useState} from "react";
import {Image, View} from "@tarojs/components";
import {HomeApi} from "@/api";
import {useReachBottom} from "@tarojs/taro";
import styles from "../home.module.scss";
import VideoCover from "@/components/videoCover/videoCover";
import courseTag from '@/static/img/courseTag.png'

const CurRecommended: FC = () => {
  const [page, setPage] = useState(1)
  const [data, setData] = useState<Curriculum[]>([])
  const [total, setTotal] = useState(0)

  async function getData() {
    const res = await HomeApi.course(page, 4)
    setTotal(res.total)
    const newData = res.data.reduce((pre, cut) => {
      const index = pre.findIndex(d => d.id === cut.id)
      if (index === 1) {
        pre.push(cut)
      } else {
        pre.splice(index, 1, cut)
      }
      return pre
    }, data)
    setData(newData)
  }

  useEffect(() => {
    getData()
  }, [page])

  useReachBottom(() => {
    data.length < total && setPage(page + 1)
  })

  return (
    <>
      {
        data.length > 0 && <View className='mt-4'>
          <Image src={courseTag} mode='widthFix' className={styles.courseTag}/>
          <View className={'py-2 flex justify-between flex-wrap ' + styles.videoListBox}>
            {
              data.map(c => <VideoCover
                  thumb={c.thumb}
                  title={c.title}
                  id={c.id}
                  depId={c.id}
                  key={c.id}
                />)
            }
          </View>
        </View>
      }
    </>
  )
}

export default CurRecommended
