<template>
  <div class="map-container">
    <div id="statistics-scene" ref="sceneRef"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, onUnmounted } from 'vue'
import type { Ref } from 'vue'
import { getMultiModelViewTokenList } from '@/utils/model'
import axios from 'axios';

let viewTokenArray:Array<string|null> = []

let app:any;
let viewer3D:any;
let map:any;
const viewAdded = ref(false)
const sceneRef:Ref<any> = ref(null)
let observer: ResizeObserver | null = null;

const batchInit = async () => {
  if(window.sessionStorage.getItem('multiModelViewTokenList')){
    let result = window.sessionStorage.getItem('multiModelViewTokenList')
    if(result){
      viewTokenArray = result.split(',')
    }
    modelInit(viewTokenArray[0])
  } else {
    await getMultiModelViewTokenList()
    let result = window.sessionStorage.getItem('multiModelViewTokenList')
    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) => {
  let containerDom = document.getElementById('statistics-scene');
  // 设置WebApplication3D的配置项
  let webAppConfig = new window.Glodon.Bimface.Application.WebApplication3DConfig();
  // 存放视图的DOM容器
  webAppConfig.domElement = containerDom; 
  // 开启对数深度缓冲
  webAppConfig.enableLogarithmicDepthBuffer = true;

  // 创建WebApplication3D, 用以显示模型
  app = new window.Glodon.Bimface.Application.WebApplication3D(webAppConfig);
  viewTokenArray.forEach((viewToken) => {
    app.addView(viewToken)
  })
  viewer3D = app.getViewer()
  
  // 增加加载完成监听事件
  viewer3D.addEventListener(
   window.window.Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded, // 3D模型加载完毕触发事件
    function(){
      viewAdded.value = false
      // 自适应屏幕大小
      const mapResizer = () =>{
        if(containerDom){
          viewer3D.resize(
            containerDom.clientWidth,
            containerDom.clientHeight - 5
          )
        }
      }
      observer = new ResizeObserver(mapResizer)
      observer.observe(sceneRef.value)

      // 配置地图
      let mapConfig = new window.Glodon.Bimface.Plugins.TileMap.MapConfig(); 
      mapConfig.viewer = viewer3D;
      // 设置模型载入的基点，即模型上某一特征点的世界坐标，可通过鼠标点击事件获取
      mapConfig.basePoint = {
        "x": -85.689088,
        "y": -62.066347
      };
      // 设置模型载入基点所对应的经纬度(WGS84坐标系)
      mapConfig.modelPosition = [121.62844633392, 29.840569498277];
      // 设置模型的旋转弧度值
      mapConfig.modelRotationZ = 0 * Math.PI / 180;
      // 设置模型零零标高对应的高程值, 单位为米
      mapConfig.modelAltitude = 3.0;

      // 构造地图对象
      map = new window.Glodon.Bimface.Plugins.TileMap.Map(mapConfig);
      // 设置地图类型为天地图的影像底图，天地图key可在http://lbs.tianditu.gov.cn/server/MapService.html申请
      let key = '78c0c5a1844ab8a716f09bc9113d909d'
      map.setMapSource({
          url: `http://t0.tianditu.gov.cn/img_w/wmts?tk=${key}`,
          provider: 'Tianditu',
          credit:window.Glodon.Bimface.Common.Credit.Tianditu
      });

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

const failureCallback = async (error:any) => {
  sessionStorage.removeItem('multiModelViewTokenList')
  await getMultiModelViewTokenList()
}

onMounted(() => {
  batchInit()
  axios.get('/data.json').then(res => {
    console.log('res', res)
  })
})

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;
  overflow: hidden;
  height: calc(100vh - 75px);
  width: 100%;
  max-height: 100vh;
  #statistics-scene{
    height: 100%;
    overflow: hidden;
  }
  .bf-viewer3d-credit {
    bottom: 6px;
  }
}
</style>
