import {FC, useCallback, useEffect, useState} from "react";
import HVideo from "@/components/video/video";
import {curriculum, HourPlayData} from "@/api";
import {Profile} from '@/store'
import Taro from "@tarojs/taro";
import unique_ident from "@/hooks/unique_ident";
import Single from "@/components/topic/single";

interface Props {
  id: number,
  courseId: number
  preview: boolean
  curEnd: (test?: boolean) => void
}

const Course: FC<Props> = ({id, courseId, preview, curEnd}) => {
  const [breakpoints, setBreakpoints] = useState<number[]>([])                // 断点
  const [isFull, setIsFull] = useState(false)
  const [examAll, setExamAll] = useState<Record<number, ShareSubject[]>>([])  // 题库
  const [data, setData] = useState<HourPlayData | null>(null)
  const [time, setTime] = useState<number>(0) // 进入断点的时间
  const [testId, setTestId] = useState<number | null>(null)
  const {user} = Profile.useContainer()

  async function onEnded() {
    // 学习记录
    const startRecording = unique_ident.get()
    startRecording && await curriculum.curEnd(courseId, id, {...startRecording, duration: data?.duration!}) // 结束
    unique_ident.remove()

    if (testId) {
      if (preview) {
        Taro.showModal({
          title: "是否前往考试",
          success({confirm}) {
            if (confirm) {
              curEnd(true)
              Taro.navigateTo({url: `/pages/business/test/test?testId=${testId}`})
            } else {
              curEnd()
            }
          }
        })
        return
      }
      Taro.navigateTo({url: `/pages/business/test/test?testId=${testId}`})
      curEnd(true)
    } else {
      curEnd()
    }
  }

  async function getData() {
    unique_ident.put(id, Date.now())
    const res = await curriculum.hourPlay(courseId, id)
    if (res) {
      setData(res)
      setBreakpoints(res.timeList)
      setExamAll(res.hourExamQuestions || [])
      setTestId(res?.hour_test?.id || null)
    }
  }

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

  const examination = useCallback((result: boolean) => {
    if (!time) return
    const {id: question_id, question_type} = examAll?.[time]?.[0]
    curriculum.answerRecord(id, {
      is_pass: result,
      user_id: user?.id!,
      time: time,
      question_type,
      question_id
    })
    setTime(0)
  }, [time])

  return (
    <>
      <HVideo
        duration={data?.duration || 0}
        preview={preview}
        src={data?.url || ''}
        onEnded={onEnded}
        breakpoint={breakpoints}
        fullChange={(fullScreen) => setIsFull(fullScreen)}
        onBreakpoint={(now) => {
          time !== now && setTime(now)
        }}>
        <Single
          full={isFull}
          examination={examination}
          topic={examAll?.[time]?.[0]}/>
      </HVideo>
    </>
  )
}
export default Course
