import {
  defineComponent,
  onMounted,
  reactive,
  onUnmounted,
  ref,
  Transition,
  computed,
  nextTick
} from 'vue';
import styles from './index.module.less';
import 'plyr/dist/plyr.css';
import MusicScore from './component/musicScore';
import iconMenu from './image/icon-menu.png';
import iconUp from './image/icon-up.png';
import iconDown from './image/icon-down.png';
import iconNote from './image/icon-note.png';
import iconWhiteboard from './image/icon-whiteboard.png';
import iconAssignHomework from './image/icon-assignHomework.png';
import iconClose from './image/icon-close.png';
import iconOverPreivew from './image/icon-over-preview.png';
import { Vue3Lottie } from 'vue3-lottie';
import playLoadData from './datas/data.json';
import Moveable from 'moveable';
import VideoPlay from './component/video-play';
import {
  useMessage,
  NDrawer,
  NDrawerContent,
  NModal,
  NSpace,
  NButton,
  NTooltip,
  NPopover,
  NImage
} from 'naive-ui';
import CardType from '@/components/card-type';
import Pen from './component/tools/pen';
import AudioPay from './component/audio-pay';
import TrainSettings from './model/train-settings';
import { useRoute } from 'vue-router';
import { lessonPreTrainingPage, queryCourseware } from '../prepare-lessons/api';
import Attentguide from '@/custom-plugins/guide-page/attent-guide';
import { vaildUrl } from '/src/utils/urlUtils';
import TimerMeter from '/src/components/timerMeter';
import toneImage from '/src/components/layout/images/toneImage.png';
import toolbox from '/src/components/layout/images/toolbox.png';
import setTimeIcon from '/src/components/layout/images/setTimeIcon.png';
import beatIcon from '/src/components/layout/images/beatIcon.png';
import toneIcon from '/src/components/layout/images/toneIcon.png';
import { px2vw } from '/src/utils';
import PlaceholderTone from '/src/components/layout/modals/placeholderTone';
import { state } from '/src/state';
export type ToolType = 'init' | 'pen' | 'whiteboard';
export type ToolItem = {
  type: ToolType;
  name: string;
  icon: string;
};

