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';

export default defineComponent({
  name: 'pptList',
  props: {
    pptData: {
      type: Object,
      default: () => ({})
    },
    fromType: {
      type: String, // 'PLATFORM' | 'TEACHER' | 'CLASS'
      default: 'TEACHER'
    }
  },
  emits: ['initPPT', 'changeSlideIndex', 'init'],
  setup(props, { emit, expose }) {
    const userStore = useUserStore();
    const iframeRef = ref<HTMLIFrameElement>();
    const src = `${vaildPPTUrl()}/#/pptScreen?id=${
      props.pptData.id
    }&Authorization=${userStore.getToken}&hideFullScreen=true&fromType=${
      props.fromType
    }`;
    // 上一页下一页
    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>
    );
  }
});
