<template>
  <el-tabs value="info">
    <el-tab-pane label="概览" name="info">
      <base-info ref="baseInfoPanel" :apiUrls="apiUrls" :currentUnit="currentUnit"></base-info>
    </el-tab-pane>
    <el-tab-pane label="设计" name="design">
      <design ref="designPanel"></design>
    </el-tab-pane>
    <el-tab-pane label="扫码" name="sminfo">
      <sm-info ref="scanPanel"></sm-info>
    </el-tab-pane>
    <el-tab-pane label="质量" name="quality">
      <quality ref="qualityPanel"></quality>
    </el-tab-pane>
    <el-tab-pane label="合同材料" name="contract">
      <contract ref="contractPanel"></contract>
    </el-tab-pane>
    <el-tab-pane label="图纸档案" name="document">
      <dcouments ref="dcoumentPanel"></dcouments>
    </el-tab-pane>
  </el-tabs>
</template>
<script>
import apis from "@/api/PipeUnitInfo";
import BaseInfo from "./BaseInfo.vue";
import Design from "./Design.vue";
import SmInfo from "./SmInfo.vue";
import Quality from "./Quality.vue";
import Contract from "./Contract.vue";
import Dcouments from "./Documents.vue";
import { InfoWindow, createTooltip, CesiumToSuperMap } from "@/utils/mapCommon/tools";
import PipeQueryHelper from '@/utils/mapCommon/PipeQueryHelper';
import $ from 'jquery'
import Config from './config.json'
export default {
  name: "PipeUnitInfo",
  components: {
    BaseInfo,
    Design,
    SmInfo,
    Quality,
    Contract,
    Dcouments,
  },
  data() {
    return {
      pickType: "point", //点选（point）、框选(rect)模式
      clickType: "", //用于点击(click)不缩放情况
      isInteractive: true, //是否与gis场景交互
      locateUnit: null, //用于不合GIS场景交互情况下，查看部件信息{}
      domObj: null,
      infoWindow: null,
      // primitiveCollection: null,
      // pointPrimitiveCollection: null,
      // polylineprimitiveCollection: null,
      toolTip: null,
      selectTarget: null,
      tooltipHandler: null,
      selectPick: null,
      currentUnit:{
        geoType: "",
        code: "",
        prjId: ""
      },
      apiUrls:{
        bjsmidfw: "",
        sjdt: "",
        sjfw: "",
        createPicNode: "/tofly-sxgk/structure/createPicNode",//检查井部件二维码
        createPicPipe: "/tofly-sxgk/structure/createPicPipe",//管道部件二维码
      }
    };
  },
  computed: {
    AppX() {
      return this.$store.getters.AppX;
    },
  },
  watch:{
    locateUnit:{
      handler(n,o){
        this.locateUnit=n;
        if (this.locateUnit) {
          this.infoWindow._handler.setInputAction(function () { },
            Cesium.ScreenSpaceEventType.LEFT_CLICK);
          this.queryForPipeUnitInfoByPBS(
            this.locateUnit.name,
            this.locateUnit.id
          );
        }
      },
      deep:true
    }
  },
  mounted() {
    this.viewer=window.viewer
    this.$store.dispatch('map/changeCurrentTool',this.otherDestroy.bind(this));
    // console.log(Config);
    this.getDirc(() => {
      // this.apiUrls.sjfw = this.AppX.appConfig.gisResource.tiplayers.config["sjfw"].url;
      // this.apiUrls.bjsmidfw = this.AppX.appConfig.gisResource.tiplayers.config["bjsmidfw"].url;
      // this.apiUrls.sjdt = this.AppX.appConfig.gisResource.maps.config["sjdt"].url;
      // if (this.AppX.runtimeConfig.autoRunAdaptor) {
      //   this.AppX.runtimeConfig.autoRunAdaptor.addOperateEvents(
      //     this.excavatename,
      //     this.otherDestroy.bind(this),
      //     this
      //   );
      // }
      this.apiUrls.sjfw = this.AppX.appConfig.gisResource.tiplayers.config["sjfw"].url;
      this.apiUrls.bjsmidfw = this.AppX.appConfig.gisResource.tiplayers.config["bjsmidfw"].url;
      this.apiUrls.sjdt = this.AppX.appConfig.gisResource.maps.config["sjdt"].url;
      this.initInfoWindow();
      if (this.isInteractive) {
        this.infoWindow._setHandler(true);
        if (this.pickType === "point") {
          this.addPointClickEvent();
        } else {
          this.addRectClickEvent();
        }
      } else {
        if (this.locateUnit) {
          this.infoWindow._handler.setInputAction(function () { },
            Cesium.ScreenSpaceEventType.LEFT_CLICK);
          this.queryForPipeUnitInfoByPBS(
            this.locateUnit.name,
            this.locateUnit.id
          );
        }
      }
    });
  },
  methods: {
    /**
     *  点选
     */
    addPointClickEvent() {
      this.toolTip = createTooltip(document.querySelector("#mainMapContainer"));
      const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas);
      this.tooltipHandler = handler;
      handler.setInputAction((e) => {
        const radius = 2;
        const position = this.viewer.scene.pickPosition(e.position);
        const ellpise = new Cesium.Entity({
          position: position,
          ellipse: {
            semiMajorAxis: radius,
            semiMinorAxis: radius,
            material: Cesium.Color.ORANGERED,
            classificationType: Cesium.ClassificationType.TERRAIN
          }
        })
        this.infoWindow.hide();
        const positions = PipeQueryHelper.converCesiumToSuperMapEllipse(ellpise);
        this.queryForPipeUnitInfoByPolygon(positions.positions);


      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      handler.setInputAction((movement) => {
        this.toolTip.showAt(movement.endPosition, '<p>鼠标左键确定缓冲中心,右键单击取消</p>');
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      this.tooltipHandler.setInputAction(function (movement) {
        this.otherDestroy();
      }.bind(this), Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },
    /**
     * 框选查询
     */
    addRectClickEvent() {
      const drawRectHandler = PipeQueryHelper.drawRect(document.querySelector("#mainMapContainer"),this.viewer, (ids) => {
        const leftTopPoint = this.viewer.scene.pickPosition(ids.leftTopPoint);
        const rightBottomPoint = this.viewer.scene.pickPosition(ids.rightBottomPoint);
        const leftBottomPoint = this.viewer.scene.pickPosition(ids.leftBottomPoint);
        const rightTopPoint = this.viewer.scene.pickPosition(ids.rightTopPoint);

        const positions = [leftTopPoint, leftBottomPoint, rightBottomPoint, rightTopPoint];
        this.queryForPipeUnitInfoByPolygon(positions);
      });
      drawRectHandler.activate();
    },
    /**
    * 该方法用于空间查询数据服务
    * @param {Cesium.Cartesian3[]} positions 多边形顶点 
    */
    queryForPipeUnitInfoByPolygon(positions) {
      const geometry = CesiumToSuperMap.convertPolygon(Cesium, SuperMap, { positions: positions });


      const layers = this.viewer.scene.layers;
      const layerList = layers.layerQueue;
      const fieldName = Config.fields;
      const pipeInfo = [];
      const allPipe = PipeQueryHelper.pipe;
      const filters = [];
      layerList.forEach(item => {
        if (!item.visible) return false;
        const pipe = _.find(allPipe, (sjpipe) => {
          const isnode = sjpipe.geometryType === "point" && sjpipe.WELL.indexOf(item.name) > -1;
          const ispipe = sjpipe.geometryType === "line" && item.name === sjpipe.name;
          return (isnode || ispipe) && sjpipe.pipeType === "SJ";
        })
        if (!pipe) return false;
        let unipipeInfo = { dataset: null };
        if (pipe.geometryType === "line") {
          unipipeInfo.dataset = pipe.origindataset;
        } else if (pipe.geometryType === "point" && pipe.WELL.indexOf(item.name) > -1) {
          unipipeInfo.dataset = pipe.origindataset;
        }
        const isExsit = _.find(pipeInfo, (pipeItem) => { return pipeItem.dataset === unipipeInfo.dataset; })
        if (!isExsit) {
          pipeInfo.push(unipipeInfo);
          const filter = unipipeInfo.dataset + "@" + pipe.datasource;
          filters.push(filter);
        }
      })
      if (filters.length === 0) return;
      const onComplete = function (geoResult) {
        if (geoResult.originResult.currentCount === 0) {
          this.$message.warning('当前范围内无管网数据');
          this.infoWindow.hide();
          return;
        }
        this.flashMapService(geoResult.originResult.recordsets, geoResult.originResult.totalCount);
      }.bind(this);
      PipeQueryHelper.queryMapByGeometry({
        url: this.apiUrls.sjdt,
        datasetNames: filters,
        geometry: geometry,
        fields: [fieldName.id, fieldName.pbs, fieldName.pipeID],
        completed: onComplete.bind(this),
        failed: function (err) {
          console.log(err);
        }
      })
      if (!this.primitiveCollection) {
        this.primitiveCollection = new Cesium.PrimitiveCollection();
        this.viewer.scene.primitives.add(this.primitiveCollection);
      }
    },
    /**
     * 该方法用于添加二维管线高亮
     * @param records 
     */
    flashMapService(records, totalCount) {
      //that.pointArrCluster.splice(0,this.pointArrCluster.length);//清空已存在的数据
      if (!records || records.length === 0) return;
      if (!this.primitiveCollection) return;
      const primtCol = this.primitiveCollection;
      primtCol.removeAll();
      this.selectPick=null;
      //fade材质
      let t = 0.0;
      const linefadeMaterial = Cesium.Material.fromType(Cesium.Material.FadeType, {
        repeat: true,
        fadeInColor: Cesium.Color.CYAN,
        fadeOutColor: Cesium.Color.CYAN.withAlpha(0.0),
        time: new Cesium.Cartesian2(0.0, 0.0),
        fadeDirection: {
          x: false,
          y: false,
        }
      });
      //圆
      const EllipsoidFadeSource = "czm_material czm_getMaterial(czm_materialInput materialInput)\n" +
        "{\n" +
        "  czm_material material = czm_getDefaultMaterial(materialInput);\n" +
        "  material.diffuse = 1.5 * color.rgb;\n" +
        "  vec2 st = materialInput.st;\n" +
        "  float dis = distance(st, vec2(0.5, 0.5));\n" +
        "  float per = 1.0;\n" +
        "  if(dis > per * 0.5) {\n" +
        "    material.alpha = 0.3;\n" +
        "    discard;\n" +
        "  }else{\n" +
        "    material.alpha = 0.3;\n" +
        "  }\n" +
        "  return material;\n" +
        "}";
      const circlefadeMaterial = new Cesium.Material({
        fabric: {
          type: "fadeCircle",
          uniforms: {
            color: Cesium.Color.CYAN,
            time: 0.0
          },
          source: EllipsoidFadeSource
        }
      });
      records.forEach(record => {
        if (record.features.length == 0) return false;

        record.features.forEach(feature => {
          const geometry = feature.geometry.points;
          const geotype = feature.geometry.type.toLowerCase().indexOf('line') > -1 ? "LINE" : "POINT";

          if (geotype === "LINE") {
            const pointA = Cesium.Cartesian3.fromDegrees(geometry[0].x, geometry[0].y,200);
            const pointB = Cesium.Cartesian3.fromDegrees(geometry[1].x, geometry[1].y,200);
           
            primtCol.add(this.generaGroundPolyline([pointA, pointB], linefadeMaterial, feature, totalCount === 1));

          } else {
            const pointS = Cesium.Cartesian3.fromDegrees(geometry[0].x, geometry[0].y, 70);
            primtCol.add(this.generaGroundCircle(pointS, 10, circlefadeMaterial, 1.5, feature, totalCount === 1));

          }
        })
      });
      if (primtCol.length === 1) {
        const primitive = primtCol.get(0);
        this.showUniinfoPanel(primitive.geometryInstances.id);

      } else {
        this.clearDrawEvent();
        this.addPrimitiveHandler();
      }
    },
    addPrimitiveHandler() {
      if (this.toolTip) {
        this.toolTip.remove();
        this.toolTip = null;
      }//++
      this.toolTip = createTooltip(document.querySelector("#mainMapContainer"));
      //二维亮圈比例变换
      const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas);
      this.tooltipHandler = handler;
      const that = this;
      handler.setInputAction(function () {
      }, Cesium.ScreenSpaceEventType.WHEEL);
      handler.setInputAction(function (movement) {
        that.removeHightLight(that.selectPick);
        var pick = that.viewer.scene.drillPick(movement.position);
        if (pick.length != 0) {
          that.showSelect(pick, movement);
        } else {
          that.infoWindow.hide();
          that.removePickInfo();

        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      handler.setInputAction(function (movement) {
        that.toolTip.showAt(movement.endPosition, '<p>鼠标左键选择高亮管线,右键单击取消</p>');
      }.bind(this), Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      handler.setInputAction(function (movement) {
        that.otherDestroy();
      }.bind(this), Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },
    /**
     * 
     * @param pick 屏幕点击获取到的对象
     */
    showSelect(pick, position) {
      var that = this;
      // that.parentDom = $("#mainMap .pickUpInfo");
      // if (that.parentDom.length == 0) {
      //   $("#mainMap").append(this.template.split("$$")[1]);
      //   that.parentDom = $("#mainMap .pickUpInfo");
      // } else {
      //   that.parentDom.empty();
      //   that.parentDom.find("span").empty();
      // }
      // if (pick.length > 1) {
      //   that.parentDom.empty();//先清空原有内容
      //   that.parentDom.attr('style', 'left:' + position.position.x + 'px;top:' + position.position.y + 'px;');//根据鼠标点击位置进行显示
      //   that.parentDom.addClass('show');
      //   pick.forEach((item, index) => {
      //     let pickPipeId = pick.primitive.custom[Config.fields.pipeID];
      //     var selectInfo = "<a class='selectInfo' style='width:100%'><span style='visibility:hidden;' id='index'>" + index
      //       + "</span><span id='pid'>" + pickPipeId + "</span><span id='tid'>" + item.id + "</span></a>";
      //     that.parentDom.append(selectInfo)
      //     that.parentDom.find(".selectInfo").on('click', (e) => {
      //       const id = e.currentTarget.lastElementChild.innerHTML;
      //       const index = e.currentTarget.firstElementChild.innerHTML;
      //       this.pickHightLight(pick[index]);
      //       //this.pickSend = pick;
      //       //this.pickIndex = index;
      //       this.showUniinfoPanel(id);
      //       this.removePickInfo();
      //     })
      //   })
      // } else {
      //   //this.pickSend = pick;
      //   //this.pickIndex = 0;
      //   this.pickHightLight(pick[0])
      //   this.showUniinfoPanel(pick[0].id)
      // }
      if(pick.length>0){
        this.pickHightLight(pick[0])
        this.showUniinfoPanel(pick[0].id)
      }
    },
    /**
     * 该方法用于根据pbs编码定位部件位置
     * @param pbs 
     */
    showUniinfoPanel(pbs) {
      const data={
        pbs:pbs
      }
      apis.getPidByPbs(data).then((result) => {
        if (result.data.code !== 1) return;
        let lyName = result.data.result.layerName;
        const code = pbs;
        if (lyName.indexOf(',') > -1) {
          lyName = lyName.split(',')[1];
        }
        else {
          lyName = lyName;
        }
        this.queryForPipeUnitInfoByPBS(lyName, code);
      })
    },
    /**
     * 该方法用于通过iserver接口利用pbs编码查询构件信息
     * @param {string} tableName 数据服务中的三维数据表名
     * @param {string} code 构件pbs编码
     */
    queryForPipeUnitInfoByPBS(tableName, code) {
      const gl = this;
      const queryParameter = Config.queryParameter;
      const datasets = queryParameter.datasets;
      const dataset = _.find(datasets, function (item) {
        return item.layername === tableName;
      });
      if (dataset) {
        const options = {
          url: this.apiUrls.sjfw,
          datasetNames: [queryParameter.dataSource + ":" + dataset.layername],
          whereclause: "CODE='" + code + "'",
          completed: function (result) {
            if (result.result.featureCount > 0) {
              this.clearSelection();//先清除已存在的高亮对象
              //交互式部件查看不需高亮
              if (!gl.isInteractive) {
                this.entitiesHighLight(result, code, dataset.name);
              }//++
              const attrs = result.result.features[0].attributes;
              const condition = attrs.LAYER_NAME.split(",")[0];
              const target = Config.layerInfo;
              //gl.linkViewLocation(result.originResult.features[0]);
              this.setSpaceSelect(target, condition, this.getDircList, attrs);
              const geometry = result.originResult.features[0].geometry;
              const geoType = geometry.type;
              const baseInfo = gl.formPipeAttribs(geoType, attrs);
              //添加部件类型
              let config = Config.pipeUnitInfo;
              config.baseInfo = baseInfo;
              const title = attrs["TYPE"] + ' ' + attrs["PIPE_ID"];
              const pbsCode = attrs["CODE"];
              //if (!gl.isInteractive) {
              gl.location(geometry, ()=> {
                gl.infoWindow.show(title, gl.$el);
                $('.bubblewindow').css('width', 810);
                $('.bubblewindow').css('height', 550);
                gl.initPanle();
              });
              // } else {
              //     gl.infoWindow.show(title, gl.template.split('$$')[0]);
              //     $('.bubblewindow').css('width', 810);
              //     $('.bubblewindow').css('height', 550);
              //     gl.initPanle(config);
              // }
            }
          }.bind(this),
          failed: function (error) {
            console.error(error);
          }
        }
        this.queryByAttribute(options);
      }
    },
    /**
         * 清除拾取对象框
         */
    removePickInfo() {
      this.parentDom = $("#mainMap .pickUpInfo");
      if (this.parentDom.hasClass('show')) {
        this.parentDom.removeClass('show');
      }
      this.parentDom.empty();
    },
    /**
     * 对象高亮
     * @param pick 拾取对象
     * @param index 对象索引值
     */
    pickHightLight(pick) {
      var attributes = pick.primitive.getGeometryInstanceAttributes(pick.id);//获取某个实例的属性集
      attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromBytes(255, 125, 0))//设置其高亮
      this.selectPick = pick;
    },
    /**
     * 清除对象高亮
     * @param pick 
     * @param index 
     */
    removeHightLight(pick) {
      if (pick) {
        var attributes = pick.primitive.getGeometryInstanceAttributes(pick.id);//获取某个实例的属性集
        attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromBytes(0, 255, 255, 100))//设置其初始颜色
      }
    },
    /**
     * 该方法用于初始化信息窗,考虑工程结构树的对外接口
     * 
     */
    initInfoWindow() {
      if (!this.AppX.appConfig.infowindow) {
        this.AppX.appConfig.infowindow = InfoWindow(document.querySelector("#mainMapContainer"), this.viewer);

      }
      this.infoWindow = this.AppX.appConfig.infowindow;
      this.domObj = $(this.infoWindow._div);
      var that = this;
      this.domObj.find('.bubbleclose').off('click').on('click', function () {
        if (that.isInteractive) {
          that.viewer.scene.layers.releaseSelection();
          that.removeHightLight(that.selectPick);
        } else {
          that.clearSelection();
        }
        that.domObj.hide();//++
      })
    },
    /**
     *展示样式初始化，新加了一个id为unitMaterials的dom元素名称与已有元素unitMaterial有点重复
     */
    initPanle() {
      //设计信息初始化
      let sjhtml = "";
      let designInfos = this.currentUnit.geoType === "LINE" ? Config.pipeDesignInfo : Config.pointDesignInfo;
      let simpleInfos = this.currentUnit.geoType === "LINE" ? Config.fieldsInfo.LINE : Config.fieldsInfo.POINT;
      designInfos = replaceUpperCase(designInfos, 1);
      simpleInfos = replaceUpperCase(simpleInfos, 2);
      function replaceUpperCase(obj, type) {
        const result = Object.keys(obj).map(item => {
          return {
            title: type == 1 ? item : obj[item],
            code: type == 1 ? obj[item].replace(/_/g, "").toLowerCase() : item.replace(/_/g, "").toLowerCase(),
          }
        });
        return result;
      }
      const apirequest = this.currentUnit.geoType === "LINE" ? apis.getPipeInfo({ code: this.currentUnit.code }) : apis.getNodeInfo({ code: this.currentUnit.code });
      apirequest.then(res => {
        res=res.data;
        let result = res.result;
        if (res.result.pressureType) {
          let indexInfo = "";
          switch (res.result.pressureType) {
            case "1":
              indexInfo = "待建";
              break;
            case "2":
              indexInfo = "建设中";
              break;
            case "3":
              indexInfo = "完工";
              break;
          }
          if (indexInfo != "") {
            let dom = $('.bubbletitle');
            let title = dom.text();
            //modify by tmx 20210630 统一图层和业务库中部件编码显示
            let arrTitle = title.split(" ");
            if (arrTitle.length > 0) {
              dom.text(arrTitle[0] + " " + (res.result.pipeId ? res.result.pipeId : "") + "(" + indexInfo + ")");
            }
            else {
              dom.text(dom.text() + "(" + indexInfo + ")");
            }
          }
        }
        if (result !== null) {
          result = Object.keys(result).map(item => {
            let temp = item.toLowerCase();
            return {
              compare: temp,
              value: result[item]
            }
          });
          designInfos.forEach(item => {
            result.forEach(el => {
              if (item.code === el.compare) {
                item.value = el.value
              }
            })
          });
          simpleInfos.forEach(item => {
            result.forEach(el => {
              if (item.code === el.compare) {
                if (item.code == "flowdirection") {
                  let value = el.value + "";
                  item.value = (value == "0" ? "起点到终点" : (value == "1" ? "终点到起点" : (value == "2" ? "双向流动" : "/")));
                } else {
                  item.value = el.value;
                }
              }
            })
          });
          //概述信息
          this.$refs.baseInfoPanel.showUnitInfoPage(res.result, simpleInfos);
          //设计信息
          this.$refs.designPanel.showDesignPage(designInfos);
          // 合同信息初始化
          this.$refs.contractPanel.showhtclPage(result,this.currentUnit);
        } else {
          sjhtml += `<tbody>
                    <tr><td style="text-align: center">暂无设计信息</td></tr>
                </tbody>`
          this.domObj.find("#" + this.unitQualityID).empty().append("<table class='table'>" + sjhtml + "</table>");
        }
      })
      const unitInfo = this.currentUnit;
      // 质量信息初始化
      if (unitInfo.code) {
        this.$refs.qualityPanel.showUnitQualityPage(unitInfo.code);
      }
      //扫码信息初始化
      if (unitInfo.code && unitInfo.geoType) {
        this.$refs.scanPanel.showSmInfoPage(unitInfo.geoType, 'CON', unitInfo.code, unitInfo.prjId);
      }
      //档案信息资料
      this.$refs.dcoumentPanel.showDAPage(unitInfo);
    },
    /**
     * 该方法用于属性查询(查询数据服务)
     * @param options 
     */
    queryByAttribute(options) {
      const filterparams = new SuperMap.REST.FilterParameter({
        attributeFilter: options.whereclause,
        fields: options.fields
      });
      const sqlParams = new SuperMap.REST.GetFeaturesBySQLParameters({
        queryParameter: filterparams,
        datasetNames: options.datasetNames,
        toIndex: -1
      });
      const queryservice = new SuperMap.REST.GetFeaturesBySQLService(options.url, {
        eventListeners: {
          processCompleted: options.completed,
          processFailed: options.failed
        }
      });
      queryservice.processAsync(sqlParams);
    },
    /**
     * 获取图层空间管理信息表
     *
     */
    getDirc(callback) {
      let data = {
        current: 1,
        size: 1000,
      };
      apis.getLayermanagement(data).then((results) => {
        this.getDircList = results.data.result.records;
        callback();
      });
    },
    /**
     * 该方法用于组织管线或管点属性信息
     * @param {object} attrs 属性信息
     * @param {string} geotType 几何类型
     * @returns {Array<any>} 返回包含中文字段名的信息 
     */
    formPipeAttribs(geotType, attrs) {
      const unitType = geotType === "LINE3D" ? "LINE" : "POINT";
      const fields = Config.fieldsInfo[unitType];
      let info = [];
      for (let name in fields) {
        info.push({ "title": fields[name], "value": attrs[name] });
      }
      //记录部件类型和PBScode
      this.currentUnit.code = attrs["CODE"];
      this.currentUnit.prjId = attrs['PRJ_ID']
      this.currentUnit.geoType = unitType;
      return info;
    },
    /**
     * 提供对外接口时，定位至构件位置
     * @param geometry 几何图形
     * @param completed 回调函数
     */
    location(geometry, completed) {
      const position = geometry.position;
      const location = Cesium.Cartographic.fromDegrees(position.x, position.y, position.z + 50);
      const scenePosition = Cesium.Cartographic.fromDegrees(position.x, position.y, position.z);
      const cartesian3 = Cesium.Cartographic.toCartesian(location);
      this.infoWindow._scenePosition = Cesium.Cartographic.toCartesian(scenePosition);
      const camera = this.viewer.camera;
      if (this.clickType === "click") {
        completed();
      } else {
        camera.flyTo({
          destination: cartesian3,
          orientation: {
            heading: camera.heading,
            pitch: Cesium.Math.toRadians(-82),
            roll: 0
          },
          complete: completed()
        })
      }
    },
    /**
    * 查询结果二三维高亮
    * @param result 
    * @returns 
    */
    entitiesHighLight(result, pbsCode, name) {
      const that = this;
      if (result.originResult.featureCount === 0) {
        return;
      }
      // this.hightLight3D(pbsCode,name);
      this.clickHightLight(result.originResult)
    },
    /**
     * 二维高亮
     * @param result 
     * @returns 
     */
    clickHightLight(result) {
      if (!this.polylineprimitiveCollection) {
        this.polylineprimitiveCollection = new Cesium.PrimitiveCollection();
        this.viewer.scene.primitives.add(this.polylineprimitiveCollection);//添加线容器
      }
      if (!this.pointPrimitiveCollection) {
        this.pointPrimitiveCollection = new Cesium.PointPrimitiveCollection();
        this.viewer.scene.primitives.add(this.pointPrimitiveCollection);//添加点容器
      }
      if (!result) return;
      if (!this.polylineprimitiveCollection) return
      if (!this.pointPrimitiveCollection) return
      const geometry = result.features[0].geometry.points;
      const geotype = result.features[0].geometry.type
      if (geotype === "LINE3D") {
        const pointA = Cesium.Cartesian3.fromDegrees(geometry[0].x, geometry[0].y, geometry[0].z);
        const pointB = Cesium.Cartesian3.fromDegrees(geometry[1].x, geometry[1].y, geometry[0].z);
        this.polylineprimitiveCollection.add(GroundPolyline([pointA, pointB]));
      } else {
        const pointS = Cesium.Cartesian3.fromDegrees(geometry[0].x, geometry[0].y, geometry[0].z);
        this.pointPrimitiveCollection.add({
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          pixelSize: 30,
          color: Cesium.Color.fromBytes(255, 125, 0),
          outlineColor: Cesium.Color.TRANSPARENT,
          outlineWidth: 0.0,
          position: pointS
        });
      }
      function GroundPolyline(positions) {
        const instance = new Cesium.GeometryInstance({
          geometry: new Cesium.GroundPolylineGeometry({
            positions: positions,
            width: 15.0
          }),
          attributes: {
            color: new Cesium.ColorGeometryInstanceAttribute(1.0, 0.5, 0.0, 1)
          },
        });
        const polyline = new Cesium.GroundPolylinePrimitive({
          geometryInstances: instance,
          appearance: new Cesium.PolylineColorAppearance(),
          classificationType: Cesium.ClassificationType.TERRAIN
        })
        return polyline;
      }
    },
    clearDrawEvent() {
      if (this.toolTip) {
        this.toolTip.remove();
        this.toolTip = null;
      }
      if (this.tooltipHandler && !this.tooltipHandler.isDestroyed()) {
        this.tooltipHandler.destroy();
        this.tooltipHandler = null;
      }
    },
    /**
     * 清除高亮显示 
     */
    clearSelection() {
      this.viewer.scene.layers.releaseSelection();
      this.clearAllPrimitives();
    },
    /**
    * 该方法用于清除二维点和线的primitivecollection
    */
    clearAllPrimitives() {
      if (this.pointPrimitiveCollection) {
        this.pointPrimitiveCollection.removeAll();
        const isPointDel = this.viewer.scene.primitives.remove(this.pointPrimitiveCollection);
        if (isPointDel) this.pointPrimitiveCollection = null;
      }
      if (this.polylineprimitiveCollection) {
        this.polylineprimitiveCollection.removeAll();
        const isPolylineDel = this.viewer.scene.primitives.remove(this.polylineprimitiveCollection);
        if (isPolylineDel) this.polylineprimitiveCollection = null;
      }
    },
    /**
     * 设置选中的空间数据
     */
    setSpaceSelect(target, condition, dircList, attributes) {
      Object.keys(target).forEach(item => {
        if (item.indexOf(condition) !== -1) {
          const result = dircList.find(v => {
            if (v.name == target[item].parentLayer && v.layerType == target[item].type) return v;
          })
          this.selectTarget = {
            layerId: result.id,
            prjId: attributes['PRJ_ID'],
            partsCode: attributes['PARTS_CODE'],
            size: 1000
          };
        }
      });
    },
    /**
     * 清除临时对象
     */
    clearObjs() {
        if (this.toolTip) {
            this.toolTip.remove();
            this.toolTip = null;
        }
        if (this.infoWindow) {
            this.infoWindow.remove();
            this.infoWindow = null;
            this.AppX.appConfig.infowindow = null;
        }
        //this.activeCursor(false);
        if (this.tooltipHandler && !this.tooltipHandler.isDestroyed()) {
            this.tooltipHandler.destroy();
            this.tooltipHandler = null;
        }
        if(this._vectorLayer){
            this._vectorLayer.getSource().clear();
            this._vectorLayer=null;
            
        }
        this.clearPrimitives();
        this.clearAllPrimitives();
    },
    /**
    * 该方法用于清除primitivecollection
    */
    clearPrimitives() {
        if (this.primitiveCollection) {
            this.primitiveCollection.removeAll();
            const isDel = this.viewer.scene.primitives.remove(this.primitiveCollection);
            if (isDel) this.primitiveCollection = null;
        }
    },
    /**
    * 其他模块操作冲突销毁
    */
    otherDestroy() {
      this.clearObjs();
      //this.addLayerQueryParameters(false);
    },
    /**
     * 该方法用于生成贴地线图元
     * @returns groundPolylinePrimitive
     */
    generaGroundPolyline(positions, material, feature, isPicked) {
      const fields = Config.fields;
      const id = feature.fieldValues[feature.fieldNames.indexOf(fields.id)];
      const code = feature.fieldValues[feature.fieldNames.indexOf(fields.pbs)];
      const pipeId = feature.fieldValues[feature.fieldNames.indexOf(fields.pipeID)];
      const color = isPicked ? new Cesium.ColorGeometryInstanceAttribute(1.0, 0.5, 0.0, 1.0) : new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5);

      const instance = new Cesium.GeometryInstance({
        geometry: new Cesium.GroundPolylineGeometry({
          positions: positions,
          width: 15.0
        }),
        attributes: {
          color: color
        },
        id: code
      });
      const polyline = new Cesium.GroundPolylinePrimitive({
        geometryInstances: instance,
        appearance: new Cesium.PolylineColorAppearance(),
        classificationType: Cesium.ClassificationType.TERRAIN
      })
      polyline.custom = { id: id, pipeId: pipeId };
      return polyline;
    },
    /**
    * 该方法用于生成贴地圆图元
    * @returns groundPolylinePrimitive
    */
    generaGroundCircle(center, radius, material, axis, feature, isPicked) {
      const fields = Config.fields;
      const id = feature.fieldValues[feature.fieldNames.indexOf(fields.id)];
      const code = feature.fieldValues[feature.fieldNames.indexOf(fields.pbs)];
      const pipeId = feature.fieldValues[feature.fieldNames.indexOf(fields.pipeID)];
      const color = isPicked ? new Cesium.ColorGeometryInstanceAttribute(1.0, 0.5, 0.0, 1.0) : new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5);
      const instance = new Cesium.GeometryInstance({
        geometry: new Cesium.EllipseGeometry({
          center: center,
          semiMajorAxis: axis,
          semiMinorAxis: axis,
          height: 100.0
        }),
        attributes: {
          color: color
        },
        id: code
      });
      const circle = new Cesium.GroundPrimitive({
        geometryInstances: instance,
        appearance: new Cesium.PerInstanceColorAppearance({
          flat: true,
          translucent: false
        }),
        classificationType: Cesium.ClassificationType.TERRAIN

      })
      circle.custom = { id: id, pipeId: pipeId };
      return circle;
    }
  },
};
</script>
<style lang="scss" scoped>
</style>
<style lang="scss">
.bubblewindow {
  max-width: unset;
  max-height: unset;
  height: 394px;

  .bubblecontent {
    overflow: hidden;
  }

  .bubbletitle {
    font-size: 18px;
  }
}

.bubblewindow:after {
  // left: 343px;
  left: 50%;
}
</style>