<script setup lang='ts'>
import Back from '@/components/back.uvue'
import Loading from '@/components/loading.uvue'
import { ref, onMounted, watchEffect, nextTick, onUnmounted } from 'vue'
import { type SubjectCourseResult, fetchSubjectCourseApp, updateSubjectProgress } from '@/services/subject/course'
import { router } from '@/.cool'
const isLoading = ref(true)
const showProgress = ref(true)
const showControls = ref(true)
const showVideo = ref(true)

const data = ref({
  videoSrc: 'https://oss.xiaoxiongcode.com/course-1/animate/第1集_观察.mp4',
  webviewSrc: '',
})
const menuItems = [
  { id: 'watch', name: '看课', icon: 'https://oss.xiaoxiongcode.com/static/home/kanke.png' },
  { id: 'practice', name: '练习', icon: 'https://oss.xiaoxiongcode.com/static/home/lianxi.png' },
  { id: 'experiment', name: '虚拟实验', icon: 'https://oss.xiaoxiongcode.com/static/home/shiyan.png' },
  { id: 'diary', name: '科学日记', icon: 'https://oss.xiaoxiongcode.com/static/home/riji.png' }
]
const menu2Items = [
  { id: '1', name: '观察', icon: 'https://oss.xiaoxiongcode.com/static/home/kanke.png' },
  { id: '2', name: '提问', icon: 'https://oss.xiaoxiongcode.com/static/home/lianxi.png' },
  { id: '3', name: '假设', icon: 'https://oss.xiaoxiongcode.com/static/home/shiyan.png' },
  { id: '4', name: '实验', icon: 'https://oss.xiaoxiongcode.com/static/home/riji.png' },
  { id: '5', name: '总结', icon: 'https://oss.xiaoxiongcode.com/static/home/riji.png' },
  { id: '6', name: '拓展', icon: 'https://oss.xiaoxiongcode.com/static/home/riji.png' },
]
//当前进度
const progress = ref(1)
const progress2 = ref(1)
const recorderManager = ref<any>()
const innerAudioContext = ref<any>()
const voicePath = ref('')
function initOnlibeRecord() {
  recorderManager.value = uni.getRecorderManager();
  innerAudioContext.value = uni.createInnerAudioContext();
  innerAudioContext.value.autoplay = true;
  recorderManager.value.onStop(function (res) {
    console.log('recorder stop' + JSON.stringify(res));
    if (res.duration < 5000) {
      uni.showToast({
        title: '录音时间过短',
        icon: 'none'
      })
      return
    }
    voicePath.value = res.tempFilePath;
  });
}

const course = ref<SubjectCourseResult>()
//通过路由参数获取课程id
async function fetchCatalog() {
  course.value = await fetchSubjectCourseApp({ id: router.query().id })
  if (!course.value?.courseUserProgress) {
    await updateSubjectProgress({
      courseId: course.value?.id,
      mainProgress: 1,
      assistantProgress: 1,
      status: 0
    })
    progress.value = 1
    progress2.value = 1
    data.value.videoSrc = course.value?.detailItem?.observeVideoPath || ''
    data.value.webviewSrc = course.value?.detailItem?.observeAnimationPath || ''
  } else {
    // progress.value = 1
    // progress2.value = 1
    progress.value = course.value?.courseUserProgress.mainProgress
    progress2.value = course.value?.courseUserProgress.assistantProgress
  }
}
onMounted(async () => {
  await fetchCatalog()
  isLoading.value = false
  initOnlibeRecord()
  setTimeout(() => {
    showProgress.value = false
    isLoading.value = false
  }, 1000)
})
async function handleEnded() {
  // await updateSubjectProgress({
  //   courseId: course.value?.id,
  //   mainProgress: 1,
  //   assistantProgress: 2,
  //   status: 0
  // })
  // progress2.value = 2

  switch (progress2.value) {
    case 1:
      router.push({
        path: "/pages/catalog/web-view",
        query: {
          src: data.value.webviewSrc,
          progress: progress2.value,
        }
      });
      break
    case 2:
    case 4:
    case 5:
    case 6:
      progress2.value++
      break
  }
}
const status = ref('wait')
onShow(() => {
  isLoading.value = true
  var pages = getCurrentPages();
  const prevPage = pages[pages.length - 1];
  console.log('prevPage', prevPage)
  status.value = (prevPage as any)?.status || 'wait'
  if (status.value === 'success') {
    progress2.value++
      ; (prevPage as any).status = 'wait'
  }
  isLoading.value = false

})

function handleControlsToggle(e) {
  console.log(e)
  showControls.value = e.detail.show
}

