<template>
  <div class='buttons'>
    <button class="button" id="btnDrawAnnotation" @click="drawAnnotation">开始绘制批注</button>
    <button class="button" id="btnRestoreAnnotation" @click="restoreAnnotation">恢复批注</button>
    <button class="button" id="btnAddCompletedEvent" @click="addCompletedEvent">绘制完成事件</button>
    <button class="button" id="btnEnablePick" @click="enablePick">禁用批注选择</button>
    <button class="button" id="btnEnableMove" @click="enableMove">禁止批注移动</button>
    <button class="button" id="btnEnableSnapMode" @click="enableSnapMode">启用捕捉模式</button>
  </div>
  <div id="domId" class="bimface-container" ref="gradeRef"></div>
  <el-drawer v-model="drawer" title="标注结果" :size="300" :close-on-click-modal="false">
    <img v-for="i in imgArr" :src="i" class="img" alt="" />
  </el-drawer>
</template>

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

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

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])
  }
}
function initBimface(token: any) {
  let loaderConfig = new BimfaceSDKLoaderConfig();
  loaderConfig.viewToken = token;
  BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback);
}
onMounted(() => {
  batchInit()
});
onUnmounted(() => {
  // const dom: any = document.getElementsByClassName('img-annotation')
  // const len = dom.length;
  // for (let i = len - 1; i >= 0; i--) {
  //   if (dom[i] != null) {
  //     dom[i].parentNode.removeChild(dom[i]);
  //   }
  // }
  drawer.value = false;
  if(viewer3D){
    viewer3D.destroy()
    viewer3D = null
  }
  imgArr.value = []
  if(observer){
    observer.disconnect()
    observer = null
  }
})
// 加载成功回调函数
function successCallback(viewMetaData: any) {
  let dom4Show = document.getElementById('domId');
  // 设置WebApplication3D的配置项
  let webAppConfig = new window.Glodon.Bimface.Application.WebApplication3DConfig();
    // 配置移动端工具条的参数对象
  webAppConfig.MobileToolbars = ["ModelTree", "MainToolbar"];
  webAppConfig.domElement = dom4Show;
    // 设置全局单位
  webAppConfig.globalUnit =window.Glodon.Bimface.Common.Units.LengthUnits.Millimeter;
  // 创建WebApplication3D，用以显示模型
  app = new window.Glodon.Bimface.Application.WebApplication3D(webAppConfig);
  viewer3D = app.getViewer();
  viewTokenArray.forEach((viewToken) => {
    viewer3D.loadModel({ viewToken: viewToken });
  })
  
  // 监听添加view完成的事件
  viewer3D.addEventListener(window.Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded, function () {
    //自适应屏幕大小
    const mapResizer = () =>{
      if(dom4Show){
        viewer3D.resize(
          dom4Show.clientWidth,
          dom4Show.clientHeight - 5
        )
      }
    }
    observer = new ResizeObserver(mapResizer)
    observer.observe(gradeRef.value)
    // viewAdded = true;
    // 渲染3D模型
    viewer3D.render();
  });
}
// 加载失败回调函数
const failureCallback = async() => {
  sessionStorage.removeItem('singleModelViewTokenList')
  await getSingleModelViewTokenList()
}

// ************************** 批注 **************************
let isDrawAnnotationActivated = false;
let annotationToolbar: any = null;
let annotationState: any = null;
function createAnnotationToolbar() {
  if (!annotationToolbar) {
    // 创建批注工具条的配置
    let config = new window.Glodon.Bimface.Plugins.Annotation.AnnotationToolbarConfig();
    config.viewer = viewer3D;
    // 创建批注工具条
    annotationToolbar = new window.Glodon.Bimface.Plugins.Annotation.AnnotationToolbar(config);
    annotationToolbar.getAnnotationManager().setFillColor(new window.Glodon.Web.Graphics.Color(255, 0, 0, 0.3));

    // 注册批注工具条的监听事件
    annotationToolbar.addEventListener(window.Glodon.Bimface.Plugins.Annotation.AnnotationToolbarEvent.Saved, onAnnotationSaved);
    annotationToolbar.addEventListener(window.Glodon.Bimface.Plugins.Annotation.AnnotationToolbarEvent.Cancelled, eixtAnnotation);
  }
}
const imgArr: any = ref([])
// 保存批注并退出
function onAnnotationSaved() {
  annotationState = annotationToolbar.getAnnotationManager().getCurrentState();
  // 批注导出快照
  annotationToolbar.getAnnotationManager().createSnapshot(function (img: string) {
    // let image = new Image();
    // image.src = img;
    // image.classList.add('img-annotation');
    // document.body.appendChild(image);
    drawer.value = true
    imgArr.value.push(img)
  });
  eixtAnnotation();
}

