<template>
  <div style="width: 100%;height: 100%;">
    <!-- 课程详情 -->
    <div v-if="mode == 'detail'" class="detail">
      <div class="header">
        <el-page-header @back="goBack">
          <template #content>
            <span class="text-large font-600 mr-3"> 课程详情 </span>
          </template>
        </el-page-header>
      </div>


      <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
        :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div class="mb-[10px]">
          <el-card shadow="hover">

            <template #header>
              <p class="card-header">
                <span>{{ dataObj.courseName }}</span>
                <el-tag type="success">{{ give_course_type[parseInt(dataObj.teachingType) - 1]?.label }}</el-tag>
              </p>
            </template>

            <div class="content">
              <div class="left">
                <p>
                  {{ dataObj.courseBrief }}
                </p>
              </div>

              <div class="right">
                <img :src="dataObj.coursePic" alt="">
              </div>
            </div>

            <template #footer>
              <el-button type="primary" @click="study">
                开始学习
              </el-button>
            </template>

          </el-card>

        </div>

      </transition>
    </div>


    <!-- 视频播放 -->
    <div v-else-if="mode == 'play'" class="video-play">
      <p>{{ dataObj.courseName }}</p>
      <vue3VideoPlay v-bind="options" @ended.native="onPlayEnded" :poster="dataObj.coursePic" @play="onPlay"
        @pause="onPause" @timeupdate="onTimeupdate" @canplay="onCanplay" />
    </div>


  </div>
</template>

<script setup lang="ts">
import { getLearningCourse, addLessonRecord } from '@/api/study/lesson/index';

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const _id = computed(() => proxy.$route.query.id);
const { give_course_type } = toRefs<any>(proxy?.useDict('give_course_type'));
const mode = ref('')

const study = () => {
  mode.value = 'play';

}
const dataObj = ref({
  courseName: '',
  courseClassify: '',
  teachingType: '',
  courseBrief: '',
  coursePic: '',
  courseAttachment: '',
});


const options = reactive({
  // width: "65vw", //播放器宽度
  height: "86vh", //播放器高度
  color: "#409eff", //主题色
  title: "测试", //视频名称
  src: "https://media.w3.org/2010/05/sintel/trailer.mp4", //视频源
  poster: "https://cdn.jsdelivr.net/gh/xdlumia/files/video-play/ironMan.jpg", // 视频封面
  muted: false, //静音
  speed: false, // 关闭进度条拖动
  webFullScreen: false,
  speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
  autoPlay: false, //自动播放
  loop: false, //循环播放
  mirror: false, //镜像画面
  ligthOff: false, //关灯模式
  volume: 0.3, //默认音量大小
  control: true, //是否显示控制
  controlBtns: [
    "audioTrack",
    "quality",
    // "speedRate",
    "volume",
    "setting",
    "pip",
    "pageFullScreen",
    "fullScreen",
  ], //显示所有按钮,
});

const postData = ref({
  courseId: _id.value.toString(),
  rate: null,
  viewDuration: null,
  status: null,
  learningSessionLength: null
});

const secondToTime = (duration: string) => {
  if (parseFloat(duration) <= 0) {
    return
  }
  let total = Math.round(parseFloat(duration));
  let minTotal = (total - total % 60) / 60;
  let sec = total - minTotal * 60;
  let hour = (minTotal - minTotal % 60) / 60;
  let min = minTotal - hour * 60;
  return `${hour}:${min < 10 ? '0' + min : min}:${sec < 10 ? '0' + sec : sec}`
}

const secondToMinutes = (duration: string) => {
  if (parseFloat(duration) <= 0) {
    return
  }
  let total = Math.round(parseFloat(duration));
  let minTotal = (total - total % 60) / 60;
  return minTotal
}

/**
 * 支持所有原生video事件
 */
const onPlayEnded = async (ev) => {
  postData.value.status = '2';
};

const onPlay = (ev) => {
  console.log("播放", ev);
};

const onPause = async (ev) => {
  ev.target.duration > ev.target.currentTime ? postData.value.status = '1' : postData.value.status = '2';
  const res = await addLessonRecord(postData.value);
  res.code == 200?
    ElNotification({
      title: '提示',
      message: '成功提交学习记录',
      type: 'success',
    })
    :ElNotification({
      title: '提示',
      message: '提交学习记录失败',
      type: 'error',
    })
};
const onTimeupdate = (ev) => {
  postData.value.rate = secondToTime(ev.target.duration);
  postData.value.viewDuration = secondToTime(ev.target.currentTime);
  postData.value.learningSessionLength = secondToMinutes(ev.target.currentTime) || 0;
};

const onCanplay = (ev) => {
  console.log(ev, "可以播放");
};

const getData = async () => {
  const res = await getLearningCourse(_id.value.toString()).finally();
  dataObj.value = res.data;
  if (res.data.courseAttachment) {
    options.src = res.data.url
  }

}

const goBack = () => {
  router.back();
}



onActivated(() => {
  if (typeof (route.query.mode) == 'string') {
    mode.value = route.query.mode;
  }
  getData();

})
onMounted(() => {
  if (typeof (route.query.mode) == 'string') {
    mode.value = route.query.mode;
  }
  getData();
})


</script>

<style lang="scss" scoped>
.header {
  margin: 1vh 0 0 2vw;
}

.el-card {
  margin-top: 2vh !important;
  width: 90%;
  margin: 0 auto;

  .card-header {
    font-size: 1.2rem;
    padding-left: 1vw;

    span:nth-child(1) {
      font-size: 1.3rem;
      font-weight: bolder;
      margin-right: 2vw;
    }
  }
}

.content {
  padding: 2vw;
  display: flex;
  justify-content: space-between;

  .left {
    width: 70%;
  }

  .right {
    width: 28%;

    img {
      width: 100%;
    }
  }
}

.el-button {
  margin-left: 2vw;
}

.video-play {
  width: 100%;
  height: 100%;

  p {
    margin: 0;
    padding: 7px;
    padding-left: 2vw;
  }

  #refPlayerWrap {
    width: 100%;
  }
}
</style>
