import {FC, ReactNode, useEffect, useState} from "react";
import {Image, Text, View} from "@tarojs/components";
import {HomeApi} from "@/api";
import Taro, {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";
import PageScript from "@/components/pageScript/pageScript";
import IconFont from "@/components/IconFont";

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.home()
    setArticles(res.articles)
    setTotal(res.courses.total)
    const newData = res.courses.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 ?? [])
  }

  function jumpArticles() {
    Taro.navigateTo({url: '/pages/preview/jumpArticles/jumpArticles'})
  }

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

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

  let examines: ReactNode | undefined
  if (articles.length > 0) {
    examines = (
      <View className='bg-white rounded-20 clip px-3'>
        <View className='mt-3 bold text-dark flex justify-between align-center mb-2'>
          <Text className='font-32'>推荐文章</Text>
          <View className='font-24 text-muted flex align-center pl-2 py-2' onClick={jumpArticles}>
            <Text>查看更多</Text>
            <IconFont name={'chevron-right'} size={14} />
          </View>
        </View>
        {articles.map(d => <ArticlesBox key={d.id} data={d}/>)}
      </View>
    )
  }

  let videos: ReactNode | undefined
  if (data.length > 0) {
    videos = (
      <View className='mt-3'>
        <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}
      <PageScript/>
    </>
  )
}

export default CurRecommended