watchEffect(() => {
  if (progress.value === 1) {
    switch (progress2.value) {
      case 1:
        data.value.videoSrc = course.value?.detailItem?.observeVideoPath
        data.value.webviewSrc = course.value?.detailItem?.observeAnimationPath
        break
      case 2:
        data.value.videoSrc = course.value?.detailItem?.questionVideoPath
        break
      case 3:
        setTimeout(() => {
          playVoice('/static/rain_experiment.mp3')
        }, 2000)
        // data.value.webviewSrc = course.value?.detailItem?.assumeAnimationPath || data.value.webviewSrc
        // router.push({
        //   path: "/pages/catalog/web-view",
        //   query: {
        //     src: data.value.webviewSrc,
        //     progress: progress2.value,
        //   }
        // });
        break
      case 4:
        // data.value.videoSrc = course.value?.detailItem?.testVideoPath || data.value.videoSrc
        data.value.webviewSrc = course.value?.detailItem?.testAnimationPath
        router.push({
          path: "/pages/catalog/web-view",
          query: {
            src: data.value.webviewSrc,
            progress: progress2.value,
          }
        });
        break
      case 5:
        data.value.videoSrc = course.value?.detailItem?.summaryVideoPath
        break
      case 6:
        data.value.videoSrc = course.value?.detailItem?.expandVideoPath
        break
    }
  }
})
const timers = ref(100)
const timer = ref<any>()

function handleTop() {
  progress2.value = 4
  console.log(progress2.value)
}
function startRecord() {
  console.log('开始录音');
  timer.value = setInterval(() => {
    timers.value--
    if (timers.value <= 0) {
      endRecord()
    }
  }, 800)
  recorderManager.value.start();
}
function endRecord() {
  clearInterval(timer.value)
  timer.value = null
  timers.value = 100
  recorderManager.value.stop();
}
function playVoice(val) {
  innerAudioContext.value.src = val;
  innerAudioContext.value.play();
}
onUnmounted(() => {
  innerAudioContext.value.stop();
})
</script>
<template>
  <Loading v-show="isLoading" />
  <cl-page v-show="!isLoading">
    <Back v-show="showProgress" />
    <view class="w-[64vw] h-[36vw] absolute top-1/2  z-[1] left-[7vw]  translate50"
      :class="{ ' rounded-2xl p-[3px] bg-black mt-[25px] ': showProgress, 'video-container': !showProgress }">
      <video v-if="progress2 !== 3" id="video1" class="w-full h-full " :class="{ 'rounded-2xl': showProgress }"
        :src="data.videoSrc" :show-center-play-btn="false" :show-background-playback-button="false"
        :show-fullscreen-btn="false" :show-casting-button="false" autoplay @controlstoggle="handleControlsToggle"
        @ended="handleEnded">
      </video>
      <view v-else class="w-full h-full ">
        <img src="https://oss.xiaoxiongcode.com/static/home/assert_1.gif" alt="" class="w-full h-full object-cover" />

        <!-- 顶部提示文字 -->
        <view class="absolute text-[20px] top-[20vh] w-full flex flex-row items-center justify-center">
          <!-- <cl-icon name="notification-3-fill" color="#FCE762" :size="40"></cl-icon> -->
          <text>🔊</text>
          <text class=" font-bold text-white">为什么下雨后，盐和糖消失了，烤肉却还在呢？</text>
        </view>

        <!-- 居中麦克风按钮 -->
        <view class=" mic flex flex-col items-center w-[120px] h-[120px]">
          <view v-show="timer">
            <cl-progress-circle :value="timers"></cl-progress-circle>
          </view>

          <view class="mic  w-[120px] h-[120px] bg-[#3CB8FF]  rounded-full  flex items-center justify-center  z-[2]"
            @tap="startRecord" v-if="!timer">
            <cl-icon name="mic-fill" color="white" :size="60"></cl-icon>
          </view>
          <template v-else>
            <view class="mic  w-[120px] h-[120px] bg-[#3CB8FF]  rounded-full  flex items-center justify-center  z-[2]"
              @tap="endRecord">
              <view class="w-[50px] h-[50px] rounded-[5px] bg-white"></view>
            </view>
          </template>

          <!-- 指示手指 -->
          <view class="absolute bottom-[-20px] right-[-20px] animate-bounce pointer-events-none z-[2]"
            v-if="!timer && !voicePath">
            <cl-icon name="arrow-left-up-line" color="white" :size="60"></cl-icon>
          </view>
        </view>
        <!-- 下一步按钮 (录音完成后显示) -->
        <view v-show="voicePath" class="mic flex flex-row items-center justify-center gap-[200px]">
          <button
            class="bg-[#71C73D] text-white w-[80px] h-[80px] flex items-center justify-center rounded-full font-bold text-[25px] shadow-md active:opacity-80"
            @tap="playVoice(voicePath)">🔊</button>
          <button
            class="bg-[#71C73D] text-white w-[80px] h-[80px] flex items-center justify-center rounded-full font-bold text-[25px] shadow-md active:opacity-80"
            @tap="handleTop">√</button>
        </view>
      </view>
      <view class="video-fullscreen_title" v-show="showControls && !showProgress">
        <Back />
        <view class="text-[20px] font-bold text-white">
          {{ course?.mainTitle }}
        </view>
        <view class="control-progress">
          <view class="before"></view>
          <view v-for="(item, i) in menu2Items" :key="item.id"
            class="px-0 py-3 flex items-center justify-center gap-[5px] relative z-[1]"
            :class="{ '!bg-[#fff] rounded-full': progress2 == i + 1 }">
            <cl-image :src="item.icon" mode="heightFix" class="!h-[30px]"></cl-image>
            <text class="text-[14px]  font-bold" :class="{ '!text-[#2BA0F3]': progress2 == i + 1 }">{{ item.name
            }}</text>
          </view>
          <view class="before"></view>
        </view>
      </view>
    </view>

    <view class="course-detail-page" :class="{ 'hidden': !showProgress }">
      <!-- 顶部标题栏 -->
      <view class="flex-[1]  h-[100vh] relative">
        <view class="flex flex-row w-full pr-[3vw] pl-[10vw] items-center justify-between absolute top-[30px]">
          <text class="text-[5vh] font-bold">{{ course?.mainTitle }}</text>
          <text
            class="rounded-full p-[1vh] px-[2vh] border-2 border-[#fff] border-solid text-[#fff] text-[3vh] font-bold">课程收获</text>
        </view>

      </view>
      <!-- 右侧功能菜单 -->
      <view class="w-[25vw] h-[100vh] bg-[#5CBDFD] flex flex-col  justify-center p-5">
        <view v-for="(item, i) in menuItems" :key="item.id" class="h-[20vh]  flex flex-row items-center ">
          <view
            class="h-[15vh] w-[20vh] bg-[#999999] rounded-2xl border-[.5vh] border-[#254AD9] border-b-[1vh] border-solid flex items-center justify-center gap-[1vh]"
            :class="{ '!bg-[#fff]': progress > i }">
            <cl-image :src="item.icon" mode="heightFix" class="!h-[7vh]"></cl-image>
            <text class="text-[2vh] font-bold">{{ item.name }}</text>
          </view>
          <view class="flex items-center h-[20vh] ml-[2vh] ">
            <view class="w-[1vh] bg-[#B4DBF7] flex-1" :class="{ '!bg-[#71C73D]': progress > i, '!opacity-0': i === 0 }">
            </view>
            <view class="w-[5vh] bg-[#fff] h-[5vh] rounded-full" :class="{ '!bg-[#71C73D]': progress > i }"></view>
            <view class="w-[1vh] bg-[#B4DBF7] flex-1"
              :class="{ '!bg-[#71C73D]': progress > i, '!opacity-0': i === menuItems.length - 1 }"></view>
          </view>
        </view>
      </view>
    </view>

  </cl-page>
