<template>
  <div class="bim-briefing main-page">
    <div id="bimBriefing">
      <div id="bimBriefingContainer" class="bimBriefingContainer"></div>
    </div>
    <div class="div-left" :class="{ isShow: leftShow, isHide: !leftShow }">
      <transition name="left">
        <div class="data-content" v-show="leftShow">
          <div class="div-row">
            <div class="row-title">
              <svg-icon icon-class="signal"></svg-icon>
              模型结构树
            </div>
            <div class="model-tree scroll">
              <el-tree
                :key="treeKey"
                ref="tree"
                :default-expanded-keys="treeExpendedKeys"
                :props="{
                  children: 'children',
                  label: 'title',
                }"
                node-key="key"
                @check="onCheckTree"
                :data="modelTrees"
                show-checkbox></el-tree>
            </div>
          </div>
        </div>
      </transition>
      <img :src="leftSrc" class="toSafety-fixed-left-img" @click="arrowRetract" id="arrowLeft" />
    </div>

    <div class="div-right" :class="{ isShow: leftShow, isHide: !leftShow }">
      <transition name="right">
        <div class="data-content" v-show="leftShow">
          <div class="div-row r66">
            <div class="row-title">
              <svg-icon icon-class="signal"></svg-icon>
              {{ title }}
            </div>
            <div class="model-properties scroll">
              <template v-if="selectMenu == 7">
                <div class="loading" v-if="propertyLoad == 'start'">
                  {{ attributeInformation }}
                </div>
                <div class="model-property-nav" v-if="propertyLoad == 'end'">
                  <el-radio-group v-model="selPropertyType" size="small" fill="#6cf">
                    <el-radio-button label="att">属性</el-radio-button>
                    <el-radio-button label="type">类型</el-radio-button>
                  </el-radio-group>
                </div>
                <div class="model-property-list" v-if="propertyLoad == 'end'">
                  <div v-for="(item, index) in selPropertyType == 'att' ? propertyAttr : propertyType" :key="index">
                    <div class="group-info">
                      <svg-icon icon-class="info" />
                      <span>{{ item.name }}</span>
                    </div>
                    <table class="model-property-table my-table">
                      <tr v-for="(item2, index) in item.data" :key="index">
                        <th width="50%">{{ item2.propertyName }}</th>
                        <td width="50%">{{ item2.value }}</td>
                      </tr>
                    </table>
                  </div>
                </div>
              </template>
              <template v-if="selectMenu == 1 || selectMenu == 4">
                <div class="info-list">
                  <div v-for="(item, index) in info" :key="index">
                    <div class="group-info">
                      <svg-icon icon-class="info" />
                      <span>{{ item.name }}</span>
                    </div>
                    <table class="model-property-table my-table">
                      <tr v-for="(item2, index2) in item.data" :key="index2 + '-' + index">
                        <th width="50%">{{ item2.name }}</th>
                        <td width="50%">
                          {{ item2.value }}
                          <span v-if="index == 0">米</span>
                          <span v-if="index == 1">米<sup>2</sup></span>
                          <span v-if="index == 2">米<sup>3</sup></span>
                        </td>
                      </tr>
                    </table>
                  </div>
                </div>
              </template>

              <div class="clipping-tip" v-if="showClipping">
                <div class="info-list">
                  <div>
                    <div class="group-info">
                      <svg-icon icon-class="info" />
                      <span>操作指南</span>
                    </div>
                    <table class="clipping-tip-table my-table">
                      <tr>
                        <th>鼠标左键按住剖面框中心箭头线</th>
                      </tr>
                      <tr>
                        <td>拖动可平移剖面框，移出剖面框的部分将被剖切掉</td>
                      </tr>
                      <tr>
                        <th>鼠标左键按住剖面框中心箭头线之间的弧线</th>
                      </tr>
                      <tr>
                        <td>拖动可旋转剖面框，移出剖面框的部分将被剖切掉</td>
                      </tr>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="div-row r33">
            <div class="row-title">
              <svg-icon icon-class="signal"></svg-icon>
              进度信息
            </div>
            <div class="model-progress scroll">
              <table class="model-progress-table my-table">
                <tr>
                  <th>计划开始时间</th>
                  <td>2025-01-02</td>
                </tr>
                <tr>
                  <th>计划结束时间</th>
                  <td>2025-12-31</td>
                </tr>
              </table>
              <div class="group-info">
                <svg-icon icon-class="info" />
                <span>当前进度</span>
              </div>
              <el-progress :text-inside="true" :stroke-width="26" color="#37A685" :percentage="70" />
            </div>
          </div>
        </div>
      </transition>
      <img :src="rightSrc" class="toSafety-fixed-right-img" @click="arrowRetract" id="arrowRight" />
    </div>

    <div class="div-tools">
      <div class="tool-item" :class="{ 'is-selected': selectMenu == 0 }" @click="doSelectMenu(0)">
        <el-tooltip content="默认视点" placement="top">
          <div class="icon">
            <svg-icon icon-class="home" />
          </div>
        </el-tooltip>
      </div>

      <div class="tool-item" :class="{ 'is-selected': selectMenu == 1 }" @click="doSelectMenu(1)">
        <el-tooltip content="构建测量" placement="top">
          <div class="icon">
            <svg-icon icon-class="size2" />
          </div>
        </el-tooltip>
      </div>

      <div class="tool-item" :class="{ 'is-selected': selectMenu == 2 }" @click="doSelectMenu(2)" v-if="1 == 2">
        <el-tooltip content="构建面积" placement="top">
          <div class="icon">
            <svg-icon icon-class="area2" />
          </div>
        </el-tooltip>
      </div>

      <div class="tool-item" :class="{ 'is-selected': selectMenu == 3 }" @click="doSelectMenu(3)" v-if="1 == 2">
        <el-tooltip content="构建体积" placement="top">
          <div class="icon">
            <svg-icon icon-class="volume" />
          </div>
        </el-tooltip>
      </div>

      <div class="tool-item" :class="{ 'is-selected': selectMenu == 4 }" @click="doSelectMenu(4)">
        <el-tooltip content="距离测量" placement="top">
          <div class="icon">
            <svg-icon icon-class="distance" />
          </div>
        </el-tooltip>
      </div>

      <div class="tool-item" :class="{ 'is-selected': selectMenu == 5 }" @click="doSelectMenu(5)">
        <el-tooltip content="剖切" placement="top">
          <div class="icon">
            <svg-icon icon-class="sectioning" />
          </div>
        </el-tooltip>
      </div>

      <div class="tool-item" :class="{ 'is-selected': selectMenu == 6 }" @click="doSelectMenu(6)">
        <el-tooltip content="构建隐藏" placement="top">
          <div class="icon">
            <svg-icon icon-class="hide" />
          </div>
        </el-tooltip>
      </div>

      <div class="tool-item" :class="{ 'is-selected': selectMenu == 7 }" @click="doSelectMenu(7)">
        <el-tooltip content="构建属性" placement="top">
          <div class="icon">
            <svg-icon icon-class="attribute" />
          </div>
        </el-tooltip>
      </div>
    </div>
  </div>
