<template>
    <div class="buttons">
      <button class="button" id="btnShowSctBox" @click="showSectionBox">开启剖切盒</button>
      <button class="button" id="btnResetSctBox" @click="resetSectionBox">重置剖切盒</button>
      <button class="button" id="btnFitSctBox" @click="fitToModel">剖切盒自适应</button>
      <button class="button" id="btnGetSctBox" @click="getSectionBoxState">获取剖切盒状态</button>
    </div>
    <div id="domId" class="bimface-container" ref="gradeRef"></div>
</template>

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

let viewTokenArray:Array<string|null> = []
// 声明Viewer及App
let viewer3D: any;
let app: any;
let viewAdded = false;
const gradeRef:Ref<any> = ref(null)
let observer: ResizeObserver | null = null;

const batchInit = async () => {
  if(window.sessionStorage.getItem('singleModelViewTokenList')){
    let result = window.sessionStorage.getItem('singleModelViewTokenList')
    if(result){
      viewTokenArray = result.split(',')
    }
    initBimface(viewTokenArray[0])
  } else {
    await getSingleModelViewTokenList()
    let result = window.sessionStorage.getItem('singleModelViewTokenList')
    if(result){
      viewTokenArray = result.split(',')
    }
    initBimface(viewTokenArray[0])
  }
}
// 配置JSSDK加载项
function initBimface(token: any) {
  let loaderConfig = new BimfaceSDKLoaderConfig();
  loaderConfig.viewToken = token;
  BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback);
}
onMounted(() => {
  batchInit()
});

// 加载成功回调函数
function successCallback(viewMetaData: any) {
  let dom4Show = document.getElementById('domId');
  // 设置WebApplication3D的配置项
  let webAppConfig = new window.Glodon.Bimface.Application.WebApplication3DConfig();
  webAppConfig.domElement = dom4Show;
    // 设置全局单位
  webAppConfig.globalUnit =window.Glodon.Bimface.Common.Units.LengthUnits.Millimeter;
  // 创建WebApplication3D，用以显示模型
  app = new window.Glodon.Bimface.Application.WebApplication3D(webAppConfig);
  viewTokenArray.forEach((viewToken) => {
    app.addView(viewToken)
  })
  viewer3D = app.getViewer();

  // 增加加载完成监听事件
  viewer3D.addEventListener(window.Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded, function () {
    viewAdded = true;
    addCustomTag();
    //自适应屏幕大小
    const mapResizer = () =>{
      if(dom4Show){
        viewer3D.resize(
          dom4Show.clientWidth,
          dom4Show.clientHeight - 5
        )
      }
    }
    observer = new ResizeObserver(mapResizer)
    observer.observe(gradeRef.value)
    // 渲染场景
    viewer3D.render();
  });
}
// 加载失败回调函数
const failureCallback = async() => {
  sessionStorage.removeItem('singleModelViewTokenList')
  await getSingleModelViewTokenList()
}

onUnmounted(() => {
  if(viewer3D){
    viewer3D.destroy()
    viewer3D = null
  }
  if(observer){
    observer.disconnect()
    observer = null
  }
})
// ************************** 自定义标签 **************************
let isAddCustomTagActivated = false;
let cunstomItemContainer: any = null;
let worldPos;
function createCustomItemContainer() {
  if (!cunstomItemContainer) {
    // 创建标签容器配置
    let drawableContainerConfig = new window.Glodon.Bimface.Plugins.Drawable.DrawableContainerConfig();
    // 设置容器配置匹配的对象
    drawableContainerConfig.viewer = viewer3D;
    // 设置标签受剖切功能的影响，即该容器内的标签被剖切后不显示，默认开启该功能
    drawableContainerConfig.affectedBySection = true;
    // 创建标签容器
    cunstomItemContainer = new window.Glodon.Bimface.Plugins.Drawable.DrawableContainer(drawableContainerConfig);
  }
}