export default defineComponent({
  name: 'CoursewarePlay',
  props: {
    type: {
      type: String,
      default: ''
    },
    subjectId: {
      type: [String, Number],
      default: ''
    },
    detailId: {
      type: String,
      default: ''
    },
    classGroupId: {
      type: String,
      default: ''
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const message = useMessage();
    const route = useRoute();
    /** 设置播放容器 16:9 */
    const parentContainer = reactive({
      width: '100vw'
    });
    const setContainer = () => {
      const min = Math.min(screen.width, screen.height);
      const max = Math.max(screen.width, screen.height);
      const width = min * (16 / 9);
      if (width > max) {
        parentContainer.width = '100vw';
        return;
      } else {
        parentContainer.width = width + 'px';
      }
    };
    const handleInit = (type = 0) => {
      //设置容器16:9
      // setContainer();
    };
    handleInit();
    onUnmounted(() => {
      handleInit(1);
    });

    const data = reactive({
      type: 'class' as '' | 'preview' | 'class', // 预览类型
      subjectId: '' as any, // 声部编号
      detailId: '' as any, // 编号 - 章节编号
      classGroupId: '' as any, // 上课时需要 班级编号
      // detail: null,
      knowledgePointList: [] as any,
      itemList: [] as any,
      // showHead: true,
      // isCourse: false,
      // isRecordPlay: false,
      videoRefs: {} as any[],
      audioRefs: {} as any[],
      modelAttendStatus: false, // 布置作业提示弹窗
      modalAttendMessage: '本节课未设置课后训练，是否继续？',
      modelTrainStatus: false, // 训练设置
      homeworkStatus: true, // 布置作业完成时
      removeVisiable: false,
      removeTitle: '',
      removeContent: ''
    });
    const activeData = reactive({
      // isAutoPlay: false, // 是否自动播放
      nowTime: 0,
      model: true, // 遮罩
      isAnimation: true, // 是否动画
      // videoBtns: true, // 视频
      // currentTime: 0,
      // duration: 0,
      timer: null as any,
      item: null as any
    });
    const showGuide = ref(false);
    const getDetail = async () => {
      try {
        const res = await queryCourseware({
          coursewareDetailKnowledgeId: data.detailId,
          subjectId: data.subjectId,
          pag: 1,
          rows: 99
        });
        const tempRows = res.data.rows || [];
        const temp: any = [];
        tempRows.forEach((row: any) => {
          if (!row.removeFlag) {
            temp.push({
              id: row.id,
              materialId: row.materialId,
              coverImg: row.coverImg,
              type: row.materialType,
              title: row.materialName,
              isCollect: !!row.favoriteFlag,
              isSelected: row.source === 'PLATFORM' ? true : false,
              content: row.content
            });
          }
        });

        data.knowledgePointList = temp;
        data.itemList = data.knowledgePointList.map((m: any) => {
          return {
            ...m,
            iframeRef: null,
            videoEle: null,
            audioEle: null,
            autoPlay: false, //加载完成是否自动播放
            isprepare: false, // 视频是否加载完成
            isRender: false // 是否渲染了
          };
        });
        setTimeout(() => {
          showGuide.value = true;
        }, 500);
      } catch {
        //
      }
    };

    const directionType = ref('left');
    const showModalBeat = ref(false);
    const showModalTone = ref(false);
    const showModalTime = ref(false);

    const isDragIng = ref(false);
    const initMoveable = async () => {
      if (document.querySelector('.wrap')) {
        const moveable = new Moveable(document.querySelector('.wrap') as any, {
          target: document.querySelector('#moveNPopover') as any,
          // If the container is null, the position is fixed. (default: parentElement(document.body))
          container: document.querySelector('.wrap') as any,
          // snappable: true,
          // bounds: {"left":100,"top":100,"right":100,"bottom":100},
          draggable: true,
          resizable: false,
          scalable: false,
          rotatable: false,
          warpable: false,
          pinchable: false, // ["resizable", "scalable", "rotatable"]
          origin: false,
          keepRatio: false,
          // Resize, Scale Events at edges.
          edge: false,
          throttleDrag: 0,
          throttleResize: 0,
          throttleScale: 0,
          throttleRotate: 0
        });
        moveable
          // .on('dragStart', ({ target, clientX, clientY }) => {
          //   console.log('dragStart');
          // })
          .on(
            'drag',
            ({
              target,
              // transform,
              left,
              top,
              right,
              bottom
              // beforeDelta,
              // beforeDist,
              // delta,
              // dist,
              // clientX,
              // clientY
            }) => {
              isDragIng.value = true;
              const subdEl = document.getElementById(
                `moveNPopover`
              ) as HTMLDivElement;
              // console.log(subdEl, "subdEl", "drag");
              const subdElStyle = getComputedStyle(subdEl, null);
              const RectInfo = {
                left: Number(subdElStyle.left.replace('px', '')),
                top: Number(subdElStyle.top.replace('px', '')),
                width: Number(subdElStyle.width.replace('px', '')),
                height: Number(subdElStyle.height.replace('px', ''))
              };

              const mainWidth =
                parseInt(
                  window.getComputedStyle(
                    document.querySelector('.wrap') as Element
                  ).width
                ) - RectInfo.width;

              const mainHeight =
                parseInt(
                  window.getComputedStyle(
                    document.querySelector('.wrap') as Element
                  ).height
                ) - RectInfo.height;

              if (left < 0) {
                left = 2;
              }
              if (top < 0) {
                top = 2;
              }
              if (right < 0) {
                right = 2;
              }
              if (bottom < 0) {
                bottom = 2;
              }
              if (left > mainWidth - 2) {
                left = mainWidth - 2;
              }
              if (top > mainHeight - 2) {
                top = mainHeight - 2;
              }

              target!.style.left = `${left}px`;
              target!.style.top = `${top}px`;
            }
          )
          .on(
            'dragEnd',
            async ({
              // target, isDrag,
              clientX
              // clientY
            }) => {
              if (document.body.clientWidth / 2 - clientX > 0) {
                // 往左出
                directionType.value = 'right';
              } else {
                // 往又出
                directionType.value = 'left';
              }
              isDragIng.value = false;
            }
          );
      }
    };

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

    onMounted(() => {
      const query = route.query;
      // 先取参数，
      data.type = props.type || (query.type as any);
      data.subjectId = props.subjectId || query.subjectId;
      data.detailId = props.detailId || query.detailId;
      data.classGroupId = props.classGroupId || query.classGroupId;
      initMoveable();
      window.addEventListener('message', iframeHandle);
      getDetail();
    });

    const onFullScreen = () => {
      if (data.type === 'preview') {
        const el: any = document.querySelector('#app');

        if (el.mozRequestFullScreen) {
          el.mozRequestFullScreen();
        } else if (el.webkitRequestFullscreen) {
          el.webkitRequestFullscreen();
        } else if (el.requestFullScreen) {
          el.requestFullscreen();
        }
      }
    };

    const popupData = reactive({
      open: false,
      activeIndex: 0,
      toolOpen: false // 工具弹窗控制
    });

    const activeName = computed(() => {
      let name = '';
      data.knowledgePointList.forEach((item: any, index: number) => {
        if (popupData.activeIndex === index) {
          name = item.title;
        }
      });
      return name;
    });

    /**停止所有的播放 */
    const handleStop = () => {
      for (let i = 0; i < data.itemList.length; i++) {
        const activeItem = data.itemList[i];
        if (activeItem.type === 'VIDEO' && activeItem.videoEle) {
          activeItem.videoEle.currentTime(0);
          activeItem.videoEle.pause();
        }

        if (activeItem.type === 'SONG' && activeItem.audioEle) {
          activeItem.audioEle.stop();
        }
        // console.log('🚀 ~ activeItem:', activeItem)
        // 停止曲谱的播放
        if (activeItem.type === 'MUSIC') {
          activeItem.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);
      message.destroyAll();
      activeData.timer = setTimeout(() => {
        activeData.model = false;
        Object.values(data.videoRefs).map((n: any) =>
          n.toggleHideControl(false)
        );

        Object.values(data.audioRefs).map((n: any) =>
          n.toggleHideControl(false)
        );
      }, 4000);
    };

    /** 立即收起所有的模态框 */
    const clearModel = () => {
      clearTimeout(activeData.timer);
      message.destroyAll();
      activeData.model = false;
      Object.values(data.videoRefs).map((n: any) =>
        n?.toggleHideControl(false)
      );
      Object.values(data.audioRefs).map((n: any) =>
        n?.toggleHideControl(false)
      );
    };
    const toggleModel = (type = true) => {
      activeData.model = type;
      Object.values(data.videoRefs).map((n: any) => n?.toggleHideControl(type));
      Object.values(data.audioRefs).map((n: any) => n?.toggleHideControl(type));
    };

    // 双击
    const handleDbClick = (item: any) => {
      if (item && item.type === 'VIDEO') {
        const videoEle: HTMLVideoElement = item.videoEle;
        if (videoEle) {
          if (videoEle.paused) {
            message.destroyAll();
            videoEle.play();
          } else {
            message.warning('已暂停');
            videoEle.pause();
          }
        }
      }
    };

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

    // const showIndex = ref(-4);
    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)'
        },
        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 = (index: number) => {
      // 如果是当前正在播放 或者是视频最后一个
      if (popupData.activeIndex == index) return;
      handleStop();
      clearTimeout(acitveTimer.value);
      checkedAnimation(popupData.activeIndex, index);
      popupData.activeIndex = index;

      acitveTimer.value = setTimeout(
        () => {
          const item = data.itemList[index];
          if (item) {
            if (item.type == 'MUSIC') {
              activeData.model = true;
            }
            if (item.type === 'SONG') {
              // 自动播放下一个音频
              clearTimeout(activeData.timer);
              message.destroyAll();
              // item.autoPlay = false;
              // nextTick(() => {
              //   item.audioEle?.onPlay();
              // });
            }
            if (item.type === 'VIDEO') {
              // 自动播放下一个视频
              clearTimeout(activeData.timer);
              message.destroyAll();
              nextTick(() => {
                if (item.error) {
                  console.log(item, 'item error');
                  item.videoEle?.src(item.content);
                  item.error = false;
                  //   item.videoEle?.onPlay();
                }
              });
              // item.autoPlay = false;
            }
          }
          //   requestAnimationFrame(() => {
          //     const _effectIndex = effectIndex.value + 1;
          //     effectIndex.value =
          //       _effectIndex >= effects.length - 1 ? 0 : _effectIndex;
          //   });
        },
        activeData.isAnimation ? 800 : 0
      );
    };

    /** 是否有转场动画 */
    const checkedAnimation = (index: number, nextIndex?: number) => {
      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?.type == 'VIDEO' && !item.videoEle?.paused) {
        setModelOpen();
      }

      if (item?.type == 'SONG' && !item.audioEle?.paused) {
        setModelOpen();
      }
    };

    // 监听页面键盘事件 - 上下切换
    document.body.addEventListener('keyup', (e: KeyboardEvent) => {
      // console.log(e, 'e');
      if (e.code === 'ArrowUp') {
        if (popupData.activeIndex === 0) return;
        handlePreAndNext('up');
      } else if (e.code === 'ArrowDown') {
        if (popupData.activeIndex === data.itemList.length - 1) return;
        handlePreAndNext('down');
      }
      //  else if (e.code === 'Space') {
      //   handleStop();
      // }
    });

    /** 教学数据 */
    const studyData = reactive({
      type: '' as ToolType,
      penShow: false,
      whiteboardShow: false
    });

    /** 打开教学工具 */
    const openStudyTool = (item: ToolItem) => {
      const activeItem = data.itemList[popupData.activeIndex];
      // 暂停视频和曲谱的播放
      if (activeItem.type === 'VIDEO' && activeItem.videoEle) {
        activeItem.videoEle.pause();
      }
      if (activeItem.type === 'SONG' && activeItem.audioEle) {
        activeItem.audioEle.stop();
      }
      if (activeItem.type === 'MUSIC') {
        activeItem.iframeRef?.contentWindow?.postMessage(
          { api: 'setPlayState' },
          '*'
        );
      }
      clearModel();
      popupData.toolOpen = false;
      studyData.type = item.type;

      switch (item.type) {
        case 'pen':
          studyData.penShow = true;
          break;
        case 'whiteboard':
          studyData.whiteboardShow = true;
      }
    };

    /** 关闭教学工具 */
    const closeStudyTool = () => {
      studyData.type = 'init';
      toggleModel();
    };

    const startShowModal = (val: 'setTimeIcon' | 'beatIcon' | 'toneIcon') => {
      if (val == 'setTimeIcon') {
        showModalTime.value = true;
      }
      if (val == 'beatIcon') {
        showModalBeat.value = true;
      }
      if (val == 'toneIcon') {
        showModalTone.value = true;
      }
    };

    return () => (
      <div id="playContent" class={[styles.playContent, 'wrap']}>
        <div
          onClick={() => {
            clearTimeout(activeData.timer);
            activeData.model = !activeData.model;
            Object.values(data.videoRefs).map((n: any) =>
              n.toggleHideControl(activeData.model)
            );
            Object.values(data.audioRefs).map((n: any) =>
              n.toggleHideControl(activeData.model)
            );
          }}>
          <div
            class={styles.coursewarePlay}
            style={{ width: parentContainer.width }}
            onClick={(e: Event) => {
              e.stopPropagation();
              setModelOpen();
            }}>
            <div class={styles.wraps}>
              {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) => {
                      e.stopPropagation();
                      clearTimeout(activeData.timer);
                      if (Date.now() - activeData.nowTime < 300) {
                        handleDbClick(m);
                        return;
                      }
                      activeData.nowTime = Date.now();
                      activeData.timer = setTimeout(() => {
                        activeData.model = !activeData.model;
                        Object.values(data.videoRefs).map((n: any) =>
                          n.toggleHideControl(activeData.model)
                        );
                        Object.values(data.audioRefs).map((n: any) =>
                          n.toggleHideControl(activeData.model)
                        );
                        if (activeData.model) {
                          setModelOpen();
                        }
                      }, 300);
                    }}>
                    {m.type === 'VIDEO' ? (
                      <>
                        <VideoPlay
                          ref={(v: any) => (data.videoRefs[mIndex] = v)}
                          item={m}
                          isEmtry={isEmtry}
                          onLoadedmetadata={(videoItem: any) => {
                            m.videoEle = videoItem;
                            m.isprepare = true;
                          }}
                          onTogglePlay={(paused: boolean) => {
                            m.autoPlay = false;
                            if (paused || popupData.open) {
                              clearTimeout(activeData.timer);
                            } else {
                              setModelOpen();
                            }
                          }}
                          onReset={() => {
                            if (!m.videoEle?.paused) {
                              setModelOpen();
                            }
                          }}
                          onError={() => {
                            console.log('video error');
                            m.error = true;
                          }}
                        />
                        <Transition name="van-fade">
                          {!m.isprepare && (
                            <div class={styles.loadWrap}>
                              <Vue3Lottie
                                animationData={playLoadData}></Vue3Lottie>
                            </div>
                          )}
                        </Transition>
                      </>
                    ) : m.type === 'IMG' ? (
                      <img src={m.content} />
                    ) : m.type === 'SONG' ? (
                      <AudioPay
                        item={m}
                        ref={(v: any) => (data.audioRefs[mIndex] = v)}
                        onLoadedmetadata={(audioItem: any) => {
                          m.audioEle = audioItem;
                          m.isprepare = true;
                        }}
                        onTogglePlay={(paused: boolean) => {
                          m.autoPlay = false;
                          if (paused || popupData.open) {
                            clearTimeout(activeData.timer);
                          } else {
                            setModelOpen();
                          }
                        }}
                        onEnded={() => {
                          const _index = popupData.activeIndex + 1;
                          if (_index < data.itemList.length) {
                            handleSwipeChange(_index);
                          }
                        }}
                        onReset={() => {
                          if (!m.audioEle?.paused) {
                            setModelOpen();
                          }
                        }}
                      />
                    ) : (
                      <MusicScore
                        activeModel={activeData.model}
                        data-vid={m.id}
                        music={m}
                        onSetIframe={(el: any) => {
                          m.iframeRef = el;
                        }}
                      />
                    )}
                  </div>
                ) : null;
              })}
            </div>
            <Transition name="right">
              {activeData.model && (
                <div
                  class={styles.rightFixedBtns}
                  onClick={(e: Event) => {
                    e.stopPropagation();
                    clearTimeout(activeData.timer);
                  }}>
                  <div
                    class={[
                      styles.fullBtn,
                      popupData.activeIndex === 0 ? styles.btnsDisabled : ''
                    ]}
                    onClick={() => {
                      if (popupData.activeIndex === 0) return;
                      handlePreAndNext('up');
                    }}>
                    <img src={iconUp} />
                  </div>
                  <div id="attent-0">
                    <div
                      class={[styles.fullBtn, styles.point]}
                      onClick={() => (popupData.open = true)}>
                      <img src={iconMenu} />
                    </div>

                    <div
                      class={[
                        styles.fullBtn,
                        popupData.activeIndex === data.itemList.length - 1
                          ? styles.btnsDisabled
                          : ''
                      ]}
                      onClick={() => {
                        if (popupData.activeIndex === data.itemList.length - 1)
                          return;
                        handlePreAndNext('down');
                      }}>
                      <img src={iconDown} />
                    </div>
                  </div>
                </div>
              )}
            </Transition>
          </div>
        </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}>{activeName.value}</div>
        </div>
        {/* 布置作业按钮 */}

        {data.type !== 'preview' ? (
          <div
            class={[
              styles.assignHomeworkClose,
              activeData.model ? '' : styles.sectionAnimateUp
            ]}
            onClick={async () => {
              data.removeVisiable = true;
              data.removeTitle = '结束课程';
              data.removeContent = '请确认是否结束课程？';
            }}>
            <img src={iconClose} />
          </div>
        ) : (
          ''
        )}
        <div
          id="attent-3"
          class={[
            styles.assignHomework,
            data.type !== 'preview' ? styles.isClose : '',
            activeData.model ? '' : styles.sectionAnimateUp
          ]}
          onClick={async () => {
            if (data.type === 'preview') {
              handleStop();

              data.removeVisiable = true;
              data.removeTitle = '结束预览';
              data.removeContent = '请确认是否结束预览？';

              // onFullScreen();
            } else {
              const res = await lessonPreTrainingPage({
                coursewareKnowledgeDetailId: data.detailId,
                subjectId: data.subjectId,
                page: 1,
                rows: 99
              });
              console.log(res, 'res');
              if (res.data.rows && res.data.rows.length) {
                data.modalAttendMessage = '本节课已设置课后训练，是否布置？';
              }
              data.modelAttendStatus = true;
            }
          }}>
          <img
            src={data.type === 'preview' ? iconOverPreivew : iconAssignHomework}
          />
        </div>

        {/* 白板 批注 */}
        <div
          class={[
            styles.switchDisplaySection,
            activeData.model ? '' : styles.sectionAnimate
          ]}>
          <NTooltip trigger="hover">
            {{
              trigger: () => (
                <div
                  id="attent-1"
                  class={styles.displayBtn}
                  onClick={() =>
                    openStudyTool({
                      type: 'pen',
                      icon: iconNote,
                      name: '批注'
                    })
                  }>
                  <img src={iconNote} />
                </div>
              ),
              default: () => '批注'
            }}
          </NTooltip>
          <NTooltip trigger="hover">
            {{
              trigger: () => (
                <div
                  id="attent-2"
                  class={styles.displayBtn}
                  onClick={() =>
                    openStudyTool({
                      type: 'whiteboard',
                      icon: iconWhiteboard,
                      name: '白板'
                    })
                  }>
                  <img src={iconWhiteboard} />
                </div>
              ),
              default: () => '白板'
            }}
          </NTooltip>
        </div>

        {/* 显示列表 */}
        <NDrawer
          v-model:show={popupData.open}
          class={styles.drawerContainer}
          onAfterLeave={handleClosePopup}
          showMask={false}>
          <NDrawerContent title="资源列表" closable>
            {data.knowledgePointList.map((item: any, index: number) => (
              <CardType
                item={item}
                isActive={popupData.activeIndex === index}
                isCollect={false}
                isShowCollect={false}
                onClick={(item: any) => {
                  popupData.open = false;
                  toggleMaterial(item.id);
                }}
              />
            ))}
          </NDrawerContent>
        </NDrawer>

        {/* 批注 */}
        {studyData.penShow && (
          <Pen
            show={studyData.type === 'pen'}
            type={studyData.type}
            close={() => closeStudyTool()}
          />
        )}

        {studyData.whiteboardShow && (
          <Pen
            show={studyData.type === 'whiteboard'}
            type={studyData.type}
            close={() => closeStudyTool()}
          />
        )}

        {/* 布置作业 */}
        <NModal
          transformOrigin="center"
          v-model:show={data.modelAttendStatus}
          preset="card"
          class={styles.attendClassModal}
          title={'课后训练'}>
          <div class={styles.modelAttendContent}>{data.modalAttendMessage}</div>
          <NSpace class={styles.modelAttendBtnGroup}>
            <NButton
              type="default"
              round
              onClick={() => {
                data.modelAttendStatus = false;
                handleStop();
                // if (state.application) {
                //   emit('close');
                // } else {
                //   window.close();
                // }
                data.modelAttendStatus = false;
              }}>
              暂不布置
            </NButton>
            <NButton
              type="primary"
              round
              onClick={() => {
                data.modelTrainStatus = true;
                data.modelAttendStatus = false;
              }}>
              布置
            </NButton>
          </NSpace>
        </NModal>

        {/* 训练设置 */}
        <NModal
          transformOrigin="center"
          v-model:show={data.modelTrainStatus}
          preset="card"
          class={[styles.attendClassModal, styles.trainClassModal]}
          title={'训练设置'}>
          <TrainSettings
            detailId={data.detailId}
            subjectId={data.subjectId}
            classGroupId={data.classGroupId}
            onClose={() => (data.modelTrainStatus = false)}
            onConfirm={() => {
              // 布置完作业之后直接关闭
              // setTimeout(() => {
              //   handleStop();
              //   if (state.application) {
              //     emit('close');
              //   } else {
              //     window.close();
              //   }
              // }, 1000);
              data.modelTrainStatus = false;
            }}
          />
        </NModal>

        {/* <NModal transformOrigin='center'
          v-model:show={data.homeworkStatus}
          preset="card"
          class={[styles.attendClassModal]}
          closable={false}
          maskClosable={false}
          title={' '}>
          <div class={styles.workContainer}>
            <h2>作业布置成功</h2>
            <p>倒</p>
          </div>
        </NModal> */}
        {showGuide.value ? <Attentguide></Attentguide> : null}

        <NPopover
          raw
          trigger="click"
          show-arrow={false}
          style="--n-box-shadow: none;"
          placement={directionType.value as 'left' | 'right'}
          v-slots={{
            trigger: () => (
              // 首页不显示工具箱
              <img
                // src={isDragIng.value ? dragingBoxIcon : toolbox}
                src={toolbox}
                id="moveNPopover"
                style={{
                  display: ['/', '/home'].includes(route.path)
                    ? 'none'
                    : 'block'
                }}
                class={[
                  styles.toolboxImg,
                  'moveNPopover',
                  isDragIng.value ? styles.isDragIng : ''
                ]}
                alt=""
              />
            )
          }}>
          <div class={styles.booxToolWrap}>
            <div
              class={styles.booxToolItem}
              onClick={() => startShowModal('beatIcon')}>
              <img src={beatIcon} alt="" />
              节拍器
            </div>
            <div
              class={styles.booxToolItem}
              onClick={() => startShowModal('toneIcon')}>
              <img src={toneIcon} alt="" />
              调音器
            </div>
            <div
              class={styles.booxToolItem}
              onClick={() => startShowModal('setTimeIcon')}>
              <img src={setTimeIcon} alt="" />
              计时器
            </div>
          </div>
        </NPopover>

        <NModal
          transformOrigin="center"
          class={['modalTitle background']}
          title={'节拍器'}
          preset="card"
          v-model:show={showModalBeat.value}
          style={{ width: '687px' }}>
          <div class={styles.modeWrap}>
            <iframe
              src={`${vaildUrl()}/metronome/?id=${new Date().getTime()}`}
              scrolling="no"
              frameborder="0"
              width="100%"
              height={'650px'}></iframe>
          </div>
        </NModal>

        <NModal
          transformOrigin="center"
          class={['background']}
          v-model:show={showModalTone.value}>
          <div>
            <PlaceholderTone
              onClose={() => {
                showModalTone.value = false;
              }}></PlaceholderTone>
          </div>
        </NModal>
        <NModal
          transformOrigin="center"
          v-model:show={showModalTime.value}
          class={['modalTitle background']}
          title={'计时器'}
          preset="card"
          style={{ width: px2vw(772) }}>
          <div>
            <TimerMeter></TimerMeter>
          </div>
        </NModal>
        <NModal
          transformOrigin="center"
          v-model:show={data.removeVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={data.removeTitle}>
          <div class={styles.studentRemove}>
            <p>{data.removeContent}</p>

            <NSpace class={styles.btnGroupModal} justify="center">
              <NButton
                round
                type="primary"
                onClick={() => {
                  //
                  if (state.application) {

                    document.exitFullscreen
                    ? document.exitFullscreen()
                    : document.mozCancelFullScreen
                    ? document.mozCancelFullScreen()
                    : document.webkitExitFullscreen
                    ? document.webkitExitFullscreen()
                    : ''
                    emit('close');
                  } else {
                    window.close();
                  }
                }}>
                确定
              </NButton>
              <NButton round onClick={() => (data.removeVisiable = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>
      </div>
    );
  }
});
