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

export const changePageSlideMes = (
  execPrev: () => void,
  execNext: () => void,
  animationIndex: Ref<number>,
  formatedAnimations: ComputedRef<any[]>
) => {
  const slidesStore = useSlidesStore()

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

  pptInitMes()
  watch([() => slidesStore.slideIndex, animationIndex], () => {
    // 翻页完成之后的事件  isAnimationed 动画结束
    window.parent.postMessage(
      {
        type: "changeSlideIndex",
        content: { slideIndex: slidesStore.slideIndex, isAnimationed: animationIndex.value === formatedAnimations.value.length }
      },
      "*"
    )
  })
  onMounted(() => {
    window.addEventListener("message", handleMessage)
  })
  onUnmounted(() => {
    window.removeEventListener("message", handleMessage)
  })
}
