import request from '@/helpers/request'
import { getSecondRPM } from '@/helpers/utils'
import { state } from '@/state'
import { computed, defineComponent, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import styles from './index.module.less'

export default defineComponent({
  name: 'playRecordTime',
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const route = useRoute()
    const saveModel = reactive({
      startTime: Date.now(),
      timer: null as any,
      totalTime: 0,
      loading: false
    })
    const total = computed(() => {
      const _total = props.list.reduce(
        (_total: number, item: any) => _total + item.adviseStudyTimeSecond,
        0
      )
      return _total
    })

    const handleRecord = async () => {
      if (saveModel.loading) return
      saveModel.loading = true
      try {
        const res: any = await request.post(
          `${state.platformApi}/courseSchedule/coursewarePlayTime`,
          {
            params: {
              courseScheduleId: route.query.courseId,
              playTime: saveModel.totalTime
            }
          }
        )
      } catch (error) {}
    }
    const timerRecord = ref()
    onMounted(() => {
      timerRecord.value = setInterval(() => {
        if (saveModel.totalTime > total.value){
          handleRecord()
        }
        saveModel.totalTime = Math.floor((Date.now() - saveModel.startTime) / 1000)
      }, 1000)
    })
    onUnmounted(() => {
      clearInterval(timerRecord.value)
    })
    return () => (
      <div class={styles.playRecordTimeWrap}>
        <div
          class={styles.playRecordTime}
          style={{ display: saveModel.totalTime > total.value ? 'none' : '' }}
        >
          <div class={styles.timeLoad}></div>
          <div>
            {getSecondRPM(saveModel.totalTime)} / {getSecondRPM(total.value)}
          </div>
        </div>
      </div>
    )
  }
})
