<script setup lang="ts">
import { computed, ref, onMounted } from "vue";
import { filePickerType } from "./type";
import type { filePickerPropsType } from "./type";

const emit = defineEmits(["submit", "close"]);
const props = withDefaults(defineProps<filePickerPropsType>(), {
  type: filePickerType.directory,
});
// const rootPath=  'https://file.monkeyking.heiyu.space/#/filepicker'
// const targetOrigin ='https://file.monkeyking.heiyu.space'
const rootPath = computed(() => {
  return `https://file.${props.boxId}.heiyu.space/#/filepicker2`;
});
const targetOrigin = computed(() => {
  return `https://file.${props.boxId}.heiyu.space`;
});
const url = computed(() => {
  const _props = JSON.stringify(props);
  return rootPath.value + `?props=${_props}`;
});
const ifr = ref();

const interval = ref();
window.addEventListener("message", (e) => {
  if (e.data.origin === window.origin) {
    if (e.data.type === "close") {
      emit("close");
    } else if (e.data.type === "submit") {
      emit("submit", e.data.fileList);
    } else if (e.data.type === "init") {
      clearInterval(interval.value);
    }
  }
});
onMounted(() => {
  interval.value = setInterval(() => {
    ifr.value.contentWindow.postMessage(
      {
        type: "init",
      },
      targetOrigin.value
    );
  }, 500);
});
</script>

<template>
  <iframe
    id="iframe"
    ref="ifr"
    style="height: 100%; width: 100%; background: white"
    :src="url"
    frameborder="0"
  ></iframe>
</template>
