import {FC, useEffect, useState} from "react";
import {useDidShow} from "@tarojs/taro";
import {ScrollView, Swiper, SwiperItem, View} from "@tarojs/components";
import {Courses, CoursesKey, publicApi} from "@/api/public";
import VideoCover from "@/components/videoCover/videoCover";
import styles from '../index.module.scss'
import {formatMinute} from "@/utils/time";
import {userApi} from "@/api";
import Empty from "@/components/empty/empty";
import eventsIndex from "@/hooks/eventsIndex";

interface Props {
  categoryKey: CoursesKey
  setCategoryKey: (categoryKey: CoursesKey) => void
}

export const VideoList: FC<Props> = ({categoryKey, setCategoryKey}) => {
  const [data, setData] = useState<Courses>({
    is_finished: [],
    is_not_required: [],
    is_required: [],
    is_not_finished: [],
  })
  const [page, setPage] = useState(1)
  const [records, setRecords] = useState<LearnRecord[]>([])

  function screen(oldData: Curriculum[], data: Curriculum[]): Curriculum[] {
    return data.reduce((pre, cur) => {
      const index = pre.findIndex(d => d.id === cur.id)
      if (index === -1) {
        pre.push(cur)
      } else {
        pre.splice(index, 1, cur)
      }
      return pre
    }, oldData)
  }

  async function getData() {
    try {
      const res = await publicApi.course({page: page, pageSize: 10})
      const old: Courses = JSON.parse(JSON.stringify(data))
      setData({
        is_required: screen(old.is_required, res.is_required || []),
        is_not_required: screen(old.is_not_required, res.is_not_required || []),
        is_finished: screen(old.is_finished, res.is_finished || []),
        is_not_finished: screen(old.is_not_finished, res.is_not_finished || []),
      })
    } catch (e) {
    }
  }

  async function getRecords() {
    try {
      const {user_course_records} = await userApi.learningRecord()
      setRecords(user_course_records)
    } catch (e) {
    }
  }


  function rateOfLearning(id: number, class_hour: number): JSX.Element {
    switch (categoryKey) {
      case "is_required":
      case "is_not_required":
      case "is_not_finished":
        const find = records.find(d => d?.course_id === id)
        if (find) {
          if (class_hour === find.finished_count) {
            return <View>已完成</View>
          }
          return (<View>{`共${class_hour}节/已学${find.finished_count}节`}</View>)
        }
        return (<View>{`共${class_hour}节/已学0节`}</View>)
      case "is_finished":
        return <View>已完成</View>
    }
  }

  eventsIndex.on(({id}) => {
    if (id == null) return;
    for (const [index, notFinished] of data.is_not_finished.entries()) {
      if (notFinished.id === id) {
        data.is_finished.push(notFinished)
        data.is_not_finished.splice(index, 1)
        return
      }
    }
  })

  useDidShow(() => {
    getData().then()
    getRecords().then()
  })

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


  function changeSwiper(e) {
    const index = e.detail.current
    const categoryKeys: CoursesKey[] = Object.keys(data) as CoursesKey[]
    setCategoryKey(categoryKeys[index])
  }

  return (
    <Swiper className={styles.swiper} onChange={changeSwiper}
            current={Object.keys(data).findIndex(d => d === categoryKey)}>
      {
        Object.values(data).map((value) => <SwiperItem>
          <ScrollView scrollY className={styles.swiper} onScrollToLower={() => setPage(page + 1)}>
            <View className='py-2 flex justify-between flex-wrap'>
              {
                value?.length ? value?.map(c =>
                    <VideoCover
                      thumb={c.thumb}
                      title={c.title}
                      id={c.id}
                      depId={c.id}
                      key={c.id}
                      time={formatMinute(c.course_duration)}
                      content={rateOfLearning(c.id, c.class_hour)}
                    />)
                  : <Empty name='暂无课程'/>
              }
            </View>
          </ScrollView>
        </SwiperItem>)
      }
    </Swiper>
  )
}

