<template>
  <div class="map-container">
    <PieChart />
    <div id="statistics-grade" ref="gradeRef"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, onUnmounted } from 'vue'
import type { Ref } from 'vue'
import { getSingleModelViewTokenList } from '@/utils/model'
import PieChart from './PieChart/index.vue'

let viewTokenArray: Array<string | null> = []
let viewer3D:any;
let app:any;
const gradeRef:Ref<any> = ref(null)
let observer: ResizeObserver | null = null;

const batchInit = async () => {
  if(window.sessionStorage.getItem('singleModelViewToken')){
    let result = window.sessionStorage.getItem('singleModelViewToken')
    if(result){
      viewTokenArray = result.split(',')
    }
    modelInit(viewTokenArray[0])
  } else {
    await getSingleModelViewTokenList('grade')
    let result = window.sessionStorage.getItem('singleModelViewToken')
    if(result){
      viewTokenArray = result.split(',')
    }
    modelInit(viewTokenArray[0])
  }
}

const modelInit = (token) => {
  let loaderConfig:any = new BimfaceSDKLoaderConfig();
  loaderConfig.viewToken = token;
  BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback);
}

const successCallback = (viewMetaData: any) => {
  if(viewMetaData.viewType == '3DView'){
    // ======= 判断是否为3D模型 =======
    let containerDom = document.getElementById('statistics-grade');
    let webAppConfig = new window.Glodon.Bimface.Application.WebApplication3DConfig();
    // 存放视图的DOM容器
    webAppConfig.domElement = containerDom;
    // 设置全局单位
    webAppConfig.globalUnit =window.Glodon.Bimface.Common.Units.LengthUnits.Millimeter;
    // 创建WebApplication 
    app = new window.Glodon.Bimface.Application.WebApplication3D(webAppConfig);
    // 添加待显示的模型
    viewTokenArray.forEach((viewToken) => {
      app.addView(viewToken)
    })
    // 从WebApplication获取viewer3D对象
    viewer3D = app.getViewer()

    //监听添加view完成的事件
    viewer3D.addEventListener(
     window.window.Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded, // 3D模型加载完毕触发事件
      function(){
        // 自适应屏幕大小
        const mapResizer = () =>{
          if(containerDom){
            viewer3D.resize(
              containerDom.clientWidth,
              containerDom.clientHeight - 5
            )
          }
        }
        observer = new ResizeObserver(mapResizer)
        observer.observe(gradeRef.value)

        // 渲染场景
        viewer3D.render();
      }
    )
  }
}

const failureCallback = async (error:any) => {
  sessionStorage.removeItem('singleModelViewToken')
  await getSingleModelViewTokenList('grade')
}

onMounted(() => {
  batchInit()
})

onUnmounted(() => {
  if(viewer3D){
    viewer3D.destroy()
    viewer3D = null
  }
  if(observer){
    observer.disconnect()
    observer = null
  }
})
</script>

<style scoped lang="scss">
.map-container{
  display: flex;
  flex-direction: column;
  height: calc(100vh - 75px);
  width: 100%;
  #statistics-grade{
    height: 100%;
  }
}
</style>