</template>

<script>
import debounce from "lodash.debounce";
import { MergeArray, DelArray } from "@/utils/tools";
import briefingTools from "./bim/briefingTools";
import SvgIcon from "@/components/SvgIcon.vue";
export default {
  components: { SvgIcon },
  name: "BimBriefing",
  data() {
    return {
      dpi: "",
      selProject: null,
      leftSrc: "./bimImages/arrow_left_retract.png",
      rightSrc: "./bimImages/arrow_right_retract.png",
      leftShow: true,
      models: [],
      treeKey: 0,
      modelTrees: [],
      treeExpendedKeys: [],
      selectMenu: 0,
      attributeInformation: "",
      propertyAttr: [],
      propertyType: [],
      selPropertyType: "att",
      propertyLoad: "",
      viewPoint: [],
      info: [],
      title: "属性",
      showClipping: false,
    };
  },
  mounted() {
    this.$store.dispatch("ChangeNav", 702);
    this.dpi = this.$dpi();
    window.addEventListener("resize", () => {
      if (this.dpi != this.$dpi()) {
        this.dpi = this.$dpi();
      }
    });
    this.$bus.$on(
      "projectChange",
      debounce((prj) => {
        this.selProject = prj;
        this.elId++;
        this.initEngine();
      })
    );
    this.selProject = this.$store.getters.selProject;
    this.initEngine();
  },
  methods: {
    doSelectMenu(index) {
      this.selectMenu = index;
      briefingTools.clearEvent(this);
      this.showClipping = false;
      briefingTools.clearSelectFeature(this);
      switch (index) {
        case 0:
          this.resetScene();
          this.title = "主界面";
          break;
        case 1:
          briefingTools.subFeatureSize(this);
          this.title = "构建测量";
          break;
        case 2:
          briefingTools.measurementArea(this);
          this.title = "面积测量";
          break;
        case 3:
          briefingTools.measurementVolume(this);
          break;
        case 4:
          briefingTools.distance(this);
          this.title = "距离测量";
          break;
        case 5:
          briefingTools.initClipping(this);
          this.title = "剖切";
          this.showClipping = true;
          break;
        case 6:
          briefingTools.actorVisible(this);
          this.title = "隐藏";
          break;
        case 7:
          briefingTools.getProperty(this);
          this.title = "属性";
          break;
      }
    },
    onCheckTree(node, event) {
      if (!this.modelLoaded) {
        this.$message.error("模型未加载完成，请稍后重试");
        return;
      }
      this.playCancle();
      let checked = event.checkedNodes.includes(node);
      console.log(node, event, checked);
      if (node.type == "root") {
        //bimBriefingApi
        node.children.forEach((m) => {
          if (bimBriefingApi.m_model.has(m.modelId)) {
            bimBriefingApi.Model.remove(m.modelId);
          }
          if (checked) {
            this.addModel(m.modelId);
          }
        });
      } else if (node.type == "model") {
        if (bimBriefingApi.m_model.has(node.modelId)) {
          bimBriefingApi.Model.remove(node.modelId);
        }
        if (checked) {
          this.addModel(node.modelId);
        }
      } else {
        if (bimBriefingApi.m_model.size == 0) {
          let modelId = checkNode.modelId;
          this.addModel(modelId, () => {
            this.showItem(node, event, checked);
          });
        } else {
          this.showItem(node, event, checked);
        }
      }
    },
    async showItem(checkNode, event, checked) {
      let api = bimBriefingApi;
      api.Model.setVisible(checkNode.modelId, true);
      let externalId = checkNode.externalId;
      if (externalId != 0) {
        if (checked) {
          this.visibleList.push(externalId);
          api.Feature.setVisible(this.visibleList.join("#"), true, checkNode.modelId, false);
        } else {
          this.visibleList = this.visibleList.filter((item) => item !== externalId);
          api.Feature.setVisible(externalId, false, checkNode.modelId);
        }
      } else {
        const res = await this.$api.bim.getTreeAllLeafChild(checkNode.modelId, checkNode.glid);
        let nodes = res.data || [];
        if (nodes.length > 0) {
          if (checked) {
            this.visibleList = MergeArray(nodes, this.visibleList);
            api.Model.setVisible(checkNode.modelId, true);
            api.Feature.setVisible(this.visibleList.join("#"), true, checkNode.modelId, false);
          } else {
            this.visibleList = DelArray(this.visibleList, nodes);
            api.Feature.setVisible(nodes.join("#"), false, checkNode.modelId);
          }
        }
      }
    },
    arrowRetract() {
      if (this.leftShow == true) {
        this.rightSrc = "./images/arrow_right_open.png";
        this.leftSrc = "./images/arrow_left_open.png";
        $("#arrowLeft").animate({ left: 10 + "px" }, 300);
        $("#arrowRight").animate({ right: 10 + "px" }, 300);
      } else {
        this.rightSrc = "./images/arrow_right_retract.png";
        this.leftSrc = "./images/arrow_left_retract.png";

        $("#arrowLeft").animate({ left: 490 + "px" }, 300);
        $("#arrowRight").animate({ right: 490 + "px" }, 300);
      }
      this.leftShow = !this.leftShow;
    },
    initEngine() {
      this.elId++;
      this.modelTrees = [];
      this.models = [];
      this.propertyAttr = [];
      this.propertyType = [];
      this.viewPoint = [];
      this.info = [];
      this.attributeInformation = "";
      setTimeout(() => {
        this.loadEngine();
      }, 10);
    },
    loadEngine() {
      window.bimBriefingApi = new SAPI(
        {
          serverIP: window.config.serverIP, //服务ip地址
          port: window.config.port, //HTTP端口
          useHttps: window.config.useHttps, //使用Https
          container: "bimBriefingContainer", //[必须]容器id
          secretKey: window.config.secretKey,
          openEarth: window.config.openEarth, //[可选]开启Gis场景
          bgColor: window.config.bgColor, //[可选]bim场景背景色, 传值即为纯色天空盒
          tintColor: window.config.tintColor, //[可选]osgb单体化颜色
          sceneTime: window.config.sceneTime, //[可选]分别为当前时间、日出时间、日落时间
          cadMode: window.config.cadMode, // 是否是Cad图纸预览模式
        },
        () => {
          this.initSuccess = true;
          console.log("初始化成功");
          setTimeout(() => {
            this.initLoadModel();
          }, 10);
          let mapOptions = {
            imgs: {
              // 六面图片
              top: "/cdn/bim/sapi/img/top.png",
              bottom: "/cdn/bim/sapi/img/under.png",
              east: "/cdn/bim/sapi/img/east.png",
              south: "/cdn/bim/sapi/img/south.png",
              west: "/cdn/bim/sapi/img/west.png",
              north: "/cdn/bim/sapi/img/north.png",
            },
            offset: {
              // 屏幕坐标偏移
              corner: GLENavigationCube.RightTop,
              x: 25,
              y: 20,
            },
            cube: {
              hoverColor: "#7193dc", // 立方导航快鼠标移过显示颜色
              size: 32, // 导航立方尺寸
              hotPointSize: 7, // 导航立方棱角热点区域尺寸
              cubeTextColor: "#4c4c4ccc", // cube 各个面文字颜色
              cubeStrokeColor: "#374769cc", // cube 各个面边框颜色
              cubeFillColor: "#374769cc", // cube 各个面填充颜色
            },
            zoomRatios: 1, // 缩放倍率
            show: true, // 是否显示
            showAxes: true, // 是否显示XYZ轴线
          };
          bimBriefingApi.Plugin.initNavCube(mapOptions);
        }
      );
    },
    initLoadModel() {
      this.$api.bim
        .listBimModel({
          pageNum: 1,
          pageSize: 100,
          comId: this.selProject.comId,
          projectId: this.selProject.id,
        })
        .then((d) => {
          this.models = d.rows || [];
          if (this.models.length == 0) {
            this.$modal.msgError("暂无模型，请先关联模型");
          } else {
            this.models.forEach((item) => {
              this.addModel(item.lightweightName);
              this.loadModelTree();
              this.doSelectMenu(7);
            });
          }
        });
      this.init();
    },
    init() {},
    loadModelTree() {
      this.modelTrees = [
        {
          title: "项目模型",
          level: 0,
          type: "root",
          key: "root",
          children: [],
          hadLoad: true,
        },
      ];
      this.treeExpendedKeys.push("root");
      this.models
        .map((d) => {
          d.gis = JSON.parse(d.gisJson);
          d.modelId = d.lightweightName;
          return d;
        })
        .forEach((d) => {
          let node = {
            title: d.modelName,
            level: 1,
            type: "model",
            hasLoad: false,
            modelId: d.lightweightName,
            key: d.lightweightName,
            externalId: "0",
            glid: "",
            children: [],
            data: d,
          };
          this.treeExpendedKeys.push(node.key);
          this.modelTrees[0].children.push(node);
          this.getTreeData(node);
        });
      this.showTree = true;
    },
    getTreeData(node) {
      this.$api.bim.modelTreeAllChild(node.modelId, "").then((d) => {
        let objs = d.data || [];
        let makeTree = (tmps) => {
          tmps.forEach((item) => {
            item.children = objs.filter((it) => it.pglid == item.glid);
            if (item.children.length > 0) {
              makeTree(item.children);
            }
            item.hasLoad = true;
            item.title = item.name;
            item.key = item.glid;
            item.modelId = node.modelId;
          });
          return tmps;
        };
        node.children = makeTree(objs.filter((item) => item.level == 0));
        node.children.forEach((item) => {
          //this.treeExpendedKeys.push(item.key)
        });
        this.treeKey++;
      });
    },
    addModel(modelId, cb) {
      let url = `${window.config.modelUrl}/Tools/output/model/${modelId}/root.glt`;
      console.log(modelId, url);
      bimBriefingApi.Model.add(
        url,
        modelId,
        () => {},
        () => {
          cb && cb();
          console.log("加载模型成功");
          setTimeout(() => {
            bimBriefingApi.Camera.getViewPort((p) => {
              this.viewPoint = p;
              this.modelLoaded = true;
            });
          }, 1000);
        }
      );
    },
    resetScene() {
      this.selectedViewpoint = null;
      this.selectedRoam = null;
      bimBriefingApi.Camera.stopImmersiveRoam();
      bimBriefingApi.Model.location(bimBriefingApi.m_model.keys().toArray()[0]);
      bimBriefingApi.Plugin.deleteMiniMap();
      if (this.viewPoint) {
        bimBriefingApi.Camera.setViewPort(this.viewPoint);
      }
    },
  },
};
</script>

