<template>
  <div class="course_lessonsBox fs14 text_1">
    <!-- 节 -->
    <div class="section_box flex-ac flex-rb" v-if="catLatestInfo.type == 1">
      <span>{{ catLatestInfo.name }}</span>
    </div>
    <!-- 课 -->
    <!-- filter_gray -->
    <div class="lesson_box flex-rb" :class="{'filter_gray': fetchIsNoneEffect(catLatestInfo)}" v-if="catLatestInfo.type == 2" @click="handelTab">
      <div class="flex-re">
        <span class="lesson_tag courseCat_tag theme_color flex-cc fs10">
          <span class="icon_cat" :class="activeClass(catLatestInfo).iconClass"></span>
          <span class="fss10">{{ activeClass(catLatestInfo).label }}</span>
        </span>
        <!-- 课件内容 -->
        <div class="lesson_content_box">
          <div class="flex cat_title_box">
            <p class="lesson_infoName text_2 flex-wr">{{ catLatestInfo.name }}</p>
            <span class="fss11" v-if="currentCatId == catLatestInfo.id">正在学</span>
            <span class="fss11" v-if="!currentCatId && catLatestInfo.lastLearn"
              >上次学到</span
            >
          </div>

          <div class="course_status_box text_3">
            <csLessonStatus
              :isLock="currentIsLock"
              :courseInfo="catLatestInfo"
              :courseDetail="courseDetail"
              :lessonStudyProgress="lessonStudyProgress"
            />
          </div>
        </div>
      </div>
      <div @click.stop="doDownLoadEvent()">
        <!-- 课件下载 -->
        <div
          class="flex-cc lesson_down"
          v-if="currentIsLock == 0 && [3, 4].includes(catLatestInfo.courseType)"

        >
          <!-- 下载进度为0 -->
          <span v-if="courseDetail.joinStatus < 1"></span>
          <!-- @click.stop="doDownLoad" -->
          <span
            class="lesson_down_icon"
            v-else-if="downloadProgress == 0"
          ></span>
          <!-- 正在下载 | 暂停 -->
          <div
            class="tc"
            v-else-if="downloadProgress < 100 && downloadProgress > 0"
          >
          <!-- @click.stop="changeDownLoadMode" -->
            <div>
              <span
                class="lesson_down_loading_icon"
                :class="isDownload ? 'downloadPause' : 'downLoading'"
              ></span>
              <p class="w-8 fss11 theme_color">下载 {{ downloadProgress }} %</p>
            </div>
            <!-- <div v-if="!isDownload" @click.stop="doDownLoad">
            <span class="lesson_down_loading_icon"></span>
            <p class="fss11 theme_color">已暂停</p>
          </div> -->
          </div>
          <!-- 下载完成 -->
          <span v-else class="theme_color">已下载</span>
        </div>
        <div class="flex-cc noeffect_box" v-if="fetchIsNoneEffect(info)">
          <div class="icon_noEffect"></div>
        </div>
      </div>
    </div>
    <ul>
      <li v-for="v in catLatestInfo.childrenList">
        <courseLessonsBox
          :info="v"
          :courseDetail="courseDetail"
          color="#21CC64"
          :lessonDownProgress="lessonDownProgress"
          :lessonStudyProgress="lessonStudyProgress"
        />
      </li>
    </ul>
    <csLessonPracticeBox
      :info="catLatestInfo.coursePaperVOS"
      :courseInfo="info"
      v-if="
        catLatestInfo.type == 1 &&
          isArray(catLatestInfo.coursePaperVOS) &&
          catLatestInfo.coursePaperVOS.length &&
          catLatestInfo.coursePaperVOS != ['']
      "
    />

  </div>
</template>

<script setup>
import {
  defineComponent,
  ref,
  nextTick,
  getCurrentInstance,
  onMounted,
  watch,
  computed,
} from "vue";
import { useRouter, useRoute } from "vue-router";
// 组件
import csLessonStatus from "./csLessonStatus.vue";
import csLessonPracticeBox from "./csLessonPracticeBox.vue";
// hooks
import { clientChangeVideo, clientDownloadVideo,  clientMediaDownloadProgress,
  clientCancelDownloadMedia } from "@/hooks/web/useClientFc"
  import { formatIsUnLock } from "@/hooks/format/comm";
import { useCourseMain, useReqApi } from "../hooks/useMain";
import { useCourseDetail } from "../hooks/useCourseDetail";
import { debounceFun } from "@/hooks/core/useLodash.js";
import {globalDebounceTime} from "@/config/settingConfig/core.js"

//方法
import { isArray } from "@/utils/is/isString";
const { appContext } = getCurrentInstance();
const {
  activeClass
} = useCourseMain();

const props = defineProps({
  info: {
    type: Object,
    default() {
      return {
        id: "",
        name: "",
        childrenList: [],
        isLastLearnCatalog: false,
      };
    },
  },

  courseDetail: {
    type: Object,
    default() {
      return {};
    },
  },

  lessonDownProgress: {
    type: Object,
    default() {
      return {};
    },
  },

  lessonStudyProgress: {
    type: Object,
    default() {
      return {};
    },
  },
});
defineComponent({ name: "courseLessonsBox" });

