import {FC, useState} from "react";
import Tabs, {OnChangOpt} from "@/components/tabs/tabs";
import {Image, View} from "@tarojs/components";
import {CourseDepData, curriculum} from "@/api";
import Collapse from "@/components/collapse/collapse";
import Hours from "@/pages/business/videoInfo/components/hours";
import Taro from "@tarojs/taro";
import MyButton from "@/components/button/MyButton";
import videoEvents from "@/hooks/videoEvents";
import curRecord from '@/static/img/curRecord.png'
import hourRecord from "@/static/img/hourRecord.png"
import CustomPageContainer from "@/components/custom-page-container/custom-page-container";
import {Profile} from "@/store";
import LoginView from "@/components/loginView";

interface Props {
  data: CourseDepData | null
  setHors: (is_complete: boolean, id: number) => void
  id: number  //课程
  playId: number | null
}

const tabList = [
  {title: '介绍', value: 0},
  {title: '目录', value: 1},
  // {title: '评价', value: 2},
]


const Catalogue: FC<Props> = ({data, setHors, id, playId}) => {
  const [current, setCurrent] = useState(1)
  const [show, setShow] = useState(false)
  const [playing, setPlaying] = useState(false)
  const {token} = Profile.useContainer()


  videoEvents.onVideoState(({name}) => {
    switch (name) {
      case "pause":
        setPlaying(false)
        break
      case 'play':
        setPlaying(true)
        break
    }
  })


  // function onPause() {
  //   videoEvents.setVideoState('pause')
  // }

  function jumCurHistory() {
    if (playId) {
      Taro.navigateTo({url: `/pages/business/hourHistory/hourHistory?courseId=${id}&hourId=${playId}`})
    }
  }

  function tabChange({tab}: OnChangOpt) {
    setCurrent(tab?.value as number)
  }

  function getHors(chapter_id?: number): Hour[] | null {
    for (const d of Object.values(data?.hours || {})) {
      if (d[0].chapter_id === chapter_id) {
        return d
      }
    }
    return null
  }

  function chapters_complete(chapter: Chapters): boolean {
    const hors = getHors(chapter.id)
    if (hors) {
      for (const hor of hors) {
        const courseHourRecordsFinish = data?.learn_hour_records?.find(d => d.id === hor.id)?.courseHourRecordsFinish
        if (courseHourRecordsFinish === 0 || !courseHourRecordsFinish) {
          return false
        }
      }
      return true
    }
    return false
  }

  function upChaptersOver(is_complete: boolean, id: number, index: number) {
    if (!index) {
      setHors(is_complete, id)
    } else {
      const ok = chapters_complete((Object.values(data?.chapters || {})?.[index - 1]))
      if (!ok) {
        Taro.showModal({title: '上一章节未完成'})
        return
      }
      setHors(is_complete, id)
    }
  }

  function learning() {
    const flats: Hour[] = Object.values(data?.hours || {}).flat(Infinity) as Hour[]

    if (!flats.length) return;
    if (!data?.learn_hour_records?.length || data.learn_hour_records.length === data.learn_record?.hour_count) {
      if (flats[0].id === playId) {
        videoEvents.setVideoState('play')
      } else {
        setHors(!!data?.learn_hour_records?.length, flats[0].id)
      }
      return
    }


    if (data?.learn_hour_records.length) {
      const lastHours = data.learn_hour_records[data.learn_hour_records.length - 1]

      if (lastHours.courseHourRecordsFinish < 1) {
        Taro.showModal({
          title: '考卷未完成,是否前往',
          content: '考卷未完成不能播放下一个视频',
          confirmText: '前往考试',
          cancelText: '观看视频',
          async success({confirm}) {
            if (confirm) {
              const {hour_test} = await curriculum.hourPlay(lastHours.course_id, lastHours.id)
              Taro.navigateTo({url: `/pages/business/test/test?testId=${hour_test?.id}`})
            } else {
              setHors(true, lastHours.id)
            }
          }
        })
        return;
      }

      for (const [index, flat] of flats.entries()) {
        if (flat.id === lastHours.id) {
          const next = flats[index + 1]
          if (next) {
            if (next.id === playId) {
              videoEvents.setVideoState('play')
            } else {
              setHors(false, next.id)
            }
          }
        }
      }
    }
  }


  return (
    <>
      <View className='catalogue'>
        <Tabs tabList={tabList} onChange={tabChange} current={current}/>
        <View className='py-2 hours'>
          {current === 0 && <View className='short_desc'>{data?.course.short_desc || data?.course.title}</View>}
          {current === 1 && <View>
            <View className='my-2'>课程目录</View>
            {!token && <LoginView offImage style={{
              position: 'absolute',
              left: 0,
              height: 'auto',
              right: 0,
              bottom: 0,
              top: 0,
              margin: 'auto',
              paddingTop: '100rpx',
              justifyContent: 'flex-end',
              flexDirection: 'column-reverse',
              background: 'rgba(255,255,255,.9)'
            }}/>}
            {data?.chapters.length
              ? Object.values(data?.chapters || {}).map((d, index) => <View key={d.id}>
                <Collapse title={`${index + 1}.${d.name}`}>
                  <Hours
                    playId={playId}
                    click={(is_complete, id) => upChaptersOver(is_complete, id, index)}
                    learn_hour_records={data.learn_hour_records}
                    data={getHors(d.id)}
                  />
                </Collapse>
              </View>)
              : <Hours
                playId={playId}
                data={data?.hours?.[0]}
                click={setHors}
                learn_hour_records={data?.learn_hour_records}/>}
          </View>}
          {current === 2 && <View className='text-center'>评论暂未开放</View>}
        </View>
      </View>

      {
        token && <View className='Videobutton'>
          {
            playing ? <MyButton className='flex-1'>播放中</MyButton>
              : <MyButton className='flex-1' onClick={learning}>立即学习</MyButton>
          }
          <View className='px-3' onClick={() => setShow(true)}>...</View>
        </View>
      }

      <CustomPageContainer
        show={show}
        position='bottom'
        onClickOverlay={() => setShow(false)}>
        <View className='more'>
          <View>更多操作</View>
          <View className='flex justify-around'>
            <View onClick={() => Taro.navigateTo({url: '/pages/business/curHistory/curHistory?course_id=' + id})}>
              <Image src={curRecord} className='image'/>
              课程记录
            </View>
            <View onClick={jumCurHistory} className={playId ? undefined : 'filter-saturate'}>
              <Image src={hourRecord} className='image'/>
              当前课时学习记录
            </View>
          </View>
          <MyButton onClick={() => setShow(false)} type='default' fillet>取消</MyButton>
        </View>
      </CustomPageContainer>
    </>
  );
}

export default Catalogue
