import {Image, Text, View} from "@tarojs/components";
import {FC, useCallback, useEffect, useState} from "react";
import {CourseDepData, curriculum} from "@/api";
import './videoInfo.scss'
import Catalogue from "./components/catalogue";
import Course from "./components/course";
import Taro from "@tarojs/taro";
import eventsIndex from "@/hooks/eventsIndex";

const VideoInfo: FC = () => {
  const {id, depId} = Taro.getCurrentInstance()?.router?.params as any
  const [data, setData] = useState<CourseDepData | null>(null)
  const [playId, setPlayId] = useState<number | null>(null)
  const [preview, setPreview] = useState(false)


  const getData = async () => {
    const res = await curriculum.courseDep(id, depId)
    if (res) {
      setData(res)
    }
    if (playId) { //  用于自动播放 判断当前课程是否完成
      currentVideo(res)
    }
  }

  function setHors(is_complete: boolean, play_id: number) {
    setPreview(is_complete)
    setPlayId(play_id)
  }

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


  /** 播放下一个视频 */
  const playNext = useCallback(() => {
    const flats: Hour[] = Object.values(data?.hours || {}).flat(Infinity) as Hour[]
    if (playId === flats?.[flats.length - 1]?.id) {
      Taro.showModal({title: '当前课程结束'})
      eventsIndex.trigger(id)
      return;
    }
    for (const [index, flat] of flats.entries()) {
      if (flat.id === playId) {
        const next = flats[index + 1]
        if (next) {
          Taro.showModal({
            title: '继续播放下个视频',
            success({confirm}) {
              if (confirm) {
                setPlayId(next.id)
                setPreview(false)
              }
            }
          })
        }
        return
      }
    }
  }, [playId, data])

  /**
   * 判断当前课程是否完成
   */
  const currentVideo = useCallback((data: CourseDepData) => {
    const courseHourRecordsFinish = data?.learn_hour_records.find(d => d.id === playId)?.courseHourRecordsFinish
    if (typeof courseHourRecordsFinish === 'number') {
      if (courseHourRecordsFinish === 1) {
        playNext()
      } else {
        Taro.showModal({
          title: '有考卷还未完成',
          content: '未完成考卷不能播放下一个视频',
          confirmText: '考试',
          success({confirm}) {
            confirm && Taro.navigateTo({url: `/pages/business/test/test?testId=${playId}`})
          }
        })
      }
    }
  }, [playId, data])

  Taro.useDidShow(() => {
    data && getData()
  })



  return (
    <>
      <View className='content'>
        <View className='content-video'>
          {playId ?
            <Course id={playId} courseId={id} curEnd={getData} preview={preview}/>
            : <Image src={data?.course.thumb || ''} className='image' mode='scaleToFill'/>}
        </View>

        <View className='header'>
          <View className='flex justify-between text-muted'>
            <Text className='font-34 text-warning'>{data?.is_required ? '必修' : '选修'}</Text>
            <Text>{data?.course.class_hour}课时</Text>
          </View>
          <View className='font-weight font-40 my-3'>{data?.course.title}</View>
          <View className='text-muted font-26'>
            <Text>学习进度{data?.learn_hour_records.length || 0}/{data?.course.class_hour}</Text>
          </View>
        </View>
        <Catalogue data={data} setHors={setHors} id={id} playId={playId}/>
      </View>
    </>
  )
}

export default VideoInfo
