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

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

// 声明Viewer及App
let viewer3D: any;
let app: any;
let viewAdded = false;
let modelId = '10000863512342';
let extObjMng: any = null;
let extObjId = null;
const gradeRef:Ref<any> = ref(null)
let observer: ResizeObserver | null = null;
let modelIdList:any = []

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

let map:any;

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

// 初始化显示组件
const modelInit = (token: any) => {
  let loaderConfig:any = new BimfaceSDKLoaderConfig();
  loaderConfig.viewToken = token;
  BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback);
}

function successCallback(viewMetaData?: any) {
  // ======== 判断是否为3D模型 ========
  // if (viewMetaData.viewType == "3DView") {
    // 获取DOM元素
    let dom4Show = document.getElementById('scene');
    let webAppConfig = new window.Glodon.Bimface.Application.WebApplication3DConfig();
    webAppConfig.domElement = dom4Show;
    webAppConfig.Buttons = [];
    webAppConfig.Toolbars = [];
    // 创建WebApplication
    app = new window.Glodon.Bimface.Application.WebApplication3D(webAppConfig);
    // 添加待显示的模型
    viewTokenArray.forEach((viewToken) => {
      app.addView(viewToken)
    });
    // 从WebApplication获取viewer3D对象
    viewer3D = app.getViewer();

    // 监听添加view完成的事件
    viewer3D.addEventListener(window.Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded, function() {
      viewAdded = true;
      //自适应屏幕大小
      const mapResizer = () =>{
        if(dom4Show){
          viewer3D.resize(
            dom4Show.clientWidth,
            dom4Show.clientHeight - 5
          )
        }
      }
      observer = new ResizeObserver(mapResizer)
      observer.observe(gradeRef.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
      });

      // 渲染3D模型
      viewer3D.render();
      setTimeout(() => {
        editModels();
      }, 600);
      
    });
}
let editor: any
//编辑模型
const editModels = () => {
  if (!viewAdded) {
    return;
  }
  // 设置模型编辑器工具条的配置项
  let modelToolbarConfig = new window.Glodon.Bimface.Plugins.ModelEditor.ModelEditorToolbarConfig();
  // modelToolbarConfig.ids = ['10000863513130','10000863512342'];
  modelToolbarConfig.ids = modelIdList;
  // modelToolbarConfig.ids = ['10000863dfad513130','1000086351234daff2'];
  modelToolbarConfig.viewer = viewer3D;
  // 创建模型编辑器工具条
  editor = new window.Glodon.Bimface.Plugins.ModelEditor.ModelEditorToolbar(modelToolbarConfig);
  // 设置编辑器工具条按钮可见性，开启平移、旋转、缩放
  editor.setButtonVisibility({
    translate: true,
    rotate: true,
    scale: true
  });
  // 平移编辑禁用设置，开启沿X、Y、Z轴的平移
  editor.setTranslationController({
    X: true,
    Y: true,
    Z: true
  });

  // 显示编辑工具条
  editor.show();
  closeBtn()
  editPanel()
}

// 取消关闭按钮
const closeBtn = () => {
  const dom: any = document.getElementsByClassName('bf-modeleditor-cancel')
  if (dom.length && dom[0].parentElement) {
    dom[0].parentElement.remove();
  }
}
/**
 * 点击隐藏编辑控件
 */
const editPanel = () => {
  const effectToolbar = document.getElementsByClassName('scene-container')
  if (effectToolbar.length && effectToolbar[0].parentElement) {
    effectToolbar[0].insertAdjacentHTML("beforebegin", '<div class="bf-button bimface-icon gld-bf-edit-24 bf-checked bf-hideEditControl" title="点击隐藏编辑控件"></div>')
    
    const hideEditControlBtn = document.getElementsByClassName('bf-hideEditControl')
    hideEditControlBtn[0].addEventListener('click', () => {
      const visibility = editor.getButtonVisibility().scale;

      editor.setButtonVisibility({
        translate: !visibility,
        rotate: !visibility,
        scale: !visibility
      });
      if (visibility) {
        hideEditControlBtn[0].classList.remove('bf-checked')
        editor.exit()
      } else {
        hideEditControlBtn[0].classList.add('bf-checked');

        let modelToolbarConfig = new window.Glodon.Bimface.Plugins.ModelEditor.ModelEditorToolbarConfig();
        // modelToolbarConfig.ids = ['10000863513130','10000863512342'];
        modelToolbarConfig.ids = modelIdList;
        modelToolbarConfig.viewer = viewer3D;
        // 创建模型编辑器工具条
        editor = new window.Glodon.Bimface.Plugins.ModelEditor.ModelEditorToolbar(modelToolbarConfig);
        editor.show()
        closeBtn()
      }
    })
  }
}

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

onMounted(() => {
  axios.get('/data.json').then(async(res) => {
    let singleModels = res.data.singleModels
    singleModels.forEach((item:any) => {
      modelIdList.push(item.value)
    })
    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;
  overflow: hidden;  
  height: calc(100vh - 75px);
  width: 100%;
  .scene-container {
    height: 100%;
    overflow: hidden;
  }
}
</style>
<style lang="scss">
.gld-bf-edit-24:before {
    content: "\e604";
}
.map-container {
  position: relative;
  .bf-toolbar {
      border: 1px solid #333;
      background-color: rgba(17, 17, 17, 0.88);
  }
  .bf-button.bf-checked {
      padding-bottom: 0;
      border-bottom: none;
      color: #32D3A6;
      border-radius: 2px;
      background-color: rgba(17, 17, 17, 0.88);
  }
  .bf-viewer3d-credit {
    bottom: 6px;
  }
}
.bf-hideEditControl {
  width: 50px;
  height: 51px;
  position: absolute;
  bottom: 15px;
  left: calc(50% - 136px);
  z-index: 11;
  padding-bottom: 0;
  border-bottom: none;
  color: #32D3A6;
  border-radius: 2px;
  background-color: rgba(17, 17, 17, 0.88);
}

</style>