import { closeToast, Form, Icon, Popup, showDialog, showToast } from 'vant';
import {
  defineComponent,
  onMounted,
  reactive,
  nextTick,
  onUnmounted,
  ref,
  watch,
  Transition,
  computed
} from 'vue';
import iconBack from './image/back.svg';
import styles from './index.module.less';
import 'plyr/dist/plyr.css';
import { useRoute, useRouter } from 'vue-router';
import {
  listenerMessage,
  postMessage,
  promisefiyPostMessage,
  removeListenerMessage
} from '@/helpers/native-message';
import MusicScore from './component/musicScore';
import iconMenu from './image/icon-menu.svg';
import iconChange from './image/icon-change.svg';
import iconDian from './image/icon-dian.svg';
import iconPoint from './image/icon-point.svg';
import iconUp from './image/icon-up.svg';
import iconDown from './image/icon-down.svg';
import Points from './component/points';
import { browser, getSecondRPM } from '@/helpers/utils';
import { Vue3Lottie } from 'vue3-lottie';
import playLoadData from './datas/data.json';
import { usePageVisibility } from '@vant/use';
import AudioItem from './component/audio-item';
import {
  api_classLessonCoursewareQuery,
  api_lessonCoursewareKnowledgeDetailDetail
} from './api';
import {
  api_lessonDetailCourseware,
  api_classDetailCourseware
} from '../courseware-list/api';
import VideoItem from './component/video-item';
import Chapter from './component/chapter';
import {
  api_classLessonCoursewareDetail,
  api_lessonCoursewareDetail
} from '../courseware-list/api';
// import detail from '../information/help-center/detail';
import { state } from '@/state';
import Theory from './component/theory';
import InstrumentInfo from './component/instrument-info';
// import TempoPractice from '../../views/tempo-practice';
import SelectCoursewarePop from '@/components/select-courseware-pop';
import { debounce } from '../../helpers/utils';
import TempoItem from './component/tempo-item';
import ListenItem from './component/listen-item';
import SelectCoursewareMember from '@/components/select-courseware-member';

