import { onMounted, onUnmounted, watch } from "vue"
import { useSlidesStore } from "@/store"

export const changePageSlideMes = (changePageSlide: (type: "prev" | "next") => void) => {
  const slidesStore = useSlidesStore()

  /** 初始化ppt完成之后给父级传递消息 */
  function pptInitMes() {
    window.parent.postMessage({ type: "initPPT", content: { slidesLen: slidesStore.slides.length } }, "*")
  }
  function handleMessage(event: any) {
    const { type, content } = event.data || {}
    if (type === "changePageSlide") {
      changePageSlide(content)
    }
  }

  pptInitMes()
  watch(
    () => slidesStore.slideIndex,
    () => {
      // 翻页完成之后的事件
      window.parent.postMessage({ type: "changeSlideIndex", content: { slideIndex: slidesStore.slideIndex } }, "*")
    }
  )
  onMounted(() => {
    window.addEventListener("message", handleMessage)
  })
  onUnmounted(() => {
    window.removeEventListener("message", handleMessage)
  })
}
