import {Image, Progress, View} from "@tarojs/components";
import Taro from "@tarojs/taro";
import styles from './curHistory.module.scss'
import {useState} from "react";
import {userApi} from "@/api";
import {formatDateTime, formatMinute} from "@/utils/time";
import CustomPageContainer from "@/components/custom-page-container/custom-page-container";
import Empty from "@/components/empty/empty";

const CurHistory = () => {
  const [show, setShow] = useState(false)
  const {course_id} = Taro.getCurrentInstance().router?.params as unknown as { course_id: string }
  const [data, setData] = useState<HourHistory[]>([])
  const [DataAll, setDataAll] = useState<HourHistory[]>([])
  const [course, setCourse] = useState<Curriculum | null>(null)
  const [hours, setHours] = useState<Hour[] | null>(null)
  const [durations, setDuration] = useState<Record<number, number> | null>(null)
  const [time, setTime] = useState<Record<number, { start: number, end: number }> | null>(null)
  const [page, setPage] = useState(1)

  Taro.useLoad(() => {
    userApi.courseRecord(course_id).then(res => {
      Taro.setNavigationBarTitle({title: res.course.title})
      setDataAll(Object.values(res.data))
      setData(Object.values(res.data).slice(0, 10))
      setCourse(res.course)
    })
  })

  Taro.useReachBottom(() => {
    if (data.length < DataAll.length) {
      const page_size = page * 10
      setData([
        ...data,
        ...DataAll.slice(page_size, page_size + 10)
      ])
      setPage(page + 1)
    }
  })

  async function setHour(unique_ident: number) {
    try {
      const res = await userApi.hourCourse(course_id, unique_ident)
      setHours(Object.values(res.courseHour))
      setDuration(res.duration)
      setTime(res.date)
      setShow(true)
    } catch (e) {

    }
  }

  function percent(duration: number): number {
    if (!course?.course_duration) return 0
    return Number((duration / course.course_duration * 100).toFixed(2))
  }

  function getTime(id: number): string {
    const day = formatDateTime(new Date(time?.[id].start || 0), 'MM-dd')
    const start = formatDateTime(new Date(time?.[id].start || 0), 'HH:mm:ss')
    const end = formatDateTime(new Date(time?.[id].end || 0), 'HH:mm:ss')
    return `${day} ${start} - ${end}`
  }

  function getCurTime(startNow: string, endNow: string): string {
    const day = formatDateTime(new Date(startNow), 'MM-dd')
    const start = formatDateTime(new Date(startNow), 'HH:mm:ss')
    const end = formatDateTime(new Date(endNow), 'HH:mm:ss')
    return `${day} ${start} - ${end}`
  }

  function hourPercent(id: number, duration: number): number {
    const viewingTime = durations?.[id] || 0
    return Number((viewingTime / duration * 100).toFixed(2))
  }

  return (
    <View className={styles.page}>
      <View className={styles.cur}>
        <Image className={styles.image} src={course?.thumb || ''} mode='center'/>
        <View className={styles.classHour}>共{course?.class_hour}节/已学{course?.finished_hour_count || 0}节</View>
        <View className={styles.title}>{course?.title}</View>
      </View>


      {
        data.length ? <View className={styles.record}>
            {
              data.map((d, index) => <View
                key={d.id}
                onClick={() => setHour(d.unique_ident)}
                className={styles.recordItem}>
                <View className='text-hover-dark'>第{index + 1}次观看</View>
                <View>{getCurTime(d.start_at, d.end_at)} </View>
                <View>观看视频：{formatMinute(d.duration)}</View>
                <Progress
                  className={styles.progress}
                  percent={percent(d.duration)}
                  showInfo
                  borderRadius={10}
                  active
                  duration={10}
                  strokeWidth={10}
                  color='#45D4A8'
                  activeColor='#45D4A8'
                />
              </View>)
            }
            <View className='text-center font-24 text-dark mt-3'>暂无更多</View>
          </View>
          : <Empty name='暂无学习记录'/>
      }


      <CustomPageContainer
        show={show}
        round
        position='bottom'
        onClickOverlay={() => setShow(false)}>
        <View className={styles.hourRecord}>
          {hours?.length ?
            hours?.map(d => <View key={d.id}>
              <View className={styles.recordItem}>
                <View>{d.title}</View>
                <View>{getTime(d.id)}</View>
                <Progress
                  percent={hourPercent(d.id, d.duration)}
                  showInfo
                  duration={10}
                  borderRadius={10}
                  active
                  strokeWidth={10}
                  color={'#45D4A8'}
                  activeColor={'#45D4A8'}
                />
              </View>
            </View>)
            : <Empty name='暂无学习记录'/>}
        </View>
      </CustomPageContainer>
    </View>
  )
}

export default CurHistory