const router = useRouter();
const route = useRoute();
const currentCatId = ref(""); // 课件目录id (正在学)
const currentDownloadCatId = ref(""); // 课件目录id (下载)
const { fetchCourseTipByRecord , fetchIsNoneEffect} = useCourseDetail();
const { updateLastLearnCatalogIdCourseApi } = useReqApi;

const isDownload = ref(true); //控制下载课件的暂停
const currCatFullData = ref({}); //当前目录课节更新所有数据

const catLatestInfo = computed(() => { //实时的课程目录课件数据
  return {...props.info ,...currCatFullData.value}
})
// 下载进度
const downloadProgress = ref(0);
// const currentIsLock = ref(1);
const currentIsLock = computed(()=>{
  return props.info?.isLock
})


// 跳转播放视频
const handelTab = 
  debounceFun(function() {
   console.log('debounceFun_handelTab')
   if(fetchIsNoneEffect(props.info)){ // 课节已失效
    return
  }
  if(props.info.id == currentCatId.value){ // 相同目录事件不处理
    return
  }
   updateChangeLessonApi();
 }, globalDebounceTime);
 

  

// 汇报上次学到的课 拿到当前实时的返回进度
async function updateChangeLessonApi() {
  const resData = await updateLastLearnCatalogIdCourseApi({
    courseCatalogId: props.info.id,
    resourceId: route.query.id,
  });
  let params = {
      ...props.info,
      courseTrainId: route.query.id,
  };
  if(resData){
    params = {...params, ...resData.data}
  }

  if (formatIsUnLock({ ...params })) {
    currCatFullData.value = params // 本课节接口数据更新
    appContext.config.globalProperties.Bus.emit(
      "changeCurrentCatId",
      props.info.id
  );
    //判断是否有锁
    clientChangeVideo(params, (res) => {});
  } else {
    // 报名、锁状态提示
    fetchCourseTipByRecord(props.courseDetail, "课件");
  }
  console.log(params, "updateChangeLessonApi");
}

// 下载相关
function doDownLoadEvent() {
  if(currentIsLock.value == 0 && [3, 4].includes(catLatestInfo.value?.courseType)){
    if(props.courseDetail.joinStatus < 1){
      return
    }
    if(downloadProgress.value == 0){
      doDownLoad()
      return
    }
    if(downloadProgress.value < 100 && downloadProgress.value > 0){
      changeDownLoadMode()
      return
    }
  }
 
}

// 下载课件
const doDownLoad = debounceFun(function() {
  if(fetchIsNoneEffect(props.info)){
    return
  }
  let params = {
    ...props.info,
    courseTrainId: route.query.id,
  };
  currentDownloadCatId.value = props.info.id;
  console.log(params, "clientDownloadVideo");
  clientDownloadVideo(params, (res) => {});
}, globalDebounceTime);

//停止下载正在下载的课件
const changeDownLoadMode = debounceFun(function() {
  let params = {
    ...props.info,
    courseTrainId: route.query.id,
  };
  currentDownloadCatId.value = props.info.id;
  console.log(params, "clientCancelDownloadMedia");
  if (isDownload.value) {
    doDownLoad();
  } else {
    clientCancelDownloadMedia(params, (res) => {});
  }
  changeIsDownload();
}, globalDebounceTime);

// 切换暂停 | 继续 下载模式
function changeIsDownload() {
  isDownload.value = !isDownload.value;
}

function initChangeDownloadProgress() {
  console.log(
    props.info.id,
    props.lessonDownProgress,
    "initChangeDownloadProgress"
  );
  const { progress } = props.lessonDownProgress;
  fetchDownloadProgressVal(progress);
}

function fetchDownloadProgressVal(progress) {
  let currProgress = Math.floor(100 * progress);
  if (currProgress <= 0) {
    currProgress = 0;
  }
  if (currProgress >= 100) {
    currProgress = 100;
    isDownload.value = false;
  }
  downloadProgress.value = currProgress;
}

nextTick(() => {
  // if (props.info) {
  //   currentIsLock.value = props.info?.isLock;
  // }
  if (props.info.isLastLearnCatalog) {
    currentCatId.value = props.info.id;
  }
  // console.log(props.info.lessonId, "isLastLearnCatalog");
  appContext.config.globalProperties.Bus.on("changeCurrentCatId", (data) => {
    console.log("接收到的内容是：" + data);
    currentCatId.value = data;
    // if(){
    //   currentIsLock.value = 0; //解锁
    // }
  });
  if (props.info.type == 2) {
    // 只有课才调用获取初始加载进度
    clientMediaDownloadProgress(
      { ...props.info, courseTrainId: route.query.id },
      (res) => {
        // initChangeDownloadProgress(res)
        isDownload.value = res?.progress > 0 && res?.progress < 1;
        fetchDownloadProgressVal(res?.progress);
      }
    );
  }
});
watch(
  () => props.lessonDownProgress,
  () => {
    if (props.lessonDownProgress.catalogId == props.info.id) {
      initChangeDownloadProgress();
    }
  },
  { deep: true }
);
</script>

<style lang="less">
@import url("../style/courseCat.less");
</style>