function addCustomTag() {
  // 定义标签坐标
  // let tagPosition = {
  //   x: 228.4,
  //   y: -4800.5,
  //   z: 12400
  // }
  // createCustomItemContainer();
  // // 创建CustomItemConfig
  // let config = new window.Glodon.Bimface.Plugins.Drawable.CustomItemConfig();
  // let content = document.createElement('div');
  // // 自定义样式，支持HTML的任意DOM元素
  // // 设置标签的宽度和高度
  // content.style.width = '80px';
  // content.style.height = '32px';
  // // 设置标签样式
  // content.style.border = 'solid';
  // content.style.borderColor = '#FFFFFF';
  // content.style.borderWidth = '2px';
  // content.style.borderRadius = '5%';
  // content.style.background = '#11DAB7';
  // // 设置标签文字内容与样式
  // content.innerText = '检查点';
  // content.style.color = '#FFFFFF';
  // content.style.textAlign = 'center';
  // content.style.lineHeight = '32px';
  // // 设置自定义标签配置
  // config.content = content;
  // config.opacity = 1;
  // config.offsetX = -40;
  // config.offsetY = -32;
  // config.viewer = viewer3D;
  // config.worldPosition = tagPosition;
  // // 创建自定义标签对象
  // let customItem = new window.Glodon.Bimface.Plugins.Drawable.CustomItem(config);
  // // 将自定义标签添加至标签容器内
  // cunstomItemContainer.addItem(customItem)
}

// ************************** 开启 / 关闭剖切盒 **************************
let isSectionBoxActivated = false;
let sectionBox: any = null;
let sectionBoxConfig: any;
function showSectionBox() {
  if (!isSectionBoxActivated) {
    if (!sectionBox) {
      sectionBoxConfig = new window.Glodon.Bimface.Plugins.Section.SectionBoxConfig();
      sectionBoxConfig.viewer = viewer3D;
      sectionBox = new window.Glodon.Bimface.Plugins.Section.SectionBox(sectionBoxConfig);
    } else {
      sectionBox.showBox();
    }
    setButtonText("btnShowSctBox", "关闭剖切盒");
  } else {
    sectionBox.hideBox();
    setButtonText("btnShowSctBox", "开启剖切盒");
  }
  viewer3D.render();
  isSectionBoxActivated = !isSectionBoxActivated;
}

// ************************** 重置剖切盒 **************************
function resetSectionBox () {
  if (!isSectionBoxActivated) {
    showSectionBox();
  }
  sectionBox.reset();
  viewer3D.render();
}

// ************************** 剖切盒适应到模型 **************************
function fitToModel () {
  if (!isSectionBoxActivated) {
    showSectionBox();
  }
  let condition = [
    {
      "categoryId": -2001340
    }, {
      "categoryId": -2001360
    }
  ]
  viewer3D.getModel().hideComponentsByObjectData(condition);
  viewer3D.render();
  sectionBox.fitToModel();
}

// ************************** 获取 / 设置剖切盒状态 **************************
let sectionBoxState: any = null;
function getSectionBoxState() {
  if (!sectionBox) {
    window.alert('请创建剖切盒');
    return;
  }
  if (!sectionBoxState) {
    sectionBoxState = sectionBox.getState();
    setButtonText('btnGetSctBox', '恢复剖切盒状态');
  } else {
    sectionBox.setState(sectionBoxState);
    sectionBoxState = null;
    setButtonText('btnGetSctBox', '获取剖切盒状态');
  }
  viewer3D.render();
}

// ************************** 按钮文字 **************************
function setButtonText(btnId: string, text: string) {
  let dom = document.getElementById(btnId);
  if (dom != null && dom.nodeName == "BUTTON") {
    dom.innerText = text;
  }
}
</script>

<style lang="scss" scoped>
.button {
  margin-right: 8px;
  padding: 8px 15px;
  background: #1d3359;
  color: #fff;
  border: 1px solid #1d3359;
  border-radius: 3px;
  cursor: pointer;
  font-size: 18px;
}
.bimface-container {
  height: calc(100% - 58px);
  margin-top: 12px;
}
.buttons {
  position: relative;
  top: 7px;
  left: 7px;
}
</style>
