import {View} from "@tarojs/components";
import {FC, useEffect, useState} from "react";
import Taro, {useReachBottom, useRouter} from "@tarojs/taro";
import {courseApi} from "@/api";
import VideoCover from "@/components/videoCover/videoCover";
import {formatMinute} from "@/utils/time";
import Empty from "@/components/empty/empty";

const CourType: FC = () => {
  const params = useRouter().params
  const [total, setTotal] = useState(0)
  const [data, setData] = useState<Curriculum[]>([])
  const [page, setPage] = useState<Pages>({
    page: 1,
    page_size: 10
  })

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

  async function getData() {
    if (!params.type) return;
    try {
      const res = await courseApi.courseType(params.type, page)
      setTotal(res.total)

      const oldData: Curriculum[] = JSON.parse(JSON.stringify(data))

      res.data.forEach(d => {
        const index = oldData.findIndex(x => x.id === d.id)
        if (index === -1) {
          oldData.push(d)
        } else {
          oldData.splice(index, 1, d)
        }
      })
      setData(oldData)
    } catch (e) {
    }
  }


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

  Taro.useLoad(() => {
    Taro.setNavigationBarTitle({
      title: ['课程', '必修课', '选修课', '已完成', '未完成'][params.type ? Number(params.type) : 0]
    })
  })

  return (
    <>
      {
        data.length > 0 ?
          <>
            <View className='py-2 flex justify-between flex-wrap'>
              {
                data.map(c => <VideoCover
                  thumb={c.thumb}
                  title={c.title}
                  id={c.id}
                  depId={c.id}
                  key={c.id}
                  time={formatMinute(c.course_duration)}
                />)
              }
            </View>
            <View className='text-center font-24 text-dark'>暂无更多</View>
          </>
          : <Empty name='暂无数据'/>
      }
    </>
  )
}

export default CourType
