<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { useRoute } from 'vue-router';
  import Postmate from 'postmate';
  import { Spin, Alert, Button } from 'ant-design-vue';

  const route = useRoute();
  const MAX_RETRIES = 3;

  const loading = ref(true);
  const errorMessage = ref('');
  const retryCount = ref(0);

  const initPostmate = async () => {
    loading.value = true;
    errorMessage.value = '';
    const container = document.getElementById('low-code-adapter');
    console.log('container', container);
    if (!container) {
      errorMessage.value = '容器元素未找到';
      loading.value = false;
      return;
    }

    const handle = new Postmate({
      container,
      url: route.meta?.app?.url,
      name: 'y-code-renderer',
      classListArray: ['responsive-iframe'],
      model: {
        name: route.meta?.app?.name,
        applicationId: route.meta?.app?.applicationId,
        projectId: route.meta?.app?.projectId,
        fileId: route.meta?.app?.fileId,
        url: route.meta?.app?.url,
      },
    });

    handle
      .then((instance) => {
        console.log('Postmate连接成功', instance);
        retryCount.value = 0; // 重置重试计数器
      })
      .catch((err) => {
        retryCount.value++;
        errorMessage.value = `连接失败: ${err.message}`;
        if (retryCount.value < MAX_RETRIES) {
          initPostmate(); // 自动重试
        } else {
          errorMessage.value = '已达到最大重试次数，请检查网络连接';
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

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

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

    <!-- <div v-if="loading" class="loading-overlay">
      <Spin :tip="`正在连接应用（${retryCount + 1}/${MAX_RETRIES}）`" />
    </div> -->

    <!-- <div v-if="errorMessage" class="error-overlay">
      <Alert type="error" :message="errorMessage" show-icon />
      <Button v-if="retryCount < MAX_RETRIES" @click="initPostmate">重新连接</Button>
    </div> -->
  </div>
</template>

<style>
  .responsive-iframe {
    width: 100%;
    height: 100%;

    border: none;
  }
</style>

<style lang="scss" scoped>
  .iframe-container {
    position: relative;
    height: 100%;
  }

  #low-code-adapter {
    width: 100%;
    height: 100%;
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }

  .error-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1001;
  }
</style>
