<template>
  <div class="go-iframe-container" :style="{ width: w + 'px', height: h + 'px' }">
    <iframe ref="iframeRef" class="iframe-content" src="/static/index.html"></iframe>
  </div>
</template>

<script setup lang="ts">
import config, { BarOption } from './config';
import { PropType, toRefs, ref, onMounted, computed, watchEffect } from 'vue'; // 1. 引入 watchEffect
import dataJson from './data.json'

const iframeRef = ref<HTMLIFrameElement | null>(null);
const isIframeReady = ref(false); // 2. 创建一个状态来跟踪 iframe 是否已加载
let iframeApi: any = null;

const props = defineProps({
  chartConfig: {
    type: Object as PropType<config>,
    required: true
  }
})

const { w, h } = toRefs(props.chartConfig.attr)



const BarOptionsData = computed(() => {
  return dataJson.barOptions.map(item =>
    new BarOption(item as unknown as Partial<BarOption>)
  );
});
console.log(BarOptionsData)

onMounted(() => {
  const iframe = iframeRef.value;
  if (iframe) {
    iframe.onload = () => {
      console.log(" Iframe content has loaded!");
      if (iframe.contentWindow && (iframe.contentWindow as any).g) {
        iframeApi = (iframe.contentWindow as any).g.active3d;
        isIframeReady.value = true;
      } else {
        console.error("无法访问 iframe 内的 g.active3d 对象。");
      }
    };
    // 禁止聚焦，免得柱图消失
    setTimeout(() => {
      callIframeMethod("setProvinceFocusable", false)
    }, 3000)
  }
});

// 4. 使用 watchEffect 来处理所有绘图逻辑
// index.vue

watchEffect(() => {
  if (isIframeReady.value && BarOptionsData.value && iframeApi) {
    // console.log(" Drawing chart with new options...");

    // 增加延迟，确保iframe内方法准备就绪
    setTimeout(() => {

      BarOptionsData.value.forEach(barConfig => {
        // console.log(" Drawing bar with config:", barConfig);
        callIframeMethod("createBar", barConfig);
      });
    }, 500); // 500ms延迟，可根据实际情况调整
  }
});


/**
 * 调用 iframe 内部方法的通用函数
 */
function callIframeMethod(methodName: string, ...args: any[]) {
  if (iframeApi && typeof iframeApi[methodName] === 'function') {
    iframeApi[methodName].apply(iframeApi, args);
  } else if (isIframeReady.value) {
    console.error(`方法 ${methodName} 在 iframe API 上不存在。`);
  }
}
</script>

<style lang="scss" scoped>
.go-iframe-container {
  // width: 1300px;
  // height: 900px;
  overflow: hidden;
  // border: 1px solid #ccc;
}

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