import { onMounted, onBeforeUnmount } from "vue";
import {
  postMessageOk,
  postMessageFail,
} from "@/components/InteractiveVideoEditor/utils/iframePip";

// 检查素材数据的有效性
const checkSourcesData = (list) => {
  if (!Array.isArray(list)) return false;
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    // 需要校验的字段
    const propList = ["id", "name", "url"];
    for (let j = 0; j < propList.length; j++) {
      const key = propList[j];
      if (item[key] === undefined) return false;
    }
  }
  return true;
};

// 监听iframe通讯
const useEditIframeEvent = (pipData, graphData, videoSources, imageSources) => {
  const handleMessage = (e) => {
    if (e.data.source === "InteractiveVideo") {
      console.log("接收到外部调用者的数据", e);
      // 外部传入流程图数据，此时需要更新流程图数据
      if (
        e.data.toolType === "InteractiveVideoUser" &&
        e.data.msgType === "graph_change_data"
      ) {
        if (!e.data.content) {
          postMessageFail("graph_change_data", "数据格式不正确");
          return;
        }
        pipData.value = e.data;
        graphData.value = e.data.content || {};
      }
      // 外部传入视频素材数据，并更新
      if (
        e.data.toolType === "InteractiveVideoUser" &&
        e.data.msgType === "change_sources_video"
      ) {
        if (!e.data.content || !checkSourcesData(e.data.content)) {
          postMessageFail("change_sources_video", "数据格式不正确");
          return;
        }
        pipData.value = e.data;
        videoSources.value = e.data.content || [];
        postMessageOk("change_sources_video");
      }

      // 外部传入图片素材数据，并更新
      if (
        e.data.toolType === "InteractiveVideoUser" &&
        e.data.msgType === "change_sources_image"
      ) {
        if (!e.data.content || !checkSourcesData(e.data.content)) {
          postMessageFail("change_sources_image", "数据格式不正确");
          return;
        }
        pipData.value = e.data;
        imageSources.value = e.data.content || [];
        postMessageOk("change_sources_image");
      }

      // 外部主动想要获取到流程图数据
      if (
        e.data.toolType === "InteractiveVideoUser" &&
        e.data.msgType === "graph_get_data"
      ) {
        pipData.value = e.data;
      }
    }
  };

  onMounted(() => {
    window.addEventListener("message", handleMessage);
  });

  onBeforeUnmount(() => {
    window.removeEventListener("message", handleMessage);
  });
};

export default useEditIframeEvent;