// 退出批注
function eixtAnnotation() {
  // 显示主工具条
  app.getToolbar("MainToolbar").show();
  annotationToolbar.getAnnotationManager().exit();
  // 批注的激活状态为false
  isDrawAnnotationActivated = false;
}

// 绘制批注
function drawAnnotation() {
  // 创建批注工具条
  createAnnotationToolbar();
  if (!isDrawAnnotationActivated) {
    // 隐藏主工具条
    app.getToolbar("MainToolbar").hide();
    // 显示批注工具条
    annotationToolbar.show();
    // 修改批注的激活状态为true
    isDrawAnnotationActivated = true;
  }
}

// 恢复批注
function restoreAnnotation() {
  if (annotationState != null) {
    // 恢复批注
    annotationToolbar.getAnnotationManager().setState(annotationState);
    // 开始绘制批注
    drawAnnotation();
  } else {
    window.alert("请先绘制并保存批注！");
  }
}

let isPickEnabled = true;
// 禁用批注选择
function enablePick() {
  if (annotationToolbar != null) {
    if (isPickEnabled) {
      // 禁用批注选择
      annotationToolbar.getAnnotationManager().enablePick(false);
      setButtonText("btnEnablePick", "启用批注选择");
    } else {
      // 启用批注选择
      annotationToolbar.getAnnotationManager().enablePick(true);
      setButtonText("btnEnablePick", "禁用批注选择");
    }
    isPickEnabled = !isPickEnabled;
  } else {
    window.alert("请先开始绘制批注！");
  }
}

let isMoveEnabled = true;
// 禁止批注移动
function enableMove() {
  if (annotationToolbar != null) {
    if (isMoveEnabled) {
      // 设置操作模式，"Delete"为删除，"Edit"为编辑内容(仅对文字类型生效)，"Move"为移动，"Rotate"为旋转，"Stretch"为拉伸，[]代表不支持操作，默认全部支持
      annotationToolbar.getAnnotationManager().setOperationMode(["Delete", "Edit", "Rotate", "Stretch"]);
      setButtonText("btnEnableMove", "允许批注移动");
    } else {
      // 允许批注移动
      annotationToolbar.getAnnotationManager().setOperationMode(["Delete", "Edit", "Move", "Rotate", "Stretch"]);
      setButtonText("btnEnableMove", "禁止批注移动");
    }
    isMoveEnabled = !isMoveEnabled;
  } else {
    window.alert("请先开始绘制批注！");
  }
}

// 添加绘制完成事件
function addCompletedEvent() {
  if (annotationToolbar != null) {
    annotationToolbar.getAnnotationManager().itemCompleted(getType);
  } else {
    window.alert("请先开始绘制批注！");
  }
}

// 获取绘制完成的批注类型
function getType(data: any) {
  let type = data.markupType;
  window.alert(type);
}

// ************************** 捕捉模式 **************************
let isSnapModeActivated = false;
function enableSnapMode() {
  // 构造捕捉模式
  let snapMode = new window.window.Glodon.Bimface.Viewer.SnapMode();
  // 设置捕捉对象,三维场景支持的捕捉对象：Endpoint（端点）, Line（线）, Face（面）
  let endpoint =window.window.Glodon.Bimface.Viewer.SnapObject.Endpoint;
  let line =window.window.Glodon.Bimface.Viewer.SnapObject.Line;
  let face =window.window.Glodon.Bimface.Viewer.SnapObject.Face;
  snapMode.setSnap3DList([endpoint, line, face]);
  // 应用捕捉设置
  viewer3D.setSnapMode(snapMode);
  if (!isSnapModeActivated) {
    // 启用捕捉设置
    viewer3D.enableSnap(true);
    setButtonText('btnEnableSnapMode', '关闭捕捉模式');
  } else {
    // 关闭捕捉设置
    viewer3D.enableSnap(false);
    setButtonText('btnEnableSnapMode', '启用捕捉模式');
  }
  isSnapModeActivated = !isSnapModeActivated;
}

// ************************** 按钮文字 **************************
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>

<style lang="scss">
.img-annotation {
  width: 100%;
}
.el-overlay {
  background: initial !important;
  pointer-events: none;
  .el-drawer.rtl {
    height: calc(100% - 134px);
    top: 134px;
    background-color: #000c;
    pointer-events: auto;
  }
  .el-drawer__header {
    color: #fff;
    font-family: 'ROBOTO_BOLD';
    font-size: 18px;
    border-bottom: 1px solid #5c6171;
    margin-bottom: 15px;
    padding: 10px;
  }
  .el-drawer__body {
    padding: 10px;
    overflow: scroll;
    height: 100%;
    &::-webkit-scrollbar{
      display: none;
    }
  }
  .img {
    width: 100%;
    height: 150px;
  }
}
</style>