<script setup lang="ts">
import urgeApi from '@/api/urge.ts'
import { urgeStore, userStore } from '@/stores'
import DoWork from '@/page/subject/doWork/index.vue'
import VideoPlayer from './VideoBox.vue'

const props = defineProps<{
  show: boolean
}>()

const emit = defineEmits(['update:show'])

const { inspectorInfo } = toRefs(urgeStore())
const { userInfo } = userStore()

const currentTaskIdx = ref(-1)
const tasks = ref<anyObj[]>([])

const pageLoading = ref(false)

const doWorkRef = ref()
const videoPlayerRef = ref()

const showNext = ref(true)
function workSubmit() {
  // 完成一次答题
  showNext.value = true
  doWorkRef.value?.endTime()
}

async function changeTask(time = true) {
  // 0-视频 1-章节 2-精准学 3-语感训练 4-订正错题
  const { subjectId, courseTimeId } = tasks.value[currentTaskIdx.value]
  if (tasks.value[currentTaskIdx.value]?.taskType === 0) {
    try {
      const {
        data: { data: res },
      } = await urgeApi.getChapterVideoById({ id: '1831079368051396610', userId: userInfo.userId })
      videoPlayerRef.value?.videoInit(res, {
        subjectId,
        resourceType: 0,
        origin: 1,
      })
    } catch {
      // 当前任务若报错去下一个任务
      onNext()
    }
  } else if (tasks.value[currentTaskIdx.value]?.taskType === 3) {
    console.log('语感')
  } else if ([1, 2, 4].includes(tasks.value[currentTaskIdx.value]?.taskType)) {
    const resourceType = [0, 0, 1, 0, 2][tasks.value[currentTaskIdx.value].taskType]

    try {
      await doWorkRef.value.initUrge({
        resourceType,
        subjectId,
        knowledgeId: courseTimeId,
        num: 10,
      })

      if (time) {
        await nextTick()
        doWorkRef.value?.startTime(true)
      }
    } catch {
      // 当前任务若报错去下一个任务
      onNext()
    }
  }
}

async function onNext() {
  // 下一题
  showNext.value = true

  // const { progress, finishedNum, num } = tasks.value[currentTaskIdx.value];
  // if (progress === 1 || (finishedNum > 1 && finishedNum === num)) {
  //     if (currentTaskIdx.value >= tasks.value.length - 1) {
  //         return console.log('完成计划');
  //     }
  //     currentTaskIdx.value++;
  // } else {
  //     tasks.value[currentTaskIdx.value].finishedNum++;
  // }

  if (currentTaskIdx.value >= tasks.value.length - 1) {
    return console.log('完成计划')
  }
  pageLoading.value = true
  try {
    currentTaskIdx.value++

    await nextTick()
    await changeTask()
  } catch {}
  pageLoading.value = false
}

const onClose = () => {
  emit('update:show', false)
}

watch(
  () => props.show,
  async nv => {
    if (nv) {
      nextTick(() => {
        doWorkRef.value?.startTime()
        // videoPlayerRef.value?.play();
      })
    } else {
      nextTick(() => {
        doWorkRef.value?.endTime()
        videoPlayerRef.value?.pause()
      })
    }
  },
)

onMounted(async () => {
  try {
    const {
      data: { data: res },
    } = await urgeApi.getInspectorPlanInfo(inspectorInfo.value.conductInspectorPlanId)
    tasks.value = res.taskList.map((task: anyObj) => {
      const {
        subjectName,
        finishedNum = 0,
        num,
        progress,
        subjectId,
        courseTimeId,
      } = JSON.parse(task.taskInfoJson)
      return {
        id: task.id,
        subject: subjectName,
        subjectId: subjectId,
        taskType: task.taskType, // 0-视频 1-章节 2-精准学 3-语感训练 4订正错
        completionRate: progress ?? 0,
        num,
        finishedNum,
        courseTimeId,
        completed: progress === 1 || (finishedNum > 1 && finishedNum === num),
      }
    })
    currentTaskIdx.value = tasks.value.findIndex((task: anyObj) => !task.completed)
    changeTask(false)
  } catch {}
})
</script>
<template>
  <div v-show="show && currentTaskIdx !== -1" class="learning-dia">
    <Empty v-show="pageLoading" type="loading"></Empty>
    <div v-show="!pageLoading" class="learning-dia-main">
      <VideoPlayer v-if="tasks[currentTaskIdx]?.taskType === 0" ref="videoPlayerRef"></VideoPlayer>
      <DoWork
        v-else-if="[1, 2, 4].includes(tasks[currentTaskIdx]?.taskType)"
        ref="doWorkRef"
        @urgeSubmit="workSubmit"
      ></DoWork>
    </div>
    <div class="btns">
      <Btn class="back-btn" @click="onClose">返回</Btn>
      <Btn v-if="showNext" class="next-btn" @click="onNext">下一题</Btn>
    </div>
  </div>
</template>
<style scoped lang="scss">
.learning-dia {
  position: fixed;
  width: 100vw;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 1000;
  overflow: hidden;
  box-sizing: border-box;
  line-height: 1.5;
  @include main_bg;
  @include hidden_scroll;
  .empty {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1001;
  }
  .btns {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1002;
  }
  &-main {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
}
</style>
