import {FC, ReactNode, 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'
import ArticlesBox from "@/components/articlesBox/articlesBox";

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

  async function getData() {
    const res = await HomeApi.course(page, 4)
    setArticles(res.articles)
    setTotal(res.course.total)
    const newData = res.course.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
    }, JSON.parse(JSON.stringify(data)) as Curriculum[])
    setData(newData ?? [])
  }

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

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

  let examines: ReactNode | undefined
  if (articles.length > 0) {
    examines = (
      <View className="mb-5">
        <View className='bg-white rounded-20 clip px-3'>
          <View className='mt-3 mb-3 font-32 bold text-dark'>推荐文章</View>
          {
            articles.map(d => <ArticlesBox data={d}/>)
          }
        </View>
      </View>
    )
  }

  let videos: ReactNode | undefined
  if (data.length > 0) {
    videos = (
      <View>
        <Image src={courseTag} mode='widthFix' className={styles.courseTag}/>
        <View className={'pb-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}
              marker={`共${c.class_hour}节`}
            />)
          }
        </View>
      </View>
    )
  }

  return (
    <>
      {examines}
      {videos}
      <View className='text-center font-24 text-dark'>暂无更多</View>
    </>
  )
}

export default CurRecommended
