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 arrowRight from '@/static/img/arrow-right.png'
import PageScript from "@/components/pageScript/pageScript";

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 ?? [])
  }

  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'>
          <Text className='font-32'>推荐文章</Text>
          <View className='font-24 text-muted flex align-center' onClick={jumpArticles}>
            <Text>查看更多</Text>
            <Image src={arrowRight} mode='widthFix' style={{width: '20rpx', height: '20rpx'}}/>
          </View>
        </View>
        {articles.map(d => <ArticlesBox 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