</template>
<style lang="scss" scoped>
.translate50 {
  transform: translateY(-50%);
}

.course-detail-page {
  @apply flex flex-row items-center;
  background-color: #3498DB;
  height: 100vh;
  color: black;
  transition: all 1s ease-in-out;

}

.video-container {
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  transform: translate(0, 0);
  animation: spin 2s linear 1;
  transition: all 2s ease-in-out;
}

@keyframes spin {
  0% {
    opacity: 50%;
  }

  100% {
    opacity: 1;
  }
}

.hidden {
  opacity: 0;
  transition: all 3s ease-in-out;
}

.video-fullscreen_title {
  @apply absolute top-3 left-0 pl-[80px] w-[100vw] z-10 flex items-center justify-between flex-row;
  color: #fff;

  .control-progress {
    @apply flex flex-row gap-[1vh] relative justify-end;
    flex: 1;

    .before {
      @apply absolute top-1/2 right-0 w-[410px] h-[40px] bg-[#2BA0F3] rounded-l-full;
      transform: translateY(-30%);
    }
  }
}

video::-webkit-media-controls-fullscreen-button,
video::-webkit-media-controls-enter-fullscreen-button,
video::-webkit-media-controls-rotate-button,
video::-webkit-media-controls-seek-back-button,
video::-webkit-media-controls-seek-forward-button {
  display: none !important;
}

.mic {
  @apply absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2;
}
</style>
