import { closeToast, Icon, Popup, showDialog, showToast } from 'vant';
import {
  defineComponent,
  onMounted,
  reactive,
  nextTick,
  onUnmounted,
  ref,
  watch,
  Transition,
  computed,
  shallowRef
} from 'vue';
import iconBack from './image/back.svg';
import styles from './index.module.less';
import 'plyr/dist/plyr.css';
import request from '@/helpers/request';
import { handleShowVip, state } from '@/state';
import { useRoute, useRouter } from 'vue-router';
import {
  listenerMessage,
  postMessage,
  promisefiyPostMessage
} from '@/helpers/native-message';
import MusicScore from './component/musicScore';
// import iconDian from './image/icon-dian.svg';
// import iconPoint from './image/icon-point.svg';
// import qs from 'query-string';
import { iconUp, iconDown, iconTouping, iconMenu, iconCourseType, iconSearch } from './image/icons.json';
import Points from './component/points';
import { browser } from '@/helpers/utils';
import { Vue3Lottie } from 'vue3-lottie';
import playLoadData from './datas/data.json';
import { usePageVisibility } from '@vant/use';
// import PlayRecordTime from './playRecordTime';
import OGuide from '@/components/o-guide';
// import VideoItem from './component/video-item';
import VideoPlay from './component/video-play';
import deepClone from '@/helpers/deep-clone';
import { useInterval, useIntervalFn, useNetwork } from '@vueuse/core';
import CoursewareType from './component/courseware-type';
import CoursewareTips from './component/courseware-tips';
import GlobalTools from '@/components/globalTools';
import { isHidden, isPlay, penShow, toolOpen, whitePenShow } from '@/components/globalTools/globalTools';
import { vaildCurrentUrl } from '@/helpers/validate';
import PointsSearch from './component/points-search';

