<script setup lang="ts">
import { onMounted } from 'vue';

import Postmate from 'postmate';

const props = defineProps<{
  accessToken?: string;
  applicationId: number | string;
  fileId: number | string;
  name: string;
  projectId: number | string;
  url: string;
}>();

const initPostmate = async () => {
  const container = document.querySelector('#low-code-adapter');
  if (!container) {
    console.error('容器元素未找到');
    return;
  }

  // 构建包含除 accessToken 外所有参数的 URL
  const buildUrl = () => {
    const baseUrl = props.url || '';
    const urlObj = new URL(
      baseUrl.includes('://') ? baseUrl : `http://dummy${baseUrl}`,
    );

    // 添加其他参数到 URL
    if (props.applicationId)
      urlObj.searchParams.set('applicationId', props.applicationId);
    if (props.fileId) urlObj.searchParams.set('fileId', props.fileId);
    if (props.name) urlObj.searchParams.set('name', props.name);
    if (props.projectId) urlObj.searchParams.set('projectId', props.projectId);

    // 返回构建好的 URL，如果使用了 dummy 前缀则去掉
    return baseUrl.includes('://')
      ? urlObj.toString()
      : urlObj.toString().replace('http://dummy', '');
  };

  const finalUrl = buildUrl();
  console.log('finalUrl', finalUrl);

  const connection = new Postmate({
    classListArray: ['low-code-adapter-iframe'],
    container: document.querySelector('#low-code-adapter'),
    model: {
      accessToken: props.accessToken,
      // 其他参数仍然保留在 model 中，以保持兼容性
      applicationId: props.applicationId,
      fileId: props.fileId,
      name: props.name,
      projectId: props.projectId,
      url: props.url,
    },
    name: 'y-code-renderer',
    url: finalUrl,
  });

  connection.then((ctx) => {
    console.log('ctx', ctx);
    console.log('ctx.parent', ctx.parent);
    console.log('ctx.parent.innerHeight', ctx.parent.innerHeight);
    ctx.frame.style.height = `${ctx.parent.innerHeight - 38 - 88}px`;
    // ctx.frame.style.minHeight = `800px`;
    ctx.frame.style.width = '100%';
    // @ts-ignore 忽略 console
    console.log(`${props.name} 连接成功`, ctx);
    ctx.call('child-connected', {
      name: props.name,
    });
  });
};

onMounted(() => {
  initPostmate();
});
</script>

<template>
  <div id="low-code-adapter"></div>
</template>

<style>
.low-code-adapter-iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style>
