import { closeToast, Icon, Popup, showDialog, showToast } from 'vant';
import {
  defineComponent,
  onMounted,
  reactive,
  nextTick,
  onUnmounted,
  ref,
  watch,
  Transition
} 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 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 VideoItem from './component/video-item';

export default defineComponent({
  name: 'CoursewarePlay',
  setup() {
    const pageVisibility = usePageVisibility();

    /** 设置播放容器 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 route = useRoute();
    const headeRef = ref();
    const data = reactive({
      knowledgePointList: [] as any,
      itemList: [] as any,
      videoRefs: {} as any[]
    });
    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 getDetail = async () => {
      let courseList: any[] = [];
      if (route.query.tab == 'course') {
        const res = await api_classLessonCoursewareQuery({
          coursewareDetailKnowledgeId: route.query.id,
          page: 1,
          rows: -1
        });
        if (res?.code === 200 && Array.isArray(res.data.rows)) {
          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
            });
          });
        }
      } else {
        const res = await api_lessonCoursewareKnowledgeDetailDetail({
          lessonCoursewareKnowledgeDetailId: route.query.id
        });
        if (res?.code === 200 && Array.isArray(res.data)) {
          courseList = res.data || [];
        }
      }
      // 课程
      if (courseList.length > 0) {
        data.knowledgePointList = courseList.map((item: any) => {
          return {
            ...item,
            url:
              item.type === 'SONG'
                ? 'https://gyt.ks3-cn-beijing.ksyuncs.com/courseware/1687916228530.png'
                : item.coverImg
          };
        });
      }

      data.itemList = data.knowledgePointList.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 // 是否渲染了
        };
      });
    };

    // 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
      }
    };

    onMounted(() => {
      postMessage({
        api: 'courseLoading',
        content: {
          show: false,
          type: 'fullscreen'
        }
      });
      getDetail();
      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: ''
    });

    // 切换素材
    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.model = !activeData.model;
      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 acitveTimer = ref();
    // 轮播切换
    const handleSwipeChange = (index: number) => {
      // 如果是当前正在播放 或者是视频最后一个
      if (popupData.activeIndex == index) return;
      clearTimeout(acitveTimer.value);
      const item = data.itemList[index];
      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();
        }
      }
    };

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

    /** 弹窗关闭 */
    const handleClosePopup = () => {
      setModelOpen();
    };
    return () => (
      <div id="playContent" class={styles.playContent}>
        <div onClick={() => setModelOpen()}>
          <div
            class={styles.coursewarePlay}
            style={{ width: parentContainer.width }}>
            <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) => {
                      if (Date.now() - activeData.nowTime < 300) {
                        handleDbClick(m);
                        return;
                      }
                      activeData.nowTime = Date.now();
                    }}>
                    {m.type === 'IMG' && <img src={m.content} />}
                    {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>
                        )}
                      </Transition>
                    )}
                  </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.open = true)}>
                    <img src={iconMenu} />
                    <span>课件</span>
                  </div>

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

                  <div
                    class={[
                      styles.fullBtn,
                      popupData.activeIndex == data.itemList.length - 1 &&
                        styles.btnsDisabled
                    ]}
                    onClick={() => handlePreAndNext('down')}>
                    <span style={{ textAlign: 'center' }}>下一个</span>
                    <img src={iconDown} />
                  </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}>{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
            data={data.knowledgePointList}
            itemActive={popupData.itemActive}
            onHandleSelect={(res: any) => {
              popupData.open = false;
              toggleMaterial(res.itemActive);
            }}
          />
        </Popup>
      </div>
    );
  }
});
