import {FC} from "react";
import '../videoInfo.scss'
import {Image, Text, View} from "@tarojs/components";
import playOk from "@/static/img/play-ok.png";
import play from "@/static/img/play.png";
import {formatMinute} from "@/utils/time";
import Taro from "@tarojs/taro";
import {curriculum} from "@/api";
import lock from '@/static/img/lock.png'
import {Profile} from "@/store";

interface Props {
  playId: number | null
  data?: Hour[] | null
  learn_hour_records?: LearnHourRecords[]
  click: (is_complete: boolean, id: number) => void
}

async function jumTest(hour: Hour) {
  const {hour_test} = await curriculum.hourPlay(hour.course_id, hour.id)
  Taro.navigateTo({
    url: `/pages/business/test/test?testId=${hour_test?.id}`
  })
}

const Hours: FC<Props> = ({data, click, learn_hour_records, playId}) => {
  const {token, empty} = Profile.useContainer()
  const complete = (id: number): number | undefined => {
    const find = learn_hour_records?.find(d => d.id === id)
    if (find) {
      return find.courseHourRecordsFinish
    } else {
      return undefined
    }
  }

  function onClick(id: number, is_complete: number | undefined, hour: Hour, upId?: number) {
    if (!token) {
      empty()
      return;
    }
    if (is_complete === 0) {
      Taro.showModal({
        title: '考卷未完成,是否前往',
        content: '考卷未完成不能播放下一个视频',
        confirmText: '前往考试',
        cancelText: '观看视频',
        success({confirm}) {
          if (confirm) {
            jumTest(hour)
          } else {
            click(true, id)
          }
        }
      })
      return;
    } else if (is_complete === 1) {
      click(true, id)
      return;
    }

    if (upId && complete(upId) !== 1) {
      Taro.showToast({title: '锁定中', icon: 'none'})
      return
    }

    click(is_complete !== undefined, id)
  }

  return (
    <>
      {data?.map((d, index) =>
        <View key={d.id}>
          <View className={'hor' + ` ${complete(d.id) ? 'complete' : undefined}`}
                key={index}
                onClick={() => onClick(d.id, complete(d.id), d, data?.[index - 1]?.id)}>
            <Image src={(complete(d.id) || playId === d.id) ? playOk : play} mode="scaleToFill" className='image'/>
            <View className='title'>
              <View className='text'>
                <View style={{wordBreak: 'break-all'}}>{playId === d.id &&
                  <Text className='text-center text-success'>正在播放：</Text>}{index + 1}. {d.title}</View>
                <View className='font-26 text-muted mt-1'>时长：{formatMinute(d.duration)}</View>
                {complete(d.id) === 0 && <View className='font-26 text-danger'>考卷未完成</View>}
              </View>
              {
                complete(data?.[index - 1]?.id) !== 1
                && index !== 0
                && <Image className='lock' src={lock} mode='aspectFit'/>
              }
            </View>
          </View>
        </View>)}

    </>
  )
}

export default Hours
