import {Image, Progress, View} from "@tarojs/components";
import {FC, useEffect, useState} from "react";
import Taro from "@tarojs/taro";
import {courseApi} from "@/api";
import styles from './hourHistory.module.scss'
import Empty from "@/components/empty/empty";
import {formatDateTime} from "@/utils/time";

const HourHistory: FC = () => {
  const {courseId, hourId} = Taro.getCurrentInstance().router?.params as { courseId: string, hourId: string }
  const [cur, setCur] = useState<Curriculum | null>(null)
  const [hour, setHour] = useState<Hour | null>(null)
  const [times, setTimes] = useState<HourHistory[]>([])

  useEffect(() => {
    courseApi.hourHistory(courseId, hourId).then(res => {
      if (res) {
        setHour(res.hour)
        setCur(res.course)
        const data = Object.values(res.data).map(d => {
          if (d.length === 1) {
            return d[0]
          }
          const duration = d.reduce((pre, cur) => {
            return pre + cur.duration
          }, 0)
          return ({
            ...d[0],
            duration,
            end_at: d[d.length - 1].end_at
          })
        })
        setTimes(data)
      }
    })
  }, [])


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

      {
        times.length ?
          <View className={styles.progressBox}>
            {
              times.map(d => <View key={d.id} className={styles.recordItem}>
                <View>
                  {formatDateTime(new Date(d.start_at), 'MM-dd')}
                  {formatDateTime(new Date(d.start_at), 'HH:mm:ss')} -
                  {formatDateTime(new Date(d.end_at), 'HH:mm:ss')}
                </View>
                <Progress
                  className={styles.progress}
                  percent={Number((d.duration / (hour?.duration || 0) * 100).toFixed(2))}
                  showInfo
                  borderRadius={10}
                  active
                  duration={10}
                  strokeWidth={10}
                  color='#45D4A8'
                  activeColor='#45D4A8'
                />
              </View>)
            }
          </View>
          : <Empty name='暂无数据'/>
      }

    </View>
  )
}

export default HourHistory
