import request from '@/helpers/request';
import { getSecondRPM } from '@/helpers/utils';
import { state } from '@/state';
import { usePageVisibility } from '@vant/use';
import {
  computed,
  defineComponent,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  watch
} 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, { expose }) {
    const pageVisibility = usePageVisibility();

    watch(pageVisibility, value => {
      if (value == 'hidden') {
        handleOut();
      } else {
        // 页面显示
        handleStartInterval();
      }
    });
    const handleOut = () => {
      clearInterval(timerRecord.value);
      handleRecord(true);
    };
    expose({
      handleOut
    });
    const route = useRoute();
    const saveModel = reactive({
      loading: true,
      /**当前时长 */
      currentTime: 0,
      /**记录的开始时间 */
      startTime: 0,
      timer: null as any,
      /** 已经播放的时间 */
      playTime: 0
    });
    /** 建议学习总时长 */
    const total = computed(() => {
      const _total = props.list.reduce(
        (_total: number, item: any) =>
          _total + (item.totalMaterialTimeSecond || 0),
        0
      );
      return _total;
    });

    const getPlayTime = async () => {
      saveModel.loading = true;
      try {
        const res: any = await request.post(
          `${state.platformApi}/courseSchedule/getCoursewarePlayTime?courseScheduleId=${route.query.courseId}`
        );
        if (res.data) {
          saveModel.playTime = res.data;
        }
      } catch (error) {
        //
      }
      saveModel.loading = false;
      handleStartInterval();
    };

    /** 记录时长 */
    const handleRecord = (isOut = false) => {
      saveModel.currentTime++;
      const playTime = saveModel.currentTime - saveModel.startTime;
      // 1分钟记录1次
      if (playTime >= 5 || isOut) {
        console.log('isOut', isOut);
        saveModel.startTime = saveModel.currentTime;
        request.post(`${state.platformApi}/courseSchedule/coursewarePlayTime`, {
          params: {
            courseScheduleId: route.query.courseId,
            playTime
          },
          hideLoading: true
        });
      }
    };
    const timerRecord = ref();
    const handleStartInterval = () => {
      clearInterval(timerRecord.value);
      timerRecord.value = setInterval(() => handleRecord(), 1000);
    };
    onMounted(() => {
      getPlayTime();
    });
    onUnmounted(() => {
      clearInterval(timerRecord.value);
    });
    return () => (
      <div
        class={styles.playRecordTimeWrap}
        style={{
          display:
            saveModel.loading ||
            saveModel.currentTime + saveModel.playTime > total.value
              ? 'none'
              : ''
        }}>
        <div class={styles.playRecordTime}>
          <div class={styles.timeLoad}></div>
          <div>
            {getSecondRPM(saveModel.currentTime + saveModel.playTime)} /{' '}
            {getSecondRPM(total.value)}
          </div>
        </div>
      </div>
    );
  }
});