export default defineComponent({
  name: 'CoursewarePlay',
  setup() {
    const pageVisibility = usePageVisibility();
    const lastTimeKey = 'lastTime' + (state?.user?.data?.phone ?? '');
    const showSelectCourseware = ref(false);
    const showMember = ref(false);
    const debounceSkip = ref(false);
    /** 设置播放容器 16:9 */
    const parentContainer = reactive({
      width: '100vw'
    });
    const setContainer = () => {
      let min = Math.min(screen.width, screen.height);
      let max = Math.max(screen.width, screen.height);
      let width = min * (16 / 9);
      if (width > max) {
        parentContainer.width = '100vw';
        return;
      } else {
        parentContainer.width = width + 'px';
      }
    };
    const handleInit = (type = 0) => {
      //设置容器16:9
      setContainer();
      // 横屏
      // postMessage(
      //   {
      //     api: 'setRequestedOrientation',
      //     content: {
      //       orientation: type
      //     }
      //   },
      //   () => {
      //     console.log(234);
      //   }
      // );
      // 头,包括返回箭头
      // postMessage({
      //   api: 'setTitleBarVisibility',
      //   content: {
      //     status: type
      //   }
      // })
      // 安卓的状态栏
      postMessage({
        api: 'setStatusBarVisibility',
        content: {
          isVisibility: type
        }
      });
      // 进入页面设置常量
      postMessage({
        api: 'keepScreenLongLight',
        content: {
          isOpenLight: type ? true : false
        }
      });
    };
    handleInit();
    onUnmounted(() => {
      handleInit(1);
      window.removeEventListener('message', iframeHandle);
    });

    const getCourseDetail = async () => {
      try {
        if (route.query.tab == 'course') {
          const res = await api_classLessonCoursewareDetail({
            id: activeData.courseId as any,
            subjectId: activeData.subjectId
          });
          if (res?.code == 200 && Array.isArray(res?.data?.lessonList)) {
            data.courseDetails = res.data.lessonList || [];
            // console.log('🚀 ~ data.details course:', data.courseDetails);
          }
        } else {
          const res = await api_lessonCoursewareDetail({
            id: route.query.lessonCoursewareId as any,
            subjectId: activeData.subjectId
          });
          if (res?.code == 200 && Array.isArray(res?.data?.lessonList)) {
            data.courseDetails = res.data.lessonList || [];
          }
        }

        // console.log(data.courseDetails, 'data.courseDetails');
      } catch {
        //
      }
    };

    const route = useRoute();
    const headeRef = ref();
    const loadingClass = ref(false); // 重新加载课件
    const data = reactive({
      allList: [] as any, // 所选章节下的所有课件列表
      kjId: route.query.id as string, // 所选的课件id
      currentCourse: {} as any, // 当前选中的课件
      zsdId: '' as string, // 知识点id
      knowledgePointList: [] as any, //所选课件，所选知识点下所有的资源列表
      courseDetails: [] as any,
      itemList: [] as any,
      videoRefs: {} as any[],

      videoState: 'init' as 'init' | 'play',
      videoItemRef: null as any,
      animationState: 'start' as 'start' | 'end',
      coursewareList: []
    });
    const activeData = reactive({
      isAutoPlay: true, // 是否自动播放
      subjectId: route.query.subjectId,
      lessonCoursewareId: route.query.lessonCoursewareId,
      lessonCoursewareDetailId: route.query.lessonCoursewareDetailId,
      coursewareDetailKnowledgeId: route.query.coursewareDetailKnowledgeId,
      courseId: route.query.courseId, // 我的课程专用编号
      nowTime: 0,
      model: true, // 遮罩
      isAnimation: true, // 是否动画
      videoBtns: true, // 视频
      currentTime: 0,
      duration: 0,
      timer: null as any,
      item: null as any
    });
    //  切换单元临时数据
    const temporaryData = reactive({
      dyId: '', // 单元id
      zjId: '' // 章节id
    });
    const getDetail = async () => {
      data.allList = [];
      let courseList: any[] = [];
      if (route.query.tab == 'course') {
        // const res = await api_classLessonCoursewareQuery({
        //   coursewareDetailKnowledgeId: activeData.coursewareDetailKnowledgeId,
        //   subjectId: activeData.subjectId,
        //   page: 1,
        //   rows: -1
        // });
        const res = await api_classDetailCourseware({
          lessonCoursewareKnowledgeDetailId:
            activeData.coursewareDetailKnowledgeId // 章节id
        });
        if (res?.code === 200 && Array.isArray(res.data)) {
          // const tempRows = res.data.rows || [];
          // tempRows.forEach((item: any) => {
          //   courseList.push({
          //     content: item.content,
          //     coverImg: item.coverImg,
          //     id: item.id,
          //     materialId: item.materialId,
          //     name: item.materialName,
          //     relOrder: 0,
          //     sourceFrom: item.source,
          //     type: item.materialType
          //   });
          // });
          res.data.forEach((item: any) => {
            item.knowledgeList = item.resourceList;
            item.resourceList.forEach((n: any) => {
              n.materialInfo = n.resourceList;
            });
          });
          data.allList = res.data;
          const currentCourse = res.data.find(
            (item: any) => item.id === data.kjId
          );
          data.zsdId = currentCourse?.knowledgeList?.[0].id;
          courseList = currentCourse?.knowledgeList?.[0].materialInfo || [];
          data.currentCourse = currentCourse || {};
        }
      } else {
        // const res = await api_lessonCoursewareKnowledgeDetailDetail({
        //   lessonCoursewareKnowledgeDetailId:
        //     activeData.coursewareDetailKnowledgeId,
        //   subjectId: activeData.subjectId
        // });
        const res = await api_lessonDetailCourseware({
          lessonCoursewareKnowledgeDetailId:
            activeData.coursewareDetailKnowledgeId // 章节id
        });
        if (res?.code === 200 && Array.isArray(res.data)) {
          data.allList = res.data;
          const currentCourse = res.data.find(
            (item: any) => item.id === data.kjId
          );
          data.zsdId = currentCourse?.knowledgeList?.[0].id;
          courseList = currentCourse?.knowledgeList?.[0].materialInfo || [];
          data.currentCourse = currentCourse || {};
          // console.log('课件类型', data.allList);
        }
      }
      // 当前的资源id
      let resourceId: any = null;
      // 课程
      if (courseList.length > 0) {
        resourceId = courseList[0].id;
        data.knowledgePointList = courseList.map((item: any) => {
          return {
            ...item,
            url:
              item.type === 'SONG'
                ? 'https://oss.dayaedu.com/ktqy/1698420034679a22d3f7a.png'
                : item.type === 'PPT'
                ? 'https://oss.dayaedu.com/ktqy/12/1701931810284.png'
                : item.coverImg
          };
        });
      }
      // 当前章节下的所有资源列表
      let allResource: any = [];
      data.allList.forEach((item: any) => {
        item.knowledgeList.forEach((material: any) => {
          material.materialInfo.forEach((resource: any) => {
            resource.zsdId = material.id; // 知识点id
            resource.kjId = item.id; // 课件id
            resource.bizId =
              route.query.tab == 'course'
                ? resource.materialId
                : resource.bizId;
            resource.url =
              resource.type === 'SONG'
                ? 'https://oss.dayaedu.com/ktqy/1698420034679a22d3f7a.png'
                : resource.type === 'PPT'
                ? 'https://oss.dayaedu.com/ktqy/12/1701931810284.png'
                : resource.coverImg;
          });
          allResource = allResource.concat(material.materialInfo);
        });
      });

      // 当前章节下，所选的课件所有资源列表
      let allKjResource: any = [];
      data.currentCourse?.knowledgeList?.forEach((material: any) => {
        material.materialInfo.forEach((resource: any) => {
          resource.zsdId = material.id; // 知识点id
          resource.kjId = data.currentCourse.id; // 课件id
          resource.bizId =
            route.query.tab == 'course' ? resource.materialId : resource.bizId;
          resource.url =
            resource.type === 'SONG'
              ? 'https://oss.dayaedu.com/ktqy/1698420034679a22d3f7a.png'
              : resource.type === 'PPT'
              ? 'https://oss.dayaedu.com/ktqy/12/1701931810284.png'
              : resource.coverImg;
        });
        allKjResource = allKjResource.concat(material.materialInfo);
      });

      data.itemList = allKjResource.map((m: any, index: number) => {
        if (!popupData.itemActive) {
          popupData.itemActive = m.id;
          popupData.itemName = m.name;
        }
        return {
          ...m,
          iframeRef: null,
          videoEle: null,
          autoPlay: false, //加载完成是否自动播放
          isprepare: false, // 视频是否加载完成
          isRender: false // 是否渲染了
        };
      });
      const resourceIndex = data.itemList.findIndex(
        (resource: any) => resource.id === resourceId
      );
      setTimeout(() => {
        handleSwipeChange(resourceIndex);
      }, 0);

      setTimeout(() => {
        data.animationState = 'end';
      }, 500);
    };

    // ifram事件处理
    const iframeHandle = (ev: MessageEvent) => {
      if (ev.data?.api === 'headerTogge') {
        activeData.model =
          ev.data.show || (ev.data.playState == 'play' ? false : true);
      }
      if (ev.data?.api === 'api_fingerPreView') {
        clearInterval(activeData.timer);
        activeData.model = !ev.data.state;
      }

      if (ev.data?.api === 'clickTempo' || ev.data?.api === 'clickViewFigner') {
        setModelOpen();
      }
    };

    onMounted(() => {
      // needVipLock
      const schoolInfos = state.user.data?.schoolInfos;
      const schoolLock =
        schoolInfos && schoolInfos.length > 0
          ? schoolInfos[0].needVipLock
          : true;
      if (!state?.user?.data.vipMember && schoolLock) {
        showMember.value = true;
      } else {
        showMember.value = false;
      }
      postMessage({
        api: 'courseLoading',
        content: {
          show: false,
          type: 'fullscreen'
        }
      });
      getDetail();
      getCourseDetail();
      window.addEventListener('message', iframeHandle);
    });

    const playRef = ref();
    // 返回
    const goback = () => {
      try {
        playRef.value?.handleOut();
      } catch (error) {}
      postMessage({ api: 'goBack' });
      // router.back()
    };

    const popupData = reactive({
      open: false,
      activeIndex: 0,
      itemActive: '',
      itemName: '',
      itemPointName: route.query.name as any,
      chapterOpen: false
    });

    // 切换素材
    const toggleMaterial = (itemActive: any, zsdId: any, kjId: any) => {
      // 如果切换了知识点或者切换了课件，需要加载新的
      // if (zsdId !== data.zsdId || kjId !== data.kjId) {
      //   data.zsdId = zsdId
      //   data.kjId = kjId
      //   let target = { materialInfo: [] }
      //   // 如果是切换了知识点id
      //   const kjIndex = data.allList.findIndex((item: any) => item.id === kjId)
      //   target = data.allList[kjIndex].knowledgeList.find((item: any) => item.id === zsdId)
      // } else {
      //   const index = data.itemList.findIndex((n: any) => n.id == itemActive);
      //   if (index > -1) {
      //     handleSwipeChange(index);
      //   }
      // }
      const index = data.itemList.findIndex((n: any) => n.id == itemActive);
      if (index > -1) {
        handleSwipeChange(index);
      }
    };
    /** 延迟收起模态框 */
    const setModelOpen = () => {
      clearTimeout(activeData.timer);
      closeToast();
      activeData.model = !activeData.model;
      activeData.timer = setTimeout(() => {
        activeData.model = false;
      }, 4000);
    };
    const setModelOpen1 = () => {
      clearTimeout(activeData.timer);
      closeToast();
      activeData.model = true;
      activeData.timer = setTimeout(() => {
        activeData.model = false;
      }, 4000);
    };

    // 双击
    const handleDbClick = (item: any) => {
      if (item && ['VIDEO'].includes(item.type)) {
        console.log('双击');
      }
    };
    const effectIndex = ref(3);
    const effects = [
      {
        prev: {
          transform: 'translate3d(0, 0, -800px) rotateX(180deg)'
        },
        next: {
          transform: 'translate3d(0, 0, -800px) rotateX(-180deg)'
        }
      },
      {
        prev: {
          transform: 'translate3d(-100%, 0, -800px)'
        },
        next: {
          transform: 'translate3d(100%, 0, -800px)'
        }
      },
      {
        prev: {
          transform: 'translate3d(-50%, 0, -800px) rotateY(80deg)'
        },
        next: {
          transform: 'translate3d(50%, 0, -800px) rotateY(-80deg)'
        }
      },
      {
        prev: {
          transform: 'translate3d(-100%, 0, -800px) rotateY(-120deg)',
          opacity: 0
        },
        next: {
          transform: 'translate3d(100%, 0, -800px) rotateY(120deg)',
          opacity: 0
        }
      },
      // 风车4
      {
        prev: {
          transform: 'translate3d(-50%, 50%, -800px) rotateZ(-14deg)',
          opacity: 0
        },
        next: {
          transform: 'translate3d(50%, 50%, -800px) rotateZ(14deg)',
          opacity: 0
        }
      },
      // 翻页5
      {
        prev: {
          transform: 'translateZ(-800px) rotate3d(0, -1, 0, 90deg)',
          opacity: 0
        },
        next: {
          transform: 'translateZ(-800px) rotate3d(0, 1, 0, 90deg)',
          opacity: 0
        },
        current: { transitionDelay: '700ms' }
      }
    ];
    const handleStop = () => {
      data.videoItemRef?.pause();
    };
    const acitveTimer = ref();
    // 轮播切换
    const handleSwipeChange = (index: number) => {
      // 如果是当前正在播放 或者是视频最后一个
      if (popupData.activeIndex == index) return;
      data.animationState = 'start';
      data.videoState = 'init';
      handleStop();
      clearTimeout(acitveTimer.value);
      activeData.model = true;
      const item = data.itemList[index];
      data.kjId = item.kjId;
      data.zsdId = item.zsdId;
      popupData.activeIndex = index;
      popupData.itemActive = item.id;
      popupData.itemName = item.name;
      if (item.type == 'MUSIC') {
        activeData.model = true;
      } else if (item.type == 'VIDEO') {
        if (item.error) {
          data.videoRefs[index]?.onPlay();
        }
        setTimeout(() => {
          data.animationState = 'end';
        }, 800);
      }
    };

    // 上一个知识点, 下一个知识点
    const handlePreAndNext = async (type: string) => {
      // 层级关系：单元〉章节〉知识点〉课件资源
      if (type === 'up') {
        // 判断上面是否还有章节
        if (popupData.activeIndex > 0) {
          handleSwipeChange(popupData.activeIndex - 1);
          return;
        }

        // 获取当前是哪个章节
        let detailIndex = data.courseDetails.findIndex(
          (item: any) => item.id == activeData.lessonCoursewareDetailId
        );
        const detailItem = data.courseDetails[detailIndex]?.knowledgeList || [];
        let lessonIndex = detailItem.findIndex(
          (item: any) => item.id == activeData.coursewareDetailKnowledgeId
        );

        let lessonStatus = false; // 当前章节上面是否有内容
        let lessonCoursewareDetailId = '';
        let coursewareDetailKnowledgeId = '';
        let coursewareDetailKnowledgeName = '';
        let coursewareItem = {} as any;
        while (lessonIndex >= 0) {
          lessonIndex--;

          if (lessonIndex >= 0) {
            if (detailItem[lessonIndex].containMaterial) {
              lessonStatus = true;
              lessonCoursewareDetailId =
                detailItem[lessonIndex].lessonCoursewareDetailId;
              coursewareDetailKnowledgeId = detailItem[lessonIndex].id;
              coursewareDetailKnowledgeName = detailItem[lessonIndex].name;
              coursewareItem = detailItem[lessonIndex];
            }
          }

          if (lessonStatus) {
            break;
          }
        }
        // 判断当前章节下面课程是否有内容，否则往上一个章节走
        if (lessonStatus) {
          // loadingClass.value = true;
          // activeData.coursewareDetailKnowledgeId = coursewareDetailKnowledgeId;
          // activeData.lessonCoursewareDetailId = lessonCoursewareDetailId;
          // await getDetail();
          // popupData.activeIndex = data.itemList.length - 1 || 0;
          // popupData.itemActive =
          //   data.knowledgePointList[data.itemList.length - 1]?.id ||
          //   data.knowledgePointList[0]?.id;
          // popupData.itemPointName = coursewareDetailKnowledgeName;
          // popupData.itemName =
          //   data.knowledgePointList[data.itemList.length - 1]?.name ||
          //   data.knowledgePointList[0]?.name;
          // localStorage.setItem(lastTimeKey, coursewareDetailKnowledgeId);
          // popupData.chapterOpen = false;
          // loadingClass.value = false;
          // console.log
          temporaryData.zjId = coursewareDetailKnowledgeId;
          temporaryData.dyId = lessonCoursewareDetailId;
          // activeData.coursewareDetailKnowledgeId = coursewareDetailKnowledgeId;
          checkCourseware({
            ...coursewareItem,
            itemActive: coursewareDetailKnowledgeId
          });
          return;
        }

        let prevLessonStatus = false;
        while (detailIndex >= 0) {
          detailIndex--;
          const tempDetail =
            data.courseDetails[detailIndex]?.knowledgeList || [];
          let tempLessonLength = tempDetail.length;
          while (tempLessonLength > 0) {
            if (tempDetail[tempLessonLength - 1].containMaterial) {
              prevLessonStatus = true;
              lessonCoursewareDetailId =
                tempDetail[tempLessonLength - 1].lessonCoursewareDetailId;
              coursewareDetailKnowledgeId = tempDetail[tempLessonLength - 1].id;
              coursewareDetailKnowledgeName =
                tempDetail[tempLessonLength - 1].name;
              coursewareItem = tempDetail[tempLessonLength - 1];
            }
            tempLessonLength--;
            if (prevLessonStatus) {
              break;
            }
          }

          if (prevLessonStatus) {
            break;
          }
        }

        // 判断当前章节下面课程是否有内容，否则往上一个章节走
        if (prevLessonStatus) {
          // loadingClass.value = true;
          // activeData.coursewareDetailKnowledgeId = coursewareDetailKnowledgeId;
          // activeData.lessonCoursewareDetailId = lessonCoursewareDetailId;
          // await getDetail();
          // popupData.activeIndex = data.itemList.length - 1 || 0;
          // popupData.itemActive =
          //   data.knowledgePointList[data.itemList.length - 1]?.id ||
          //   data.knowledgePointList[0]?.id;
          // localStorage.setItem(lastTimeKey, coursewareDetailKnowledgeId);
          // popupData.itemPointName = coursewareDetailKnowledgeName;
          // popupData.itemName =
          //   data.knowledgePointList[data.itemList.length - 1]?.name ||
          //   data.knowledgePointList[0]?.name;
          // popupData.chapterOpen = false;
          // loadingClass.value = false;
          // console.log('2', coursewareItem, coursewareDetailKnowledgeId);
          temporaryData.zjId = coursewareDetailKnowledgeId;
          temporaryData.dyId = lessonCoursewareDetailId;
          // activeData.coursewareDetailKnowledgeId = coursewareDetailKnowledgeId;
          checkCourseware({
            ...coursewareItem,
            itemActive: coursewareDetailKnowledgeId
          });
          return;
        }
      } else {
        if (popupData.activeIndex < data.itemList.length - 1) {
          handleSwipeChange(popupData.activeIndex + 1);
          return;
        }

        // 获取当前是哪个单元
        let detailIndex = data.courseDetails.findIndex(
          (item: any) => item.id == activeData.lessonCoursewareDetailId
        );
        // 当前章节列表
        const detailItem = data.courseDetails[detailIndex]?.knowledgeList || [];
        // 获取当前是哪个章节
        let lessonIndex = detailItem.findIndex(
          (item: any) => item.id == activeData.coursewareDetailKnowledgeId
        );

        let lessonStatus = false; // 当前章节下面是否有内容
        let lessonCoursewareDetailId = '';
        let coursewareDetailKnowledgeId = '';
        let coursewareDetailKnowledgeName = '';
        let coursewareItem = {} as any;
        while (lessonIndex < detailItem.length - 1) {
          lessonIndex++;
          if (lessonIndex >= 0) {
            if (detailItem[lessonIndex].containMaterial) {
              lessonStatus = true;
              lessonCoursewareDetailId =
                detailItem[lessonIndex].lessonCoursewareDetailId;
              coursewareDetailKnowledgeId = detailItem[lessonIndex].id;
              coursewareDetailKnowledgeName = detailItem[lessonIndex].name;
              coursewareItem = detailItem[lessonIndex];
            }
          }
          if (lessonStatus) {
            break;
          }
        }
        // 判断当前章节下面课程是否有内容，否则往下一个章节走
        if (lessonStatus) {
          // loadingClass.value = true;
          // activeData.coursewareDetailKnowledgeId = coursewareDetailKnowledgeId;
          // activeData.lessonCoursewareDetailId = lessonCoursewareDetailId;
          // await getDetail();
          // popupData.activeIndex = 0;
          // popupData.itemActive = data.knowledgePointList[0].id;
          // popupData.itemName = data.knowledgePointList[0].name;
          // localStorage.setItem(lastTimeKey, coursewareDetailKnowledgeId);
          // popupData.itemPointName = coursewareDetailKnowledgeName;
          // popupData.chapterOpen = false;
          // loadingClass.value = false;
          temporaryData.zjId = coursewareDetailKnowledgeId;
          temporaryData.dyId = lessonCoursewareDetailId;
          // activeData.coursewareDetailKnowledgeId = coursewareDetailKnowledgeId;
          // console.log(coursewareItem, 'coursewareItem', temporaryData);
          checkCourseware({
            ...coursewareItem,
            itemActive: coursewareDetailKnowledgeId
          });
          return;
        }

        let nextLessonStatus = false;
        while (detailIndex <= data.courseDetails.length - 1) {
          detailIndex++;
          const tempDetail =
            data.courseDetails[detailIndex]?.knowledgeList || [];
          let tempLessonLength = 0;
          while (tempLessonLength <= tempDetail.length - 1) {
            if (tempDetail[tempLessonLength].containMaterial) {
              nextLessonStatus = true;
              lessonCoursewareDetailId =
                tempDetail[tempLessonLength].lessonCoursewareDetailId;
              coursewareDetailKnowledgeId = tempDetail[tempLessonLength].id;
              coursewareDetailKnowledgeName = tempDetail[tempLessonLength].name;
              coursewareItem = tempDetail[tempLessonLength];
            }
            tempLessonLength++;
            if (nextLessonStatus) {
              break;
            }
          }

          if (nextLessonStatus) {
            break;
          }
        }

        // 判断当前章节下面课程是否有内容，否则往下一个单元走
        if (nextLessonStatus) {
          // loadingClass.value = true;
          // activeData.coursewareDetailKnowledgeId = coursewareDetailKnowledgeId;
          // activeData.lessonCoursewareDetailId = lessonCoursewareDetailId;
          // await getDetail();
          // popupData.activeIndex = 0;
          // popupData.itemActive = data.knowledgePointList[0].id;
          // localStorage.setItem(lastTimeKey, coursewareDetailKnowledgeId);
          // popupData.itemName = data.knowledgePointList[0].name;
          // popupData.itemPointName = coursewareDetailKnowledgeName;
          // popupData.chapterOpen = false;
          // loadingClass.value = false;
          temporaryData.zjId = coursewareDetailKnowledgeId;
          temporaryData.dyId = lessonCoursewareDetailId;
          // activeData.coursewareDetailKnowledgeId = coursewareDetailKnowledgeId;
          // console.log(coursewareItem, 'coursewareItem', temporaryData);
          checkCourseware({
            ...coursewareItem,
            itemActive: coursewareDetailKnowledgeId
          });
          return;
        }
      }
    };

    /** 弹窗关闭 */
    const handleClosePopup = () => {
      // setModelOpen();
    };

    // popupData.activeIndex == 0 && styles.btnsDisabled
    // popupData.activeIndex == data.itemList.length - 1

    // 是否允许上一页
    const isUpArrow = computed(() => {
      /**
       * 1，判断当前课程中是否处在第一个资源；
       * 2，判断当前课程是否在当前章节的第一个；
       * 3，判断当前章节，当前课程上面还没有其它课程，是否有资源；
       * 4，判断当前章节上面还没有其它章节；
       * 5，判断上面章节里面课程是否有资源；
       */

      if (popupData.activeIndex > 0) {
        return true;
      }

      // 获取当前是哪个章节
      let detailIndex = data.courseDetails.findIndex(
        (item: any) => item.id == activeData.lessonCoursewareDetailId
      );
      const detailItem = data.courseDetails[detailIndex]?.knowledgeList || [];
      let lessonIndex = detailItem.findIndex(
        (item: any) => item.id == activeData.coursewareDetailKnowledgeId
      );

      // 说明已经是第一单元，第一课
      if (detailIndex <= 0 && lessonIndex <= 0) {
        return false;
      }

      let lessonStatus = false; // 当前章节上面是否有内容
      while (lessonIndex >= 0) {
        lessonIndex--;

        if (lessonIndex >= 0) {
          if (detailItem[lessonIndex].containMaterial) {
            lessonStatus = true;
          }
        }
      }
      // 判断当前章节下面课程是否有内容，否则往上一个章节走
      if (lessonStatus) {
        return true;
      }

      // 已经是第一个章节了
      if (detailIndex <= 0) {
        return false;
      }

      let prevLessonStatus = false;
      while (detailIndex >= 0) {
        detailIndex--;
        const tempDetail = data.courseDetails[detailIndex]?.knowledgeList || [];
        let tempLessonLength = tempDetail.length;
        while (tempLessonLength > 0) {
          if (tempDetail[tempLessonLength - 1].containMaterial) {
            prevLessonStatus = true;
          }
          tempLessonLength--;
        }

        if (prevLessonStatus) {
          return true;
        }
      }

      return false;
    });

    // 是否允许下一页
    const isDownArrow = computed(() => {
      if (popupData.activeIndex < data.itemList.length - 1) {
        return true;
      }

      // 获取当前是哪个章节
      let detailIndex = data.courseDetails.findIndex(
        (item: any) => item.id == activeData.lessonCoursewareDetailId
      );
      const detailItem = data.courseDetails[detailIndex]?.knowledgeList || [];
      let lessonIndex = detailItem.findIndex(
        (item: any) => item.id == activeData.coursewareDetailKnowledgeId
      );

      // 说明已经是最后-单元，最后一课
      if (
        detailIndex >= data.courseDetails.length - 1 &&
        lessonIndex >= detailItem.length - 1
      ) {
        return false;
      }

      let lessonStatus = false; // 当前章节下面是否有内容
      while (lessonIndex < detailItem.length - 1) {
        lessonIndex++;
        if (lessonIndex >= 0) {
          if (detailItem[lessonIndex].containMaterial) {
            lessonStatus = true;
          }
        }
      }

      // 判断当前章节下面课程是否有内容，否则往下一个章节走
      if (lessonStatus) {
        return true;
      }

      // 已经是最后一个章节了
      if (detailIndex >= data.courseDetails.length - 1) {
        return false;
      }

      let nextLessonStatus = false;
      while (detailIndex < data.courseDetails.length - 1) {
        detailIndex++;
        const tempDetail = data.courseDetails[detailIndex]?.knowledgeList || [];
        let tempLessonLength = 0;
        while (tempLessonLength <= tempDetail.length - 1) {
          if (tempDetail[tempLessonLength].containMaterial) {
            nextLessonStatus = true;
          }
          tempLessonLength++;
        }

        if (nextLessonStatus) {
          return true;
        }
      }

      return false;
    });

    const activeVideoItem = computed(() => {
      const item = data.itemList[popupData.activeIndex];
      if (item && item.type && item.type.toLocaleUpperCase() === 'VIDEO') {
        return item;
      }
      return {};
    });

    // 加载新的章节里的课件
    const loadNewCourseware = async (item: any) => {
      if (item.id === data.kjId) {
        showSelectCourseware.value = false;
        return;
      }
      if (debounceSkip.value) return;
      debounceSkip.value = true;
      data.itemList = [];
      loadingClass.value = true;
      // activeData.coursewareDetailKnowledgeId = item.coursewareDetailKnowledgeId;
      // activeData.lessonCoursewareDetailId = item.lessonCoursewareDetailId;
      if (route.query.tab == 'all') {
        activeData.coursewareDetailKnowledgeId =
          item.coursewareDetailKnowledgeId;
        activeData.lessonCoursewareDetailId = temporaryData.dyId;
        localStorage.setItem(lastTimeKey, item.coursewareDetailKnowledgeId);
      } else {
        activeData.lessonCoursewareDetailId = temporaryData.dyId;
        activeData.coursewareDetailKnowledgeId = temporaryData.zjId;
        localStorage.setItem(lastTimeKey, temporaryData.zjId);
      }
      // console.log(item, 'item', route.query.tab);
      // console.log(activeData, temporaryData, 'active');
      popupData.chapterOpen = false;
      showSelectCourseware.value = false;
      data.kjId = item.id;
      await getDetail();
      popupData.activeIndex = 0;
      popupData.itemActive = data.knowledgePointList[0].id;
      popupData.itemName = data.knowledgePointList[0].name;
      // 匹配到当前的章节名称
      const dyItem = data.courseDetails.find(
        (unit: any) => unit.id === activeData.lessonCoursewareDetailId
      );
      const zjItem = dyItem?.knowledgeList?.find(
        (chapter: any) => chapter.id === activeData.coursewareDetailKnowledgeId
      );
      zjItem && (popupData.itemPointName = zjItem.name);
      // console.log('章节名称', popupData.itemPointName);
      loadingClass.value = false;
      debounceSkip.value = false;
    };
    // 通过章节id，检测此章节有几个课件
    const checkCourseware = async (item: any, checkType?: any) => {
      // 如果有多个课件，需要选择一个课件进入上课页面
      if (item.coursewareNum || checkType) {
        try {
          if (checkType) {
            // @ts-ignore
            temporaryData.zjId = activeData.coursewareDetailKnowledgeId;
            // @ts-ignore
            temporaryData.dyId = activeData.lessonCoursewareDetailId;
          }
          const res =
            route.query.tab == 'all'
              ? await api_lessonDetailCourseware({
                  lessonCoursewareKnowledgeDetailId: checkType
                    ? activeData.coursewareDetailKnowledgeId
                    : item.itemActive
                })
              : await api_classDetailCourseware({
                  lessonCoursewareKnowledgeDetailId: checkType
                    ? activeData.coursewareDetailKnowledgeId
                    : item.itemActive
                });
          if (res?.code == 200 && res.data?.length) {
            data.coursewareList = res.data;
            // 如果只有一个课件，直接进入该课件
            // console.log(res.data, 'data');
            if (res.data.length == 1) {
              loadNewCourseware({ ...res.data[0] });
            } else {
              // 如果有多个课件，需要选择一个课件进入上课页面
              showSelectCourseware.value = true;
            }
          }
        } catch {
          //
        }
      }
    };

    return () => (
      <div id="playContent" class={styles.playContent}>
        <div
          class={styles.coursewarePlay}
          style={{ width: parentContainer.width }}
          onClick={() => setModelOpen()}>
          {!loadingClass.value && (
            <div class={styles.wraps}>
              <div
                style={
                  activeVideoItem.value.type &&
                  data.animationState === 'end' &&
                  data.videoState === 'play'
                    ? {
                        zIndex: 15,
                        opacity: 1
                      }
                    : { opacity: 0, zIndex: -1 }
                }
                class={styles.itemDiv}>
                <VideoItem
                  ref={(el: any) => (data.videoItemRef = el)}
                  item={activeVideoItem.value}
                  showModel={activeData.model}
                  onClose={setModelOpen1}
                  onCanplay={() => {
                    data.videoState = 'play';
                  }}
                  onPause={() => {
                    clearTimeout(activeData.timer);
                    activeData.model = true;
                  }}
                  onEnded={() => {
                    // const _index = popupData.activeIndex + 1
                    // if (_index < data.itemList.length) {
                    //   handleSwipeChange(_index);
                    // }
                  }}
                />
              </div>
              {data.itemList.map((m: any, mIndex: number) => {
                const isRender =
                  m.isRender || Math.abs(popupData.activeIndex - mIndex) < 2;
                const isEmtry = Math.abs(popupData.activeIndex - mIndex) > 4;
                if (isRender) {
                  m.isRender = true;
                }
                return isRender ? (
                  <div
                    key={'index' + mIndex}
                    class={[
                      styles.itemDiv,
                      popupData.activeIndex === mIndex && styles.itemActive,
                      activeData.isAnimation && styles.acitveAnimation,
                      Math.abs(popupData.activeIndex - mIndex) < 2
                        ? styles.show
                        : styles.hide
                    ]}
                    style={
                      mIndex < popupData.activeIndex
                        ? effects[effectIndex.value].prev
                        : mIndex > popupData.activeIndex
                        ? effects[effectIndex.value].next
                        : {}
                    }
                    onClick={(e: Event) => {
                      if (Date.now() - activeData.nowTime < 300) {
                        handleDbClick(m);
                        return;
                      }
                      activeData.nowTime = Date.now();
                    }}>
                    {m.type === 'IMG' && <img src={m.content} />}
                    {m.type === 'PPT' && (
                      <iframe
                        src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
                          m.content
                        )}`}
                        width="100%"
                        height="100%"
                        frameborder="1"></iframe>
                    )}
                    {m.type === 'VIDEO' && (
                      <img
                        src={m.coverImg}
                        onLoad={() => {
                          m.isprepare = true;
                        }}
                      />
                    )}
                    {/* {m.type === 'VIDEO' && (
                      <VideoItem
                        ref={(v: any) => (data.videoRefs[mIndex] = v)}
                        item={m}
                        show={popupData.activeIndex === mIndex}
                        pageVisibility={pageVisibility.value}
                        showModel={activeData.model}
                        isEmtry={isEmtry}
                        onLoadedmetadata={() => {
                          m.isprepare = true;
                          m.error = false;
                        }}
                        onEnded={() => {
                          const _index = popupData.activeIndex + 1;
                          if (_index < data.itemList.length) {
                            handleSwipeChange(_index);
                          }
                        }}
                        onReset={() => {
                          m.error = false;
                        }}
                        onError={() => {
                          m.isprepare = true;
                          m.error = true;
                        }}
                      />
                    )} */}
                    {m.type === 'SONG' && (
                      <AudioItem
                        item={m}
                        show={popupData.activeIndex === mIndex}
                        pageVisibility={pageVisibility.value}
                        showModel={activeData.model}
                        isEmtry={isEmtry}
                        onEnded={() => {
                          const _index = popupData.activeIndex + 1;
                          if (_index < data.itemList.length) {
                            handleSwipeChange(_index);
                          }
                        }}
                        onClose={() => {
                          clearTimeout(activeData.timer);
                          activeData.timer = setTimeout(() => {
                            activeData.model = false;
                          }, 4000);
                        }}
                      />
                    )}
                    {m.type === 'MUSIC' && (
                      <MusicScore
                        pageVisibility={pageVisibility.value}
                        show={popupData.activeIndex === mIndex}
                        activeModel={activeData.model}
                        data-vid={m.id}
                        music={m}
                      />
                    )}

                    {m.type === 'VIDEO' && (
                      <Transition name="van-fade">
                        {/* {!m.isprepare && (
                          <div class={styles.loadWrap}>
                            <Vue3Lottie
                              style={{ width: '100%', height: '100%' }}
                              animationData={playLoadData}></Vue3Lottie>
                          </div>
                        )} */}
                        {data.videoState !== 'play' && (
                          <div class={styles.loadWrap}>
                            <Vue3Lottie
                              style={{ width: '100%', height: '100%' }}
                              animationData={playLoadData}></Vue3Lottie>
                          </div>
                        )}
                      </Transition>
                    )}

                    {/* 新增：RHYTHM：节奏练习,THEORY：乐理知识,MUSIC_WIKI:名曲鉴赏 INSTRUMENT:乐器 MUSICIAN:音乐家 资源类型 */}
                    {m.type === 'RHYTHM' && (
                      <TempoItem
                        key={mIndex}
                        class={styles.tempoPracticeGroup}
                        dataJson={m.dataJson}
                        show={popupData.activeIndex === mIndex}
                        pageVisibility={pageVisibility.value}
                      />
                      // <TempoPractice
                      //   key={mIndex}
                      //   class={styles.tempoPracticeGroup}
                      //   dataJson={m?.dataJson ? JSON.parse(m?.dataJson) : {}}
                      //   modeType={'courseware'}
                      //   show={popupData.activeIndex === mIndex}
                      // />
                    )}
                    {m.type === 'THEORY' && <Theory id={m.bizId} />}
                    {/* {popupData.activeIndex === mIndex && ( */}
                    <>
                      {m.type === 'MUSIC_WIKI' && (
                        <InstrumentInfo
                          type={'wiki'}
                          id={m.bizId}
                          show={popupData.activeIndex === mIndex}
                        />
                      )}
                      {m.type === 'INSTRUMENT' && (
                        <InstrumentInfo
                          type={'instrument'}
                          id={m.bizId}
                          show={popupData.activeIndex === mIndex}
                        />
                      )}
                      {m.type === 'MUSICIAN' && (
                        <InstrumentInfo
                          type={'musician'}
                          id={m.bizId}
                          show={popupData.activeIndex === mIndex}
                        />
                      )}
                      {m.type === 'LISTEN' && (
                        <ListenItem
                          pageVisibility={pageVisibility.value}
                          show={popupData.activeIndex === mIndex}
                          activeModel={activeData.model}
                          data-vid={m.id}
                          item={m}
                        />
                      )}
                    </>
                    {/* )} */}
                  </div>
                ) : (
                  <div
                    key={'index' + mIndex}
                    class={[
                      styles.itemDiv,
                      popupData.activeIndex === mIndex && styles.itemActive,
                      activeData.isAnimation && styles.acitveAnimation,
                      Math.abs(popupData.activeIndex - mIndex) < 2
                        ? styles.show
                        : styles.hide
                    ]}
                    style={
                      mIndex < popupData.activeIndex
                        ? effects[effectIndex.value].prev
                        : mIndex > popupData.activeIndex
                        ? effects[effectIndex.value].next
                        : {}
                    }></div>
                );
              })}
            </div>
          )}
          <Transition name="right">
            {activeData.model && (
              <div
                class={styles.rightFixedBtns}
                onClick={(e: Event) => {
                  e.stopPropagation();
                  clearTimeout(activeData.timer);
                }}>
                <div
                  class={[styles.fullBtn, styles.point]}
                  onClick={() => (popupData.chapterOpen = true)}>
                  <img src={iconChange} />
                  <span>切换</span>
                </div>

                <div
                  class={[styles.fullBtn, styles.point]}
                  onClick={() => (popupData.open = true)}>
                  <img src={iconMenu} />
                  <span>课件</span>
                </div>

                <div
                  class={[
                    styles.fullBtn,
                    // popupData.activeIndex == 0 && styles.btnsDisabled
                    !isUpArrow.value && styles.btnsDisabled
                  ]}
                  onClick={() => handlePreAndNext('up')}>
                  <img src={iconUp} />
                  <span style={{ textAlign: 'center' }}>上一个</span>
                </div>

                <div
                  class={[
                    styles.fullBtn,
                    !isDownArrow.value && styles.btnsDisabled
                  ]}
                  onClick={() => handlePreAndNext('down')}>
                  <span style={{ textAlign: 'center' }}>下一个</span>
                  <img src={iconDown} />
                </div>
              </div>
            )}
          </Transition>
        </div>

        <div
          style={{ transform: activeData.model ? '' : 'translateY(-100%)' }}
          class={styles.headerContainer}
          ref={headeRef}>
          <div class={styles.backBtn} onClick={() => goback()}>
            <Icon name={iconBack} />
            返回
          </div>
          <div class={styles.menu}>{popupData.itemName}</div>
        </div>
        {/* 课件列表 */}
        <Popup
          class={styles.popup}
          style={{ background: 'rgba(0,0,0, 0.75)' }}
          overlayClass={styles.overlayClass}
          position="right"
          round
          v-model:show={popupData.open}
          onClose={handleClosePopup}>
          <Points
            allList={data.allList}
            currentCourse={data.currentCourse}
            data={data.knowledgePointList}
            itemActive={popupData.itemActive}
            itemName={popupData.itemPointName}
            kjId={data.kjId}
            zsdId={data.zsdId}
            popShow={popupData.open}
            onHandleSelect={(res: any) => {
              popupData.open = false;
              toggleMaterial(res.itemActive, res.zsdId, res.kjId);
            }}
            onCourseSelect={async () => {
              popupData.open = false;
              checkCourseware({}, 'same');
            }}
          />
        </Popup>
        {/* 知识点列表 */}
        <Popup
          class={styles.popup}
          style={{ background: 'rgba(0,0,0, 0.75)' }}
          overlayClass={styles.overlayClass}
          position="right"
          round
          v-model:show={popupData.chapterOpen}
          onClose={handleClosePopup}>
          <Chapter
            detail={data.courseDetails}
            itemActive={activeData.coursewareDetailKnowledgeId as any}
            active={activeData.lessonCoursewareDetailId as any}
            popShow={popupData.chapterOpen}
            onHandleSelect={async (item: any) => {
              temporaryData.dyId = item.tabActive;
              temporaryData.zjId = item.itemActive;
              popupData.itemPointName = item.itemName;
              checkCourseware(item);
            }}
          />
        </Popup>
        {showMember.value && (
          // <SelectCoursewarePop
          //   list={data.coursewareList}
          //   kjId={data.kjId}
          //   onClose={() => {
          //     showSelectCourseware.value = false;
          //   }}
          //   onSelect={item => loadNewCourseware(item)}></SelectCoursewarePop>
          <SelectCoursewareMember
            onClose={() => {
              showSelectCourseware.value = false;
            }}></SelectCoursewareMember>
        )}
      </div>
    );
  }
});