export default defineComponent({
  name: 'CoursewarePlay',
  setup() {
    const router = useRouter();
    const browserInfo = browser()
    const { isOnline } = useNetwork()
    const pageVisibility = usePageVisibility();
    /** 页面显示和隐藏 */
    watch(
      () => pageVisibility.value,
      value => {
        if (value == 'hidden') {
          handleStop();
        }
        if (value === "visible") {
          if(data.source === 'search') {
            getSearchDetail({
              type: 'visible',
              id: data.currentId,
              search: data.search
            })
          } else {
            getDetail('visible', data.currentId)
            getRefLevel(data.currentId)
          }
        }
      }
    );
    /** 设置播放容器 16:9 */
    const parentContainer = reactive({
      width: '100vw'
    });
    const handleInit = (type = 0) => {
      // 横屏
      postMessage(
        {
          api: 'setRequestedOrientation',
          content: {
            orientation: type
          }
        },
        () => {
          // console.log(234);
        }
      );
      // 安卓的状态栏
      postMessage({
        api: 'setStatusBarVisibility',
        content: {
          isVisibility: type
        }
      });
      // 进入页面设置常量
      postMessage({
        api: 'keepScreenLongLight',
        content: {
          isOpenLight: type ? true : false
        }
      });
    };
    handleInit();
    onUnmounted(() => {
      handleInit(1);
      window.removeEventListener('message', iframeHandle);
    });

    const route = useRoute();
    const headeRef = ref();
    const detailTempSearchList = shallowRef<any[]>()
    const detailList = shallowRef<any[]>()// 搜索来的所有数据
    const data = reactive({
      source: route.query.source as any, // 来源 search  搜索
      isSearch: route.query.source === "search" ? true : false, // 是否搜索
      searchLoading: false, // 搜索加载状态
      search: route.query.search as any, // 默认的搜索条件 -
      searchTemp: route.query.search as any, // 默认的搜索条件 -
      currentId: route.query.id as any || route.query.lessonId as any,
      lessonId: null as any, // 课程id
      lessonCoursewareId: "",
      // detailList: [], // 搜索来的所有数据
      detail: null as any,
      refLevelList: [] as any, // 课堂类型
      knowledgePointList: [] as any,
      itemList: [] as any,
      showHead: true,
      // isCourse: false,
      isRecordPlay: false,
      videoRefs: {},
      videoState: 'init' as 'init' | 'play',
      videoItemRef: null as any,
      animationState: 'start' as 'start' | 'end',
      disableScreenRecordingFlag: '0' // disable recording
    });
    const activeData = reactive({
      isAutoPlay: true, // 是否自动播放
      nowTime: 0,
      model: true, // 遮罩
      isAnimation: true, // 是否动画
      videoBtns: true, // 视频
      currentTime: 0,
      duration: 0,
      timer: null as any,
      item: null as any
    });
    // 获取缓存路径
    const getCacheFilePath = async (material: any) => {
      const res = await promisefiyPostMessage({
        api: 'getCourseFilePath',
        content: {
          url: material.content,
          localPath: '',
          materialId: material.materialId,
          updateTime: material.updateTime,
          type: material.typeCode // SONG VIDEO IMAGE
        }
      });
      // console.log('缓存路径返回', res)
      return res;
    };
    const getTempList = async (materialList: any, name: any) => {
      const list: any = [];
      // const browserInfo = browser();
      for (let j = 0; j < materialList.length; j++) {
        const material = materialList[j];
        //请求本地缓存
        // if (browserInfo.isApp && ['VIDEO', 'IMG'].includes(material.typeCode)) {
        //   const localData: any = await getCacheFilePath(material);

        //   if (localData?.content?.localPath) {
        //     material.url = material.content;
        //     material.content = localData.content.localPath;
        //   }
        // }

        material.iframeRef = null;
        material.videoEle = null;
        material.tabName = name;
        material.autoPlay = false; //加载完成是否自动播放
        material.isprepare = false; // 视频是否加载完成
        material.isRender = false; // 是否渲染了

        list.push(material);

        // list.push({
        //   ...material,
        //   iframeRef: null,
        //   videoEle: null,
        //   tabName: name,
        //   autoPlay: false, //加载完成是否自动播放
        //   isprepare: false, // 视频是否加载完成
        //   isRender: false // 是否渲染了
        // });
      }
      return list;
    };
    const getItemList = async (type?: string) => {
      const list: any = [];

      for (let i = 0; i < data.knowledgePointList.length; i++) {
        const item = data.knowledgePointList[i];
        if (item.materialList && item.materialList.length > 0) {
          const tempList = await getTempList(item.materialList, item.name);
          list.push(...tempList);
        }

        // 第二层级
        if (item.children && item.children.length > 0) {
          const childrenList = item.children || [];
          for (let j = 0; j < childrenList.length; j++) {
            const childItem = childrenList[j];
            const tempList = await getTempList(
              childItem.materialList,
              childItem.name
            );
            list.push(...tempList);
          }
        }
      }

      // console.log(list, 'list')
      if(!type) {
        let _firstIndex = list.findIndex(
          (n: any) =>
            n.knowledgePointMaterialRelationId == route.query.kId ||
            n.materialId == route.query.kId
        );
        _firstIndex = _firstIndex > -1 ? _firstIndex : 0;
        const item = list[_firstIndex];

        // console.log(_firstIndex, '_firstIndex', route.query.kId, 'route.query.kId', item)
        // 是否自动播放
        if (activeData.isAutoPlay) {
          item.autoPlay = true;
        }
        popupData.activeIndex = _firstIndex;
        popupData.playIndex = _firstIndex;
        popupData.tabName = item.tabName;
        popupData.tabActive = item.knowledgePointId;
        popupData.itemActive = item.id;
        popupData.itemName = item.name;
      }

      nextTick(() => {
        data.itemList = list;
        getCurrentItemCatch(popupData.activeIndex) // 获取当前元素的缓存
        checkedAnimation(popupData.activeIndex);
        postMessage({
          api: 'courseLoading',
          content: {
            show: false,
            type: 'fullscreen'
          }
        });

        if (data.disableScreenRecordingFlag === '1') {
          // 检测是否录屏
          handleLimitScreenRecord();
        }
        setTimeout(() => {
          data.animationState = 'end';
        }, 500);
      });
    };

    /** 获取当前元素的缓存 */
    const getCurrentItemCatch = async (index: number) => {
      const item = data.itemList[index]
      if (browserInfo.isApp && ['VIDEO', 'IMG'].includes(item.typeCode) && !item.isReadCatch) {
        const localData: any = await getCacheFilePath(item)
        item.isReadCatch = true
        if (localData?.content?.localPath) {
          item.url = item.content
          item.content = localData.content.localPath
        }
        console.log('加载了缓存')
      }
    }

    const getDetail = async (type = "", id?: any) => {
      try {
        const res: any = await request.get(
          state.platformApi +
            `/lessonCourseware/getLessonCourseDetail/${id || route.query.id}`,
          {
            hideLoading: true
          }
        );
        const result = res.data || {}
        result.lessonTargetDesc = result.lessonTargetDesc ? result.lessonTargetDesc.replace(/\n/g, "<br />") : ""
        data.detail = result;
        data.lessonId = result.lessonCoursewareId
        data.lessonCoursewareId = result.lessonCoursewareId
        if (res?.data?.lockFlag) {
          postMessage({
            api: 'courseLoading',
            content: {
              show: false,
              type: 'fullscreen'
            }
          });
          showDialog({
            title: '温馨提示',
            message: '课件已锁定'
          }).then(() => {
            goBack();
          });
          return;
        }
        if (Array.isArray(res?.data?.knowledgePointList)) {
          let index = 0;
          data.knowledgePointList = res.data.knowledgePointList.map(
            (n: any) => {
              if (Array.isArray(n.materialList)) {
                n.materialList = n.materialList.map((item: any) => {
                  index++;
                  const materialRefs = item.materialRefs
                    ? item.materialRefs
                    : [];
                  const materialMusicId =
                    materialRefs.length > 0
                      ? materialRefs[0].resourceIdStr
                      : null;
                  const useStatus = materialRefs.length > 0
                  ? materialRefs[0]?.extend?.useStatus : null
                  const isLock = useStatus === 'LOCK' && state.platformType === "STUDENT" ? true : false
                  return {
                    ...item,
                    isLock,
                    materialMusicId,
                    content: item.content,
                    knowledgePointId: [item.knowledgePointId],
                    materialId: item.id,
                    id: index + ''
                  };
                });
              }
              if (Array.isArray(n.children)) {
                n.children = n.children.map((cn: any) => {
                  cn.materialList = cn.materialList.map((item: any) => {
                    index++;
                    const materialRefs = item.materialRefs
                      ? item.materialRefs
                      : [];
                    const materialMusicId =
                      materialRefs.length > 0
                        ? materialRefs[0].resourceIdStr
                        : null;
                    const useStatus = materialRefs.length > 0
                    ? materialRefs[0]?.extend?.useStatus : null
                    const isLock = useStatus === 'LOCK' && state.platformType === "STUDENT" ? true : false
                    return {
                      ...item,
                      isLock,
                      materialMusicId,
                      content: item.content,
                      knowledgePointId: [n.id, item.knowledgePointId],
                      materialId: item.id,
                      id: index + ''
                    };
                  });
                  return cn;
                });
              }
              return n;
            }
          );
          getItemList(type);
        }
        return true
      } catch (error) {
        console.log(error);
      }
    };



    const getSearchItemList = async (knowledgePointList: any[]) => {
      const list: any = [];

      for (let i = 0; i < knowledgePointList.length; i++) {
        const item = knowledgePointList[i];
        if (item.materialList && item.materialList.length > 0) {
          const tempList = await getTempList(item.materialList, item.name);
          list.push(...tempList);
        }

        // 第二层级
        if (item.children && item.children.length > 0) {
          const childrenList = item.children || [];
          for (let j = 0; j < childrenList.length; j++) {
            const childItem = childrenList[j];
            const tempList = await getTempList(
              childItem.materialList,
              childItem.name
            );
            list.push(...tempList);
          }
        }
      }

      return list
    };


    /** 从搜索页面来的 */
    const getSearchDetail = async (params: { type?: string, id?: any, search?: string }) => {
      data.searchLoading = true
      try {
        const res = await request.get(
          state.platformApi +
            `/lessonCourseware/getLessonCoursewareCourseList/${params.id || route.query.lessonId}`,
          {
            hideLoading: true,
            params: {
              detailFlag: "1",
              search: params.search
            }
          }
        );
        const result = res.data || []
        const allList: any[] = []
        for(let i = 0; i < result.length; i++) {
          const itemResult = result[i];
          itemResult.name = itemResult.coursewareDetailName;
          itemResult.id = itemResult.coursewareDetailId;
          itemResult.lessonTargetDesc = itemResult.lessonTargetDesc ? itemResult.lessonTargetDesc.replace(/\n/g, "<br />") : ""
          if (Array.isArray(itemResult?.knowledgePointList)) {
            let index = 0;
            itemResult.children = itemResult.knowledgePointList.map(
              (n: any) => {
                if (Array.isArray(n.materialList)) {
                  n.materialList = n.materialList.map((item: any) => {
                    index++;
                    const materialRefs = item.materialRefs
                      ? item.materialRefs
                      : [];
                    const materialMusicId =
                      materialRefs.length > 0
                        ? materialRefs[0].resourceIdStr
                        : null;
                    const useStatus = materialRefs.length > 0
                    ? materialRefs[0]?.extend?.useStatus : null
                    const isLock = useStatus === 'LOCK' && state.platformType === "STUDENT" ? true : false
                    return {
                      ...item,
                      isLock,
                      materialMusicId,
                      content: item.content,
                      coursewareDetailId: itemResult.coursewareDetailId,
                      knowledgePointId: [itemResult.coursewareDetailId, item.knowledgePointId],
                      materialId: item.id,
                      id: (i * 1000 + '') + index + ''
                    };
                  });
                }
                if (Array.isArray(n.children)) {
                  n.children = n.children.map((cn: any) => {
                    cn.materialList = cn.materialList.map((item: any) => {
                      index++;
                      const materialRefs = item.materialRefs
                        ? item.materialRefs
                        : [];
                      const materialMusicId =
                        materialRefs.length > 0
                          ? materialRefs[0].resourceIdStr
                          : null;
                      const useStatus = materialRefs.length > 0
                      ? materialRefs[0]?.extend?.useStatus : null
                      const isLock = useStatus === 'LOCK' && state.platformType === "STUDENT" ? true : false
                      return {
                        ...item,
                        isLock,
                        materialMusicId,
                        coursewareDetailId: itemResult.coursewareDetailId,
                        content: item.content,
                        knowledgePointId: [itemResult.coursewareDetailId, n.id, item.knowledgePointId],
                        materialId: item.id,
                        id: (i * 1000 + '') + index + ''
                      };
                    });
                    return cn;
                  });
                }
                return n;
              }
            );
            itemResult.knowledgePointList = null // 去掉不要的
            itemResult.list = await getSearchItemList(itemResult.children);

            allList.push(...itemResult.list)
          }
        }

        // 单独处理不是从搜索来的
        if(data.source !== 'search') {
          if(params.type === "pointSearch") {
            detailTempSearchList.value = result
            popupData.tempTabActive = allList.length > 0 ? allList[0].knowledgePointId : []
            popupData.tempItemActive = "-1"
            data.searchTemp = params.search
            return
          }
          detailList.value = result
          detailTempSearchList.value = result
          return
        }

        if(params.type === 'pointSearch') {
          detailTempSearchList.value = result

          // 初始化选中的数据 临时
          popupData.tempTabActive = allList.length > 0 ? allList[0].knowledgePointId : []
          popupData.tempItemActive = "-1"
          data.searchTemp = params.search
          return
        }
        detailList.value = result
        detailTempSearchList.value = result

        if(!params.type) {
          let _firstIndex = allList.findIndex(
            (n: any) =>
              n.knowledgePointMaterialRelationId == route.query.kId ||
              n.materialId == route.query.kId
          );
          _firstIndex = _firstIndex > -1 ? _firstIndex : 0;
          const item = allList[_firstIndex];
          // console.log(item, 'item')
          // console.log(_firstIndex, '_firstIndex', route.query.kId, 'route.query.kId', item)
          // 是否自动播放
          if (activeData.isAutoPlay) {
            item.autoPlay = true;
          }

          popupData.activeIndex = _firstIndex;
          popupData.playIndex = _firstIndex;
          popupData.tabName = item.tabName;
          popupData.tabActive = item.knowledgePointId;
          popupData.itemActive = item.id;
          popupData.itemName = item.name;
          data.detail = detailList.value?.find((child: any) => child.coursewareDetailId === item.coursewareDetailId)
        }

        nextTick(() => {
          data.itemList = allList;
          getCurrentItemCatch(popupData.activeIndex) // 获取当前元素的缓存
          checkedAnimation(popupData.activeIndex);
          postMessage({
            api: 'courseLoading',
            content: {
              show: false,
              type: 'fullscreen'
            }
          });

          if (data.disableScreenRecordingFlag === '1') {
            // 检测是否录屏
            handleLimitScreenRecord();
          }
          setTimeout(() => {
            data.animationState = 'end';
          }, 500);
        });


        return true
      } catch (error) {
        console.log(error);
      } finally {
        data.searchLoading = false
      }
    }

    const onTitleTip = (type: "phaseGoals" | "checkItem", text: string) => {
      handleStop()
      popupData.pointOpen = true
      popupData.pointContent = text
      if(type === "checkItem") {
        popupData.pointTitle = '检查事项'
      } else if(type === "phaseGoals") {
        popupData.pointTitle = '阶段目标'
      }
    }

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

    // 切换播放
    const togglePlay = (m: any, isPlay: boolean) => {
      if (isPlay) {
        m.videoEle?.play();
      } else {
        m.videoEle?.pause();
      }
    };

    let timers: any = null;
    const checkVideoPlay = () => {
      const activeVideoRef = data.videoItemRef?.getPlyrRef();
      if (activeVideoRef) {
        timers = setInterval(() => {
          if (!activeVideoRef.paused()) {
            activeVideoRef.pause();
            clearInterval(timers);
          }
          activeVideoRef.pause();
        }, 100);
      }

      setTimeout(() => {
        clearInterval(timers);
      }, 3000);
    };
    //录屏时间触发
    const handleLimitScreenRecord = async () => {
      const result = await promisefiyPostMessage({
        api: 'getDeviceStatus',
        content: { type: 'video' }
      });
      const { status } = result?.content || {};
      if (status == '1') {
        data.itemList.forEach((item: any) => (item.autoPlay = false));
        handleStop();
        // 处理事件 - 事件事件后加载的
        checkVideoPlay();
        showDialog({
          title: '温馨提示',
          message: '课件内容请勿录屏',
          beforeClose: () => {
            return new Promise(resolve => {
              promisefiyPostMessage({
                api: 'getDeviceStatus',
                content: { type: 'video' }
              }).then((res: any) => {
                const content = res.content;
                if (content?.status == '1') {
                  const activeItem = data.itemList[popupData.activeIndex];
                  togglePlay(activeItem, false);
                  resolve(false);
                } else {
                  const activeItem = data.itemList[popupData.activeIndex];
                  togglePlay(activeItem, true);
                  resolve(true);
                }
              });
            });
          }
        });
      }
    };

    // 获取支付渠道
    const sysParamConfig = async () => {
      try {
        const res = await request.get(
          state.platformApi + '/sysConfig/queryByParamName',
          {
            params: {
              paramName: 'disable_screen_recording_flag'
            }
          }
        );
        data.disableScreenRecordingFlag = res.data.paranValue || '';
      } catch {
        //
      }
    };

    const getRefLevel = async (id?: any) => {
      try {
        const res = await request.post(state.platformApi + '/lessonCourseware/refLevel', {
          data: {
            lessonCoursewareDetailId: id || route.query.id
          }
        })
        data.refLevelList = res.data || []
        return true
      } catch {
        //
      }
    }

    onMounted(async () => {
      // 键盘唤起  0是顶起 1是覆盖
      postMessage({
        api: 'setSoftInputMode',
        content: {
          type: 1
        }
      });

      isHidden.value = true;
      await sysParamConfig();
      if(data.source === 'search') {
        await getSearchDetail({search: data.search})
      } else {
        await getRefLevel()
        await getDetail();
        data.lessonId && await getSearchDetail({search: data.search, id: data.lessonId})
      }
      isHidden.value = false;
      // getCourseSchedule();
      window.addEventListener('message', iframeHandle);

      if (data.disableScreenRecordingFlag === '1') {
        //禁止录屏 ios
        listenerMessage('setVideoPlayer', result => {
          if (result?.content?.status == 'pause') {
            handleLimitScreenRecord();
          }
        });
        // 安卓
        postMessage({
          api: 'limitScreenRecord',
          content: {
            type: 1
          }
        });
      }
    });

    // const playRef = ref();
    // 返回
    const goBack = () => {
      postMessage({ api: 'back' });
    };

    const popupData = reactive({
      pointOpen: false,
      pointContent: "",
      pointTitle: "",
      coursewareOpen: false,
      open: false,
      activeIndex: 0,
      playIndex: 0,
      tabActive: '',
      tempTabActive: '', // 临时选中
      tempItemActive: "", // 临时编号
      tabName: '',
      itemActive: '',
      itemName: '',
      guideOpen: false,
      toolOpen: false // 工具弹窗控制
    });

    const stopVideo = (el: HTMLVideoElement) => {
      return new Promise(resolve => {
        if (el.paused) return resolve(true);
        el.onpause = () => {
          console.log('暂停');
          resolve(true);
        };
        el.pause();
      });
    };

    /**停止所有的播放 */
    const handleStop = async () => {
      const videos = document.querySelectorAll('video');
      for (let i = 0; i < videos.length; i++) {
        const videoEle = videos[i] as HTMLVideoElement;
        await stopVideo(videoEle);
      }
      // console.log('视频暂停完成');
      data.itemList.forEach((item: any) => {
        if (item.typeCode === 'SONG') {
          item.iframeRef?.contentWindow?.postMessage(
            { api: 'setPlayState' },
            '*'
          );
        }
      });
    };
    // 切换素材
    const toggleMaterial = (itemActive: any) => {
      const index = data.itemList.findIndex((n: any) => n.id == itemActive);
      if (index > -1) {
        handleSwipeChange(index);
      }
    };
    /** 延迟收起模态框 */
    const setModelOpen = () => {
      clearTimeout(activeData.timer);
      closeToast();
      activeData.timer = setTimeout(() => {
        activeData.model = false;
      }, 4000);
    };
    /** 立即收起所有的模态框 */
    // const clearModel = () => {
    //   clearTimeout(activeData.timer);
    //   closeToast();
    //   activeData.model = false;
    // };

    // 双击
    const handleDbClick = () => {
      if (activeVideoItem.value.typeCode === 'VIDEO') {
        const activeVideoRef = data.videoItemRef?.getPlyrRef();
        if (activeVideoRef) {
          if (activeVideoRef.paused()) {
            activeVideoRef.play();
          } else {
            activeVideoRef.pause();
            showToast('已暂停');
          }
        }
      }
    };

    const effectIndex = ref(0);
    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)'
        },
        next: {
          transform: 'translate3d(100%, 0, -800px) rotateY(120deg)'
        }
      },
      // 风车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 acitveTimer = ref();
    // 轮播切换
    const handleSwipeChange = async (index: number) => {
      if(data.source === 'search') {
        const item = data.itemList[index];
        data.detail = detailList.value?.find((child: any) => child.coursewareDetailId === item.coursewareDetailId)
        popupData.tabActive = item.knowledgePointId;
        popupData.itemActive = item.id;
        popupData.itemName = item.name;
        popupData.tabName = item.tabName;
        if (item.typeCode == 'SONG') {
          activeData.model = true;
        }
      }
      // 如果是当前正在播放 或者是视频最后一个
      if (popupData.activeIndex == index) return
      await handleStop();
      data.animationState = 'start';
      data.videoState = 'init';
      clearTimeout(acitveTimer.value);
      checkedAnimation(popupData.activeIndex, index);
      nextTick(() => {
        popupData.activeIndex = index;
        getCurrentItemCatch(index) // 获取当前元素的缓存
        acitveTimer.value = setTimeout(
          () => {
            popupData.playIndex = index;
            const item = data.itemList[index];
            if (item) {
              popupData.tabActive = item.knowledgePointId;
              popupData.itemActive = item.id;
              popupData.itemName = item.name;
              popupData.tabName = item.tabName;
              if (item.typeCode == 'SONG') {
                activeData.model = true;
              }
            }
            requestAnimationFrame(() => {
              const _effectIndex = effectIndex.value + 1;
              effectIndex.value =
                _effectIndex >= effects.length - 1 ? 0 : _effectIndex;

              if (item && item.typeCode === 'VIDEO') {
                // 自动播放下一个视频
                clearTimeout(activeData.timer);
                closeToast();
                item.autoPlay = true;
                data.animationState = 'end';
              }
            });
          },
          activeData.isAnimation ? 850 : 0
        );
      });
    };

    /** 是否有转场动画 */
    const checkedAnimation = (index: number, nextIndex?: number) => {
      nextIndex = nextIndex ? nextIndex : index + 1;
      const item = data.itemList[index];
      const nextItem = data.itemList[nextIndex];
      if (nextItem) {
        if (nextItem.knowledgePointId != item.knowledgePointId) {
          activeData.isAnimation = true;
          return;
        }
        const videoEle = item.videoEle;
        const nextVideo = nextItem.videoEle;
        if (videoEle && videoEle.duration < 8 && index < nextIndex) {
          activeData.isAnimation = false;
        } else if (nextVideo && nextVideo.duration < 8 && index > nextIndex) {
          activeData.isAnimation = false;
        } else {
          activeData.isAnimation = true;
        }
      } else {
        activeData.isAnimation = item?.adviseStudyTimeSecond < 8 ? false : true;
      }
    };

    // 上一个知识点, 下一个知识点
    const handlePreAndNext = (type: string) => {
      if (type === 'up') {
        handleSwipeChange(popupData.activeIndex - 1);
      } else {
        handleSwipeChange(popupData.activeIndex + 1);
      }
    };

    /** 弹窗关闭 */
    const handleClosePopup = () => {
      const item = data.itemList[popupData.activeIndex];
      if (item?.typeCode == 'VIDEO' && !item.videoEle?.paused) {
        setModelOpen();
      }
    };

    const activeVideoItem = computed(() => {
      const item = data.itemList[popupData.activeIndex];
      if (
        item &&
        item.typeCode &&
        item.typeCode.toLocaleUpperCase() === 'VIDEO'
      ) {
        return item;
      }
      return {};
    });
    let closeModelTimer: any = null;

    /**
     * 统计视频播放时间段
     */
    const intervalFnRef = ref(); // 定时任务
    // 播放视频总时长
    const videoIntervalRef = useInterval(1000, { controls: true });
    videoIntervalRef.pause();

    // 保存零时时间
    // const moreTime: any = ref([]) // 多个观看时间段 已经放到列表里面了
    let tempTime: any = []; // 临时存储时间
    const currentTimer = useInterval(1000, { controls: true });
    // 监听播放状态，
    watch(
      () => videoIntervalRef.isActive.value,
      (newVal: boolean) => {
        initVideoCount(newVal);
      }
    );

    // 是否收起
    watch(
      () => activeData.model,
      () => {
        if (activeData.model) {
            isPlay.value = false
        } else {
            isPlay.value = true
            toolOpen.value = false
        }
      }
    )
    // 白板的批注打开时暂停播放
    watch(
      () => [whitePenShow.value, penShow.value],
      () => {
        if (whitePenShow.value || penShow.value) {
          clearTimeout(activeData.timer);
          handleStop()
        }
      }
    )

    /**
     * 初始化视频时长
     * @param newVal 播放状态
     * @param repeat 是否为定时发送的
     */
    const initVideoCount = (newVal: any, repeat = false) => {
      // console.log('watch', forms.player.currentTime)
      const activeVideoRef = data.videoItemRef?.getPlyrRef();
      const initTime = deepClone(tempTime);
      if (repeat) {
        if (tempTime.length > 0) {
          // console.log('join video', tempTime, 'initTime', initTime)
          tempTime[1] = Math.floor(activeVideoRef.currentTime());
        }
      } else {
        if (newVal) {
          tempTime[0] = Math.floor(activeVideoRef.currentTime());
        } else {
          tempTime[1] = Math.floor(activeVideoRef.currentTime());
        }
      }

      if (tempTime.length >= 2) {
        // console.log(tempTime, 'tempTime', moreTime.value)
        // 处理在短时间内的时间差 【视屏拖动，点击可能会导致时间差太大】
        const diffTime =
          tempTime[1] - tempTime[0] - currentTimer.counter.value > 2;
        // 结束时间，如果 大于开始时间则清除
        if (tempTime[1] >= tempTime[0] && !diffTime) {
          data.itemList[popupData.activeIndex].moreTime?.push(tempTime);
          // moreTime.value.push(tempTime)
        }
        if (repeat) {
          tempTime = deepClone(initTime);
        } else {
          tempTime = [];
          currentTimer.counter.value = 0;
        }
      }
    };
    // 更新时间
    const updateStat = async () => {
      try {
        // 只有学生才统计数据
        if (state.platformType === 'STUDENT') {
          const videoTime = videoIntervalRef.counter.value;
          if (videoTime <= 0) return;
          videoIntervalRef.counter.value = 0;
          await request.post(
            `${state.platformApi}/studentCoursewarePlayRecord/save`,
            {
              data: {
                playTime: videoTime
              }
            }
          );
        }
      } catch {
        //
      }
    };

    onMounted(() => {
      if (state.platformType === 'STUDENT') {
        // 间隔多少时间同步数据
        intervalFnRef.value = useIntervalFn(async () => {
          // 同步数据时先进行有效时间进行保存
          // initVideoCount(false, true);

          await updateStat();
        }, 5000);
      }
    });
    /** 统计视频播放时间段 */
    return () => (
      <div id="playContent" class={styles.playContent}>
        <div
          class={styles.coursewarePlay}
          style={{ width: parentContainer.width }}
          onClick={() => {
            clearTimeout(closeModelTimer);
            clearTimeout(activeData.timer);
            closeToast();
            if (Date.now() - activeData.nowTime < 300) {
              handleDbClick();
              return;
            }
            activeData.nowTime = Date.now();
            closeModelTimer = setTimeout(() => {
              activeData.model = !activeData.model;
            }, 300);
          }}>
          <div class={styles.wraps}>
            <div
              style={
                activeVideoItem.value.typeCode &&
                data.animationState === 'end' &&
                data.videoState === 'play'
                  ? {
                      zIndex: 15,
                      opacity: 1
                    }
                  : { opacity: 0, zIndex: -1, pointerEvents: "none" }
              }
              class={styles.itemDiv}>
              <VideoPlay
                ref={(el: any) => (data.videoItemRef = el)}
                item={activeVideoItem.value}
                activeModel={activeData.model}
                onPlay={() => {
                  data.videoState = 'play';
                  data.animationState = 'end';
                  if(whitePenShow.value || penShow.value || popupData.coursewareOpen || popupData.open || popupData.guideOpen || popupData.pointOpen) {
                    handleStop()
                  }
                }}
                onLoadedmetadata={(videoItem: any) => {
                  data.videoState = 'play';
                  activeVideoItem.value.videoEle = videoItem;
                  if (!activeVideoItem.value.isprepare) {
                    activeVideoItem.value.isprepare = true;
                  }
                }}
                onSeeked={() => {
                  videoIntervalRef.isActive.value && videoIntervalRef.pause();
                }}
                onSeeking={() => {
                  videoIntervalRef.isActive.value && videoIntervalRef.pause();
                }}
                onWaiting={() => {
                  videoIntervalRef.isActive.value && videoIntervalRef.pause();
                }}
                onTimeupdate={() => {
                  const activeVideoRef = data.videoItemRef?.getPlyrRef();
                  if (
                    !videoIntervalRef.isActive.value &&
                    activeVideoRef?.currentTime() > 0 &&
                    !activeVideoRef?.paused()
                  ) {
                    videoIntervalRef.resume();
                  }
                }}
                onPause={() => {
                  clearTimeout(activeData.timer);
                  videoIntervalRef.pause();
                }}
                onEnded={async () => {
                  const _index = popupData.activeIndex + 1;
                  if (_index < data.itemList.length) {
                    handleSwipeChange(_index);
                  }
                }}
                onError={() => {
                  // 视屏异常
                  activeVideoItem.value.error = true;
                }}
              />
            </div>
            {data.itemList.map((m: any, mIndex: number) => {
              const isRenderItem = Math.abs(popupData.activeIndex - mIndex) < 2;
              const isRender = Math.abs(popupData.playIndex - mIndex) < 2;
              // 判断是否是当前选中的元素
              const activeEle = popupData.playIndex === mIndex ? true : false;

              return isRenderItem ? (
                <div
                  key={'index' + mIndex}
                  data-id={'data' + mIndex}
                  class={[
                    styles.itemDiv,
                    activeEle && styles.itemActive,
                    activeData.isAnimation && styles.acitveAnimation,
                    isRenderItem ? styles.show : styles.hide
                  ]}
                  style={
                    mIndex < popupData.activeIndex
                      ? effects[effectIndex.value].prev
                      : mIndex > popupData.activeIndex
                      ? effects[effectIndex.value].next
                      : {}
                  }>

                  <Transition name="van-fade">
                    {m.typeCode === 'VIDEO' &&
                      data.animationState !== 'end' &&
                      data.videoState != 'play' && (
                        <div class={styles.loadWrap}>
                          <Vue3Lottie animationData={playLoadData}></Vue3Lottie>
                        </div>
                      )}
                  </Transition>
                  {isRender && m.typeCode === 'IMG' && (
                    <>
                      <img src={m.content} />
                      {m.materialMusicId && (
                        <div
                          class={[
                            styles.goPractice,
                            activeData.model ? '' : styles.hide
                          ]}
                          onClick={(e: any) => {
                            // 去云练习完整版
                            e.stopPropagation();
                            if(m.isLock) {
                              handleShowVip(m.materialMusicId, "MUSIC")
                              return
                            }

                            // const Authorization =
                            //   sessionStorage.getItem('Authorization') || '';
                            const src = `${vaildCurrentUrl()}/gym-music-score/?id=${m.materialMusicId}&isHideMusicList=true&systemType=${ state.platformType === 'TEACHER' ? 'teacher' : 'student'}`
                            postMessage({
                              api: 'openAccompanyWebView',
                              content: {
                                url: src,
                                orientation: 0,
                                c_orientation: 0,
                                isHideTitle: true,
                                statusBarTextColor: false,
                                isOpenLight: true
                              }
                            });
                          }}></div>
                      )}
                    </>
                  )}
                  {isRender && m.typeCode === 'SONG' && (
                    <MusicScore
                      activeModel={activeData.model}
                      data-vid={m.id}
                      music={m}
                      onSetIframe={(el: any) => {
                        m.iframeRef = el;
                      }}
                    />
                  )}
                </div>
              ) : (
                ''
              );
            })}
          </div>

          <Transition name="left">
            {activeData.model && (
              <div class={styles.leftFixedBtns} onClick={(e: Event) => e.stopPropagation()}>
                <div class={[styles.btnsWrap, styles.prePoint]}>
                  {data.source !== 'search' && <div class={styles.fullBtn} onClick={() => {
                    handleStop()
                    popupData.coursewareOpen = true
                  }}>
                    <img src={iconCourseType} />
                  </div>}

                  <div class={styles.fullBtn} onClick={() => {
                    handleStop()
                    data.isSearch = true
                    detailTempSearchList.value = detailList.value
                    popupData.tempItemActive = ""
                    popupData.tempTabActive = ""
                    data.searchTemp = ""
                    // data.searchTemp = JSON.parse(JSON.stringify(data.search))
                    popupData.open = true
                  }}>
                    <img src={iconSearch} />
                  </div>
                  {data.source !== 'search' && <div class={styles.fullBtn} onClick={() => {
                    handleStop()
                    data.isSearch = false
                    popupData.open = true
                  }}>
                    <img src={iconMenu} />
                  </div>}

                  <div
                    class={[styles.fullBtn, !(popupData.activeIndex != 0) && styles.disabled]}
                    onClick={() => {
                      if(popupData.activeIndex != 0) handlePreAndNext('up')
                    }}
                  >
                    <img src={iconUp} />
                    {/* <span style={{ textAlign: 'center' }}>上一个</span> */}
                  </div>
                  <div
                    class={[styles.fullBtn, !(popupData.activeIndex != data.itemList.length - 1) && styles.disabled]}
                    onClick={() => {
                      if(popupData.activeIndex != data.itemList.length - 1) handlePreAndNext('down')
                    }}
                  >
                    {/* <span style={{ textAlign: 'center' }}>下一个</span> */}
                    <img src={iconDown} />
                  </div>
                 </div>
              </div>
            )}
          </Transition>
        </div>

          <div
            style={{ transform: activeData.model ? '' : 'translateY(-100%)' }}
            id="coursePlayHeader"
            class={styles.headerContainer}
            ref={headeRef}
          >
            <div class={styles.backBtn}>
              <Icon name={iconBack} onClick={goBack} />
              <div class={styles.titleSection}>
                <div class={styles.title} onClick={goBack}>{popupData.tabName}</div>
                <div class={styles.titleContent}>
                  <p onClick={goBack}>{data.itemList[popupData.activeIndex]?.name}</p>
                  {data.detail?.lessonTargetDesc ? <span onClick={() => onTitleTip('phaseGoals', data.detail?.lessonTargetDesc)}>阶段目标</span>: ""}
                  {data.itemList[popupData.activeIndex]?.checkItem ? <span onClick={() => onTitleTip('checkItem', data.itemList[popupData.activeIndex]?.checkItem)}>检查事项</span> : ""}
                </div>
              </div>
            </div>

            {state.platformType === 'TEACHER' && (
              <div
                class={styles.headRight}
                onClick={(e: Event) => {
                  e.stopPropagation()
                  clearTimeout(activeData.timer)
                }}
              >
                <div class={styles.rightBtn} onClick={() => {
                  handleStop()
                  popupData.guideOpen = true
                }}>
                  <img src={iconTouping} />
                </div>
              </div>
            )}
          </div>

        <Popup
          class={[styles.popup, styles.popupCoursewarePlay]}
          overlayClass={styles.overlayClass}
          position="right"
          round
          v-model:show={popupData.open}
          onClose={handleClosePopup}>
            {data.isSearch ?
              <PointsSearch
                data={detailTempSearchList.value}
                search={data.searchTemp || data.search}
                loading={data.searchLoading}
                tabActive={popupData.tempTabActive || popupData.tabActive}
                itemActive={popupData.tempItemActive || popupData.itemActive}
                open={popupData.open}
                onHandleSelect={(res: any) => {
                  if(data.source !== "search") {
                    if (browser().isApp) {
                      postMessage({
                        api: 'openWebView',
                        content: {
                          url: `${location.origin}${location.pathname}#/coursewarePlay?lessonId=${data.lessonId}&source=search&kId=${res.materialId}&search=${encodeURIComponent(data.searchTemp ? JSON.parse(JSON.stringify(data.searchTemp)) : '')}`,
                          orientation: 0,
                          isHideTitle: true,
                          statusBarTextColor: false,
                          isOpenLight: true,
                          showLoadingAnim: true
                        }
                      });
                      return
                    } else {
                      router.push({
                        path: '/coursewarePlay',
                        query: {
                          lessonId: data.lessonId,
                          kId: res.materialId,
                          search: data.searchTemp ? JSON.parse(JSON.stringify(data.searchTemp)) : '',
                          source: 'search'
                        }
                      }).then(() => {
                        window.location.reload()
                      });
                      // showToast('请使用App打开')
                      return
                    }
                  }

                  popupData.open = false;
                  if(res.isSearch) {
                    detailList.value = detailTempSearchList.value
                    const tempList: any[] = []
                    detailTempSearchList.value?.forEach((item: any) => {
                      if(Array.isArray(item.list)) {
                        tempList.push(...item.list)
                      }
                    })
                    data.itemList = tempList || []
                    data.search = data.searchTemp ? JSON.parse(JSON.stringify(data.searchTemp)) : ''
                  }
                  toggleMaterial(res.itemActive);
                }}
                onHandleSearch={async (val: any) => {
                  detailTempSearchList.value = []
                  if(data.source === 'search') {
                    await getSearchDetail({
                      type: 'pointSearch',
                      search: val.search
                    })
                  } else {
                    await getSearchDetail({
                      type: 'pointSearch',
                      search: val.search,
                      id: data.lessonId
                    })
                  }
                  data.searchTemp = val.search;
                }} /> :
              <Points
                data={data.knowledgePointList}
                tabActive={popupData.tabActive}
                itemActive={popupData.itemActive}
                onHandleSelect={(res: any) => {
                  popupData.open = false;
                  toggleMaterial(res.itemActive);
                }}
              />}

        </Popup>

        <Popup
          class={[styles.popup, styles.popupCoursewarePlay]}
          overlayClass={styles.overlayClass}
          position="right"
          round
          v-model:show={popupData.coursewareOpen}
          onClose={handleClosePopup}>
            {/* 课件类型 */}
            <CoursewareType list={data.refLevelList} onConfirm={async (item: any) => {
              // 判断是否为当前课程类型
              if(data.currentId === item.id) {
                return
              }

              // 判断当前选择的课程类型是否开通
              if(item.useStatus === "LOCK") {
                handleShowVip(item.lessonCoursewareId, "LESSON")
                return
              }

              const n = await getDetail("", item.id);
              const s = await getRefLevel(item.id);
              data.isSearch = false
              if(n && s) {
                data.currentId = item.id;
                popupData.coursewareOpen = false;
                popupData.activeIndex = 0;
                getCurrentItemCatch(popupData.activeIndex) // 获取当前元素的缓存
                nextTick(() => {
                  popupData.open = true
                })
              } else {
                if(!isOnline.value) {
                  showToast('网络异常')
                }
              }
              data.lessonId && await getSearchDetail({search: data.search, id: data.lessonId})
            }} />
        </Popup>

        <Popup
          class={[styles.popup, styles.popupCoursewarePlay]}
          overlayClass={styles.overlayClass}
          position="right"
          round
          v-model:show={popupData.guideOpen}
          onClose={handleClosePopup}>
          <OGuide />
        </Popup>

        <Popup
          class={[styles.popup, styles.popupPoint]}
          round
          style={{ background: 'transparent !important' }}
          v-model:show={popupData.pointOpen}
          onClose={handleClosePopup}>
          <CoursewareTips onClose={() => {
            popupData.pointOpen = false
          }} content={popupData.pointContent} titleName={popupData.pointTitle} />
        </Popup>

        <GlobalTools />
      </div>
    );
  }
});
