import { defineComponent, ref, onMounted, onUnmounted } from 'vue';
import styles from './pptList.module.less';
import { vaildPPTUrl } from '/src/utils/urlUtils';
import { useUserStore } from '/src/store/modules/users';
import { useRoute } from 'vue-router';

export default defineComponent({
  name: 'pptList',
  props: {
    pptData: {
      type: Object,
      default: () => ({})
    },
    instrumentId: {
      type: String,
      default: ''
    }
  },
  emits: ['initPPT', 'changeSlideIndex', 'init'],
  setup(props, { emit, expose }) {
    const route = useRoute();
    const query = route.query;
    const userStore = useUserStore();
    const iframeRef = ref<HTMLIFrameElement>();
    const src = `${vaildPPTUrl()}/#/pptScreen?id=${
      props.pptData.id
    }&instrumentId=${props.instrumentId}&Authorization=${
      userStore.getToken
    }&hideFullScreen=true&fromType=${
      query.fromType === 'PLATFORM' ? 'PLATFORM' : 'TEACHER'
    }&pptResourcesType=${
      query.fromType === 'PLATFORM' ? 'PLATFORM' : 'TEACHER'
    }`;
    // 上一页下一页
    function handleChangeSlide(type: 'prev' | 'next') {
      iframeRef.value?.contentWindow?.postMessage(
        { type: 'changePageSlide', content: type },
        '*'
      );
    }
    function handleMessage(event: any) {
      const { type, content } = event.data || {};
      console.log(content, 'message');
      if (type === 'initPPT') {
        emit('initPPT', content);
      } else if (type === 'changeSlideIndex') {
        emit('changeSlideIndex', content);
      }
    }
    emit('init');
    onMounted(() => {
      window.addEventListener('message', handleMessage);
    });
    onUnmounted(() => {
      window.removeEventListener('message', handleMessage);
    });
    expose({
      handleChangeSlide
    });
    return () => (
      <div class={styles.pptList}>
        <iframe
          ref={iframeRef}
          class={[styles.container]}
          frameborder="0"
          src={src}></iframe>
      </div>
    );
  }
});