<style lang="less">
.bim-briefing {
  height: 100%;
  position: relative;
  #bimBriefing {
    height: 100%;
    #bimBriefingContainer {
      height: 100%;
    }
  }
  .div-left {
    top: 10vh;
    left: 5%;
    position: absolute;
    height: 70vh;
    width: 14%;
    &.isHide {
      left: 0%;
      wdith: 0%;
      #arrowLeft {
        left: 0px !important;
      }
    }
    #arrowLeft {
      top: calc(50% - 50px);
      right: -21px;
      left: unset !important;
    }
    .div-row {
      height: 100%;
    }
  }

  .div-right {
    top: 10vh;
    right: 5%;
    position: absolute;
    height: 70vh;
    width: 14%;
    &.isHide {
      right: 0%;
      width: 0%;
    }
    #arrowRight {
      top: calc(50% - 50px);
      left: -21px;
    }
    .div-row {
      &.r33 {
        height: 180px;
      }
      &.r66 {
        height: calc(100% - 180px);
      }
    }
  }

  .data-content {
    height: 100%;
    .div-row {
      border: solid 1px #75fbfdaa;
      background-color: #06445b81;
      .row-title {
        background: linear-gradient(0deg, #105696, #c0dafb00, #1765ae);
        padding-left: 10px;
        height: 36px;
        line-height: 36px;
        .svg-icon {
          fill: #75fbfd;
        }
      }
    }
  }

  .div-tools {
    position: absolute;
    top: calc(80vh - 50px);
    left: 50%;
    margin-left: -150px;
    display: flex;
    background: #00000080;
    border-radius: 10px;
    .tool-item {
      display: flex;
      flex-flow: column;
      padding: 10px;
      align-items: center;
      cursor: pointer;
      &.is-selected {
        .icon {
          background: #097fca94;
          .svg-icon {
            fill: #75fbfd;
          }
        }
        .sp-text {
          color: #75fbfd;
        }
      }
      .icon {
        width: 30px;
        height: 30px;
        background: #c0c4cca1;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 15px;
        .svg-icon {
          width: 20px;
          height: 20px;
        }
      }
      .sp-text {
        margin-top: 4px;
        font-size: 12px;
      }
    }
  }

  .model-tree {
    height: calc(100% - 36px);
    overflow-y: auto;
    .el-tree {
      background: transparent;
      color: #eee;
      .el-checkbox {
        color: #45fdfe;
      }
      .el-tree-node {
        &:focus {
          & > .el-tree-node__content {
            background: #3489d966;
            &:hover {
              background: #3489d966;
            }
          }
        }
        .el-tree-node__content:hover {
          background: #3489d966;
        }
      }
    }
  }

  .model-properties {
    height: calc(100% - 46px);
    overflow-y: auto;
    padding-bottom: 10px;
    .model-property-nav {
      text-align: left;
      margin: 8px;
    }
    .model-property-list {
      padding: 0px 10px;
    }
    .info-list {
      padding: 10px;
    }
  }
  .model-progress {
    padding: 10px;
    .el-progress-bar {
      .el-progress-bar__innerText {
        color: #fff !important;
      }
    }
  }

  .loading {
    height: 50px;
    margin: 10px;
    line-height: 50px;
    text-align: center;
    color: #edffff85;
  }
  .group-info {
    padding: 4px 0px;
    .svg-icon {
      fill: #45fdfe;
    }
    span {
      font-size: 14px;
    }
  }
  .my-table {
    border-collapse: collapse;
    td,
    th {
      border: solid 1px #0e0f0f88;
      background: #10569688;
      padding: 6px 4px;
      font-size: 12px;
      text-align: left;
    }
    th {
      color: #22d3f4;
    }
  }
  @media (min-width: 2561px) {
    .data-content {
      .div-row {
        &.r33 {
          height: 210px;
        }
        &.r66 {
          height: calc(100% - 210px);
        }
        .row-title {
          height: 48px;
          line-height: 48px;
          font-size: 28px;
        }
      }
    }
    .div-tools {
      margin-left: -300px;
      border-radius: 10px;
      .tool-item {
        padding: 10px 20px;
        .icon {
          width: 60px;
          height: 60px;
          border-radius: 30px;
          .svg-icon {
            width: 40px;
            height: 40px;
          }
        }
        .sp-text {
          margin-top: 10px;
          font-size: 24px;
        }
      }
    }

    .model-tree {
      .el-tree {
        font-size: 24px;
        .el-tree-node__content {
          height: 36px;
        }
        .el-tree-node__expand-icon {
          font-size: 24px;
        }
        .el-checkbox {
          font-size: 24px;
        }
        .el-tree-node__label {
          font-size: 24px;
        }
        .el-tree__empty-text {
          font-size: 24px;
        }
      }
    }

    .group-info {
      .svg-icon {
        width: 30px;
        height: 30px;
      }
      span {
        font-size: 20px;
        position: relative;
        top:-6px;
      }
    }

    .my-table {
      td,
      th {
        font-size: 20px;
      }
    }
  }
}
</style>
