<template>
  <div class="sm-panel sm-function-module-query" v-show="PoinyQueryShow && vectorShow" v-drag>
    <div class="sm-panel-header">
      <span>{{ Resource.PoinyQuery }}</span>
      <span class="closeBtn" @click="toggleVisibility">&times;</span>
    </div>
    <!-- <div class="sm-function-module-content-btn"> -->
    <div class="btnList">
      <span v-for="(item, index) in actionOptions" :key="index" class="icon-span" :title="item.lable"
        :class="item.isSelect ? 'selected-icon' : ''" @click="changleQueryItem(item)">
        <i class="iconfont iconSize" :class="item.iconName" style="margin-top: 0px"></i>
      </span>
      <!-- <el-button type="primary" size="small" @click.stop="mapLayerQuery"
        >点击</el-button
      >
      <el-button type="primary" size="small" @click.stop="removeMapLayerQuery"
        >清除</el-button
      > -->
    </div>
    <div class="sm-function-module-content-tabs">
      <el-tabs @tab-click="handleTabClick" v-model="activeLayerId">
        <el-tab-pane :label="item.label" :name="item.id" v-for="(item, index) in layerList" :key="index"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="sm-function-module-content-table">
      <el-collapse :value="activeNames" @change="handleCollapseChange" v-if="
        activeLayerId &&
        queryResults[activeLayerId] &&
        queryResults[activeLayerId].length > 0
      ">
        <el-collapse-item :title="'查询结果' + (index + 1)" :name="'查询结果' + (index + 1)"
          v-for="(item, index) in queryResults[activeLayerId]" :key="index">
          <template slot="title">
            查询结果{{ index + 1
            }}<i title="定位" class="header-icon el-icon-s-promotion flyBtn2" @click.stop="flyTo(index)"></i>
          </template>
          <el-table :data="item" :show-header="false" border style="width: 100%" :header-cell-style="{
            background: 'rgba(10, 25, 38, 0.6)',
            color: '#66b1ff',
            fontSize: '14px',
            fontFamily: 'Microsoft YaHei',
            fontWeight: '400',
          }">
            <el-table-column prop="name" label="字段" width="100">
            </el-table-column>
            <el-table-column prop="value" label="值" width="208">
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- <CockpitVector v-if="store.state.vectorData.length > 0"></CockpitVector> -->
    <MultiLevelQuery ref="MultiLevelQuery" />
  </div>
</template>

<script>
import axios from "axios";
import { GetGDlnfo, GetXzqhTree, GetHouseInfo } from "../../../api/map";
import { keys } from "lodash";
import { handModel, handnew, clearTranslate, keyName } from "./modelLayering";
import CockpitVector from "./CockpitVector.vue";
import MultiLevelQuery from "./MultiLevelQuery.vue";
import {
  loadGeoJSON,
  removeGeoJSON,
  str2Unicode,
  bbox,
} from "@/utils/MapHelper/help.js";
import * as pick_cockpit_vector from "./pick_cockpit_vector.js";
import * as tdsy from "@/views/cockpit/js/tdsy";
import * as turf from "@turf/turf";
import {
  calcIserverURI,
  getfieldList,
  cartesianToCartographic84,
  superQuery,
  mapQuery,
  cartesian3ToWGS84,
  addGeomParts,
  addGeom,
} from "@/utils/MapHelper/clickQuery.js";
// import { cartesian3ToWGS84 } from "@/utils/MapHelper/MapHelper.js";
let gwtype;
let query_click = null;
let manager_layer_png = null;
let dataSourceLayer = null;
export default {
  name: "clickQuery",
  components: { CockpitVector, MultiLevelQuery },

  data() {
    return {
      inited: false,
      activeLayerName: "",
      columns: [
        {
          title: "字段",
          key: "name",
        },
        {
          title: "值",
          key: "value",
        },
      ],
      layersDataUrl: window.layersDataUrl,
      layersData: [],
      layerList: [],
      loading: false,
      handler: {},
      activeNames: "查询结果1",
      activeLayerId: "",
      queryResults: {},
      queryResultsGeom: {},
      queryResultsGeomPart: {},
      viewer: null,
      // dataSourceLayer: null,
      actionOptions: [
        {
          index: 1,
          lable: "图层",
          iconName: "el-icon-tickets",
          isSelect: false,
        },
        {
          index: 6,
          lable: "框选",
          iconName: "el-icon-edit-outline",
          isSelect: false,
        },
        {
          index: 2,
          lable: "模型",
          iconName: "el-icon-office-building",
          isSelect: false,
        },
        // {
        //   index: 4,
        //   lable: "矢量",
        //   iconName: "el-icon-picture",
        //   isSelect: false,
        // },
        {
          index: 5,
          lable: "联级查询",
          iconName: "el-icon-c-scale-to-original",
          isSelect: false,
        },
        {
          index: 3,
          lable: "清除",
          iconName: "el-icon-delete",
          isSelect: false,
        },
      ],
    };
  },
  computed: {
    PoinyQueryShow: function () {
      return store.state.toolBar[9];
    },
    vectorShow: function () {
      return store.state.cockpit_vector.title ||
        store.state.cockpit_vector.goitem
        ? !store.state.viewer_flag
        : true;
    },
  },
  created() { },
  watch: {
    activeLayerId(val) {
      if (val && val != "0") {
        for (let i = 0; i < store.state.vectorlayerlist.length; i++) {
          let obj = store.state.vectorlayerlist[i];
          if (obj.id == val) {
            if (obj.serverType == "geoserver") {
              removeGeoJSON("geoserver");
              this.addGeoJson("#0000ff");
            } else {
              this.addGeometrys(obj.type == "S3M");
            }
            break;
          }
        }
      }
    },
    PoinyQueryShow(val) {
      if (!this.inited) {
        this.inited = !this.inited;
        viewer.entities.removeAll();
        this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        dataSourceLayer = new Cesium.CustomDataSource("query");
        viewer.dataSources.add(dataSourceLayer);
      }
    },
  },
  mounted() {
    console.log(str2Unicode(`fid_城镇`));
    this.$nextTick((res) => {
      query_click = new Cesium.CustomDataSource("query_click");
      viewer.dataSources.add(query_click);

      manager_layer_png = new Cesium.CustomDataSource("manager_layer_png");
      viewer.dataSources.add(manager_layer_png);
    });
  },
  methods: {
    isArray2D(arr) {
      // 首先检查arr是否是数组
      if (!Array.isArray(arr)) {
        return false;
      }

      // 检查数组中的每个元素是否也是数组
      for (let i = 0; i < arr.length; i++) {
        if (!Array.isArray(arr[i])) {
          return false;
        }
      }

      // 如果所有元素都是数组，那么arr是二维数组
      return true;
    },
    toggleVisibility() {
      this.removeMapLayerQuery();
      this.remove_query_click();
      removeGeoJSON("geoserver");
      store.setToolBarAction(9);
      tdsy.remove(false);
    },
    addGeometrys(fill) {
      viewer.entities.removeAll();
      dataSourceLayer.entities.removeAll();
      let geoms = this.queryResultsGeom[this.activeLayerId];
      let parts = this.queryResultsGeomPart[this.activeLayerId];
      addGeomParts(fill, geoms, parts);
    },
    flyTo(index) {
      let geoms = this.queryResultsGeom[this.activeLayerId];
      let cur = geoms[index];
      if (cur) {
        if (cur.type) {
          removeGeoJSON("geoserver");
          loadGeoJSON(
            cur,
            "#ff0000",
            { isfly: true, fill_a: 0.6, sw: 5 },
            (data) => (data.name = "geoserver")
          );
        } else {
          this.flyToSuperMap(cur, index);
        }
      } else {
        this.$message({
          message: "空间范围为空！",
          type: "warning",
        });
      }
    },
    addGeoJson() {
      let geoms = this.queryResultsGeom[this.activeLayerId];
      geoms.forEach((geom) => {
        loadGeoJSON(
          geom,
          "#0000ff",
          { fill_a: 0.6, sw: 5 },
          (data) => (data.name = "geoserver")
        );
      });
    },
    removeGeoJSON() {
      // viewer.entities.removeAll();
      // viewer.dataSources._dataSources.forEach((das) => {
      //   if (das.name == "geoserver") viewer.dataSources.remove(das);
      // });
    },
    flyToSuperMap(cur, index) {
      dataSourceLayer.entities.removeAll();
      let parts = this.queryResultsGeomPart[this.activeLayerId];
      let part = parts[index];
      addGeom(cur, part, false, true);
    },
    handleTabClick(item, a) {
      this.activeLayerId = item.name;
    },
    // 设置数据
    setData() {
      dataSourceLayer = new Cesium.CustomDataSource("query");
      viewer.dataSources.add(dataSourceLayer);
      this.activeLayerId = "0";
      this.queryResults = {};
      this.queryResultsGeom = {};
      this.queryResultsGeomPart = {};
    },
    /**
     * 左键点击查询图层
     */
    async mapLayerQuery(movement) {
      let that = this;
      that.activeLayerId = "0";
      that.layerList = [];
      that.layersData = [];
      this.remove_query_click();
      let scene = viewer.scene;

      console.log("scene", "scene");
      console.log("scene", scene);

      viewer.entities.removeAll();
      dataSourceLayer.entities.removeAll();
      removeGeoJSON("geoserver");
      //拾取模型
      let pickedFeature = scene.pick(movement.position);
      console.log("pickedFeature", pickedFeature);
      if (
        scene.pickPositionSupported &&
        Cesium.defined(pickedFeature) &&
        pickedFeature != null &&
        pickedFeature.primitive &&
        pickedFeature.id.lable!='nopick'
      ) {
        this.pickClick(pickedFeature);
      } else {
        this.pickPosition(movement);
      }
    },
    async mapSelect(pos, obj) {
      console.log("mapSelect", "---");
      // let obj = window.tempSelect;
      let queryByIDParameters = {
        // getFeatureMode: "BUFFER",
        getFeatureMode: "SPATIAL",
        spatialQueryMode: "INTERSECT",
        datasetNames: [`${obj.fwgzkj}:${obj.fwmc}`], //obj.source.split(","),
        geometry: {
          parts: [1], // points: [{ y: xy.lat, x: xy.lng }],
          points: pos,
          type: "REGION",
        },
        bufferDistance: 0.00005,
        hasGeometry: true,
      };
      let url2 = calcIserverURI(obj.url);
      let e;
      e = await mapQuery(url2, queryByIDParameters);
      if (e && e.totalCount > 0) {
        this.addLayerList(obj.title, obj);
        let queryData = [];
        let geoms = [];
        let parts = [];
        // let parseJson = JSON.parse(obj.legend);
        let parseJson = await getfieldList(obj.id, false);
        for (let u = 0; u < e.features.length; u++) {
          let cur = [];
          var linSAr = JSON.parse(JSON.stringify(e.features[u]));
          function condition(ci) {
            return ci.status != undefined && ci.status;
          }
          if (e.features[u].fieldNames) {
            linSAr.fieldNames.forEach((fieldName, i) => {
              let perjson = parseJson.filter(
                (p) => p.filedName.toUpperCase() == fieldName
              );
              if (perjson.length > 0) {
                var show = condition(perjson[0]);
                var order = perjson[0].order || linSAr.fieldNames.length;
                if (fieldName != perjson[0].filedNameZh)
                  fieldName = perjson[0].filedNameZh;
              }
              if (show) {
                let v = linSAr.fieldValues[i];
                if (v != "" && !isNaN(parseFloat(v))) {
                  v = Math.round(parseFloat(v) * 100) / 100;
                }
                cur.push({ name: fieldName, value: v, order });
              }
            });
          } else {
            that.$message({
              message: "查询结果为空！",
              type: "warning",
              customClass: "messageIndex",
            });
          }
          // console.log(cur, "cur");
          //排序
          cur.sort((a, b) => a.order - b.order);
          let urlNew = obj.url + ".json";
          let resNew = await axios.get(urlNew);
          let serCode = resNew.data.prjCoordSys.epsgCode;
          let points = [];
          for (let y = 0; y < e.features[u].geometry.points.length; y++) {
            let c = {};
            if (serCode == 3857) {
              c = cartesianToCartographic84(
                e.features[u].geometry.points[y].x,
                e.features[u].geometry.points[y].y
              );
            } else {
              c = e.features[u].geometry.points[y];
            }
            points.push([c.x, c.y]);
          }
          parts.push(e.features[u].geometry.parts);
          geoms.push(points);
          queryData.push(cur);
        }

        this.queryResultsGeomPart[obj.id] = parts;
        this.queryResults[obj.id] = queryData;
        this.queryResultsGeom[obj.id] = geoms;
      }
      this.setactiveLayerId();

      // this.drawPolygon(window.tempSelect)
      // //拾取模型
      // let pickedFeature = viewer.scene.pick(movement.position);
      // console.log(pickedFeature, "pickedFeature");
    },

    async pickClick(pickedFeature) {
      let that = this;
      let eneityName = pickedFeature.primitive.name;
      let Pid = "";
      var tempArr = [];
      // ##############################################
      if (eneityName.indexOf("单体") > -1) {
        console.log("eneityName", eneityName);
        debugger
        let ModelName = "";
        let obj = store.state.vectorlayerlist.find((i) => {
          return eneityName == i.title;
        });
        let url1 = obj.url.replace("3D-", "data-");
        let url2 = url1.replace(
          "realspace",
          "data/featureResults.rjson?returnContent=true"
        );
        console.log(url2, "url2");
        let queryModelName = {
          getFeatureMode: "ID",
          datasetNames: [eneityName + ":" + eneityName + "关联"],
          ids: [pickedFeature.id]
        };
        let res = await mapQuery(url2, queryModelName);
        if (res && res.totalCount > 0) {
          let feature = res.features[0]
          // 循环feature中的fieldNames
          for (let i = 0; i < feature.fieldNames.length; i++) {
            // 获取字段名
            let fieldName = feature.fieldNames[i];
            // 获取字段值
            let fieldValue = feature.fieldValues[i];
            // 如果字段名为ModelName
            if (fieldName == "MODELNAME") {
              // 获取ModelName的值
              ModelName = fieldValue;
              break;
            }
          }
        }

        let queryByIDParameters = {
          getFeatureMode: "SQL",
          datasetNames: [eneityName + ":" + eneityName+"矢量"],
          queryParameter: { "attributeFilter": "ModelName=" + ModelName },
        };
        let e = await mapQuery(url2, queryByIDParameters);
        if (e && e.totalCount > 0) {
          // that.layerList.push(store.state.vectorlayerlist[i]);
          that.layerList.push(obj);
          for (let u = 0; u < e.features.length; u++) {
            let cur = [];
            var linSAr = JSON.parse(JSON.stringify(e.features[u]));
            if (e.features[u].fieldNames) {
              linSAr.fieldNames.forEach((fieldName, i) => {
                let v = linSAr.fieldValues[i];
                if (v != "" && !isNaN(parseFloat(v))) {
                  v = Math.round(parseFloat(v) * 100) / 100;
                }

                // cur.push({ name: fieldName, value: v });
                if (
                  fieldName.toLowerCase().indexOf("shape") < 0 &&
                  fieldName.toLowerCase().indexOf("sm") &&
                  v != ""
                ) {
                  cur.push({ name: fieldName, value: v });
                }
              });

              //获取图层id的参数
              let substring = pickedFeature.primitive._baseUri.query;
              for (let p = 0; p < store.state.vectorlayerlist.length; p++) {
                if (store.state.vectorlayerlist[p].id == substring) {
                  that.layerList.push(store.state.vectorlayerlist[p]);
                  break;
                }
              }
              that.queryResults[substring] = [cur];
              that.queryResultsGeom[substring] = [];
              that.activeLayerId = substring;
            } else {
              that.$message({
                message: "查询结果为空！",
                type: "warning",
                customClass: "messageIndex",
              });
            }
          }
        }
      } else if (eneityName.indexOf("雨水") > -1 || eneityName.indexOf("管线") > -1) {
        // for (let i = 0; i < store.state.vectorlayerlist.length; i++) {
        // let obj = store.state.vectorlayerlist[i];

        // console.log(obj.url,'url----------',obj);
        let str1 = eneityName.match(/@(\S*)#/)[1];
        let str2 = eneityName.match(/(\S*)@/)[1];
        let str3 = str1 + ":" + str2;
        // let obj = store.state.vectorlayerlist.find(i => i.title == str1);
        let obj = store.state.vectorlayerlist.find((i) => {
          return str1 == i.title;
        });
        let url1 = obj.url.replace("3D-", "data-");
        let url2 = url1.replace(
          "realspace",
          "data/featureResults.rjson?returnContent=true"
        );
        console.log(url2, "url2");
        let queryByIDParameters = {
          getFeatureMode: "ID",
          datasetNames: [str3],
          ids: [pickedFeature.id],
        };
        let e = await mapQuery(url2, queryByIDParameters);
        if (e && e.totalCount > 0) {
          // that.layerList.push(store.state.vectorlayerlist[i]);
          that.layerList.push(obj);
          for (let u = 0; u < e.features.length; u++) {
            let cur = [];
            var linSAr = JSON.parse(JSON.stringify(e.features[u]));
            if (e.features[u].fieldNames) {
              linSAr.fieldNames.forEach((fieldName, i) => {
                let v = linSAr.fieldValues[i];
                if (v != "" && !isNaN(parseFloat(v))) {
                  v = Math.round(parseFloat(v) * 100) / 100;
                }

                // cur.push({ name: fieldName, value: v });
                if (
                  fieldName.toLowerCase().indexOf("shape") < 0 &&
                  fieldName.toLowerCase().indexOf("sm") &&
                  v != ""
                ) {
                  cur.push({ name: fieldName, value: v });
                }
              });

              //获取图层id的参数
              let substring = pickedFeature.primitive._baseUri.query;
              for (let p = 0; p < store.state.vectorlayerlist.length; p++) {
                if (store.state.vectorlayerlist[p].id == substring) {
                  that.layerList.push(store.state.vectorlayerlist[p]);
                  break;
                }
              }
              that.queryResults[substring] = [cur];
              that.queryResultsGeom[substring] = [];
              that.activeLayerId = substring;
            } else {
              that.$message({
                message: "查询结果为空！",
                type: "warning",
                customClass: "messageIndex",
              });
            }
          }
        }
        // }
      }

      that.loading = true;
      that.queryByPickFeature(pickedFeature, function (result, Fields) {
        that.loading = false;
        if (result != null && result.features[0].fieldNames) {
          result.features[0].fieldNames.forEach((fieldName, i) => {
            const Field = Fields.find((c) => c.FieldEn == fieldName);
            let v = result.features[0].fieldValues[i];
            if (!isNaN(parseFloat(v))) {
              v = Math.round(parseFloat(v) * 100) / 100;
            }
            that.layersData.push({
              label: Field ? Field.FieldCn : fieldName,
              value: v,
            });
          });
        } else {
          that.layersData = [];
        }
      });
    },
    pickPosition(movement) {
      //拾取图层
      // let pickRay = viewer.camera.getPickRay(movement.position);
      // let artesian3 = viewer.scene.globe.pick(pickRay, viewer.scene);
      let artesian3 = viewer.scene.pickPosition(movement.position);
      let xy = cartesian3ToWGS84(artesian3);
      //TODO wanger 分图层查询
      for (let i = 0; i < store.state.vectorlayerlist.length; i++) {
        let obj = store.state.vectorlayerlist[i];
        // 结果高亮
        this.highlightResultsPng(xy.lng, xy.lat);
        if (obj.serverType == "geoserver") {
          this.getGeoserver(xy, obj);
        } else {
          if (!obj.fwgzkj && !obj.fwmc) {
            continue;
          }
          superQuery(xy, obj, (data) => this.superQfun(data, obj));
        }
      }
    },
    superQfun({ parts, queryData, geoms, e }, obj) {
      if (!e.features[0].fieldNames) {
        this.$message({
          message: "查询结果为空！",
          type: "warning",
          customClass: "messageIndex",
        });
      }
      if (e && e.totalCount > 0) {
        this.addLayerList(obj.title, obj);
        this.queryResultsGeomPart[obj.id] = parts;
        this.queryResults[obj.id] = queryData;
        this.queryResultsGeom[obj.id] = geoms;
      }
      this.setactiveLayerId();
    },
    setactiveLayerId() {
      if (this.layerList.length > 0) {
        this.activeLayerId = this.layerList[0].id;
      } else {
        this.$message({
          message: "查询结果为空！",
          type: "warning",
          customClass: "messageIndex",
        });
      }
    },
    async getGeoserver(xy, obj) {
      this.queryResults[obj.id] = [];
      this.queryResultsGeom[obj.id] = [];
      let ind =
        obj.url.indexOf("geoserver") >= 0
          ? obj.url.indexOf("geoserver")
          : obj.url.indexOf("siweiserver");
      let url = obj.url.substring(0, ind + 9) + "/ows";

      let pointml = `<gml:Point srsName='EPSG:4326'><gml:coordinates>
          ${xy.lng},${xy.lat}</gml:coordinates></gml:Point>`;
      let polygonml = `<gml:Polygon srsName="EPSG:4326">
          <gml:outerBoundaryIs>
            <gml:LinearRing>
              <gml:coordinates> ${xy.points} </gml:coordinates>
            </gml:LinearRing>
          </gml:outerBoundaryIs>
        </gml:Polygon>`;
      let params = {
        service: "WFS",
        version: "1.0.0",
        request: "GetFeature",
        typeName: `${obj.fwgzkj}:${obj.fwmc}`,
        outputFormat: "application/json",
        srsName: "EPSG:4326",
        filter: `<Filter xmlns='http://www.opengis.net/ogc' xmlns:gml='http://www.opengis.net/gml'><Intersects><PropertyName>geom</PropertyName> ${xy.lng ? pointml : polygonml
          }</Intersects></Filter>`,
      };
      console.log("----", params);
      let res = await axios.get(url, { params });
      if (res.data && res.data.features && res.data.features.length > 0) {
        this.addLayerList(obj.title, obj);
        res.data.features.forEach((feitem) => {
          let cur = [];
          Object.keys(feitem.properties).forEach((key) => {
            cur.push({ name: key, value: feitem.properties[key] });
          });
          this.queryResults[obj.id].push(cur);
          this.queryResultsGeom[obj.id].push(feitem.geometry);
        });
      } else {
        this.$message({
          message: "查询结果为空！",
          type: "warning",
          customClass: "messageIndex",
        });
      }

      this.setactiveLayerId();
    },
    highlightResultsPng(longitude, latitude) {
      manager_layer_png.entities.add({
        name: "manager_layer_png",
        position: Cesium.Cartesian3.fromDegrees(longitude, latitude),
        billboard: {
          // 图像地址，URI或Canvas的属性
          image: "./static/images/overview/go.png",
          height: 34,
          width: 36,
          scale: 1.0,
          zIndex: 2,
          show: true,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        },
      });
    },
    addLayerList(label, obj) {
      if (this.layerList.findIndex((a) => a.label == label) >= 0) return;
      if (obj) {
        this.layerList.push(obj);
      } else {
        let layers = store.state.vectorlayerlist.filter(
          (element) => element.label === label
        );
        if (layers.length > 0) {
          this.activeLayerId = layers[0].id;
          this.layerList.push(layers[0]);
        }
      }
    },
    /**
     * 左键点击模型查询
     */
    mapModelQuery(movement) {
      this.activeLayerId = "0";
      this.layerList = [];
      this.layersData = [];
      viewer.entities.removeAll();
      dataSourceLayer.entities.removeAll();
      removeGeoJSON("geoserver");
      clearTranslate()
      let title;
      if (store.state.checkedData) title = store.state.checkedData.title;
      //  超图分层分户
      if (title == "分层分户" || title == "8号楼-谷") {
        let id = handModel(movement);
      } else {
        handnew(movement);
      }
      let newArr = [];
      GetHouseInfo({ id: "2c01647f-4533-4472-b20b-f5caa4c705b0" }).then(
        (res) => {
          for (const [key, value] of Object.entries(res.data)) {
            newArr.push({ name: keyName[key], value: value });
          }
          this.addLayerList(title);
          this.queryResults[this.activeLayerId] = [newArr];
          this.queryResultsGeom[this.activeLayerId] = [];
        }
      );
    },
    mapQuerys(queryName) {
      this.setData();
      let that = this;
      this.handler.setInputAction(function (movement) {
        that[queryName](movement);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      this.handler.setInputAction(function () {
        that.removeMapLayerQuery();
        clearTranslate();
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },
    /**
     * 超图
     * 根据返回的三维对象查询数据信息
     *
     * @param {*} param
     */
    async queryByPickFeature(param, completed) {
      if (param.primitive) {
        let dataUrl = "";
        let datasourceName = "";
        let Fields = [];
        for (const layerData of this.layersDataUrl) {
          for (const datasource of layerData.datasources) {
            if (datasource.Name3D == param.primitive.name) {
              dataUrl = layerData.url;
              datasourceName = datasource.DataName;
              Fields = datasource.Fields;
              break;
            }
          }
        }

        let queryByIDParameters = {
          getFeatureMode: "ID",
          datasetNames: [datasourceName],
          ids: [param.id],
          hasGeometry: "false",
        };
        if (!dataUrl) {
          completed(null);
        } else {
          let e = await mapQuery(dataUrl, queryByIDParameters);
          if (completed) {
            completed(e, Fields);
          }
        }
      }
    },

    convertCoordinates(coordArray) {
      return coordArray.map((coord) => [coord.x, coord.y]);
    },
    // 取消左键点击查询
    removeMapLayerQuery() {
      this.queryResults = {};
      this.queryResultsGeom = {};
      this.queryResultsGeomPart = {};
      this.layerList = [];
      // viewer.entities.removeAll();
      if (this.handler.removeInputAction) {
        this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      }
      dataSourceLayer.entities.removeAll();
      removeGeoJSON("geoserver");
      viewer.dataSources.remove(dataSourceLayer);
    },

    remove_query_click() {
      for (var i = 0; i < 10; i++) {
        query_click.entities.values.forEach((res) => {
          query_click.entities.remove(res);
        });
      }

      // 图标
      var entities = manager_layer_png.entities.values;
      for (var i = entities.length - 1; i >= 0; i--) {
        manager_layer_png.entities.remove(entities[i]);
      }
    },
    //地图数据查询事件
    changleQueryItem(item) {
      switch (item.index) {
        case 1: {
          this.mapQuerys("mapLayerQuery"); //图层点击事件
          this.remove_query_click();
          // viewer.entities.removeAll();
          break;
        }
        case 2: {
          this.mapQuerys("mapModelQuery");
          break;
        }
        case 3: {
          this.removeMapLayerQuery(); //清除
          clearTranslate();
          // pick_cockpit_vector.clear_data(); //矢量拾取清除
          this.$refs.MultiLevelQuery.clear_data(); //多级查询

          this.remove_query_click();
          common.clearHandlerDrawing("Polygon");
          break;
        }
        case 4: {
          //驾驶舱矢量数据点选查询
          // pick_cockpit_vector.init_handler();
          break;
        }
        case 5: {
          //联级查询
          this.$refs.MultiLevelQuery.init_handler();
          break;
        }
        case 6: {
          //联级查询
          // this.$refs.MultiLevelQuery.init_handler();
          this.drawMap();
          console.log("框选事件");
          break;
        }
        default:
          break;
      }
    },
    //绘制
    drawMap() {
      let nReaions = [];
      let that = this;
      this.activeLayerId = "0";
      this.layerList = [];
      this.layersData = [];
      // this.remove_query_click();
      // let scene = viewer.scene;
      // viewer.entities.removeAll();
      // dataSourceLayer.entities.removeAll();
      removeGeoJSON("geoserver");
      if (!window.handlerPolygon) {
        common.initHandler("Polygon");
      }
      common.handlerDrawing("Polygon").then(
        (res) => {
          //过滤掉高度
          const filteredArr = res.positions.filter((item, index) => {
            if ((index + 1) % 3 !== 0) return item;
          });
          filteredArr.push(res.positions[0]);
          filteredArr.push(res.positions[1]);
          console.log(filteredArr, "max-----");
          for (let i = 0; i < filteredArr.length; i += 2) {
            nReaions.push({
              x: filteredArr.slice(i, i + 2)[0],
              y: filteredArr.slice(i, i + 2)[1],
            });
          }
          // console.log(nReaions, "nReaions");
          removeGeoJSON("geoserver");
          store.state.vectorlayerlist.forEach((obj) => {
            if (obj.serverType == "geoserver") {
              let points = "";
              res.positions.forEach((item, index) => {
                if ((index + 1) % 3 == 1) points += item + ",";
                if ((index + 1) % 3 == 2) points += item + " ";
              });
              points += res.positions[0] + ",";
              points += res.positions[1] + " ";
              console.log(res.positions, points);
              this.getGeoserver({ points }, obj);
            } else {
              this.mapSelect(nReaions, obj);
            }
          });
        },
        (err) => {
          console.log(err);
        }
      );
      window.handlerPolygon.activate();
    },
  },
  beforeDestroy() {
    this.removeMapLayerQuery();
    clearTranslate();
  },
};
</script>
<style>
.sm-function-module-content-btn {
  text-align: center;
  padding-top: 5px;
}

.flyBtn2 {
  position: absolute;
  right: 47px;
}

.el-tabs__item {
  color: white !important;
}

.sm-function-module-content-tabs {
  height: 45px;
  padding: 1px 5px 0px 5px;
  /* margin-top: 4rem; */
}

.sm-function-module-content-table {
  height: 564px;
  overflow-y: auto;
  padding: 1px 5px 0px 5px;
}

.sm-function-module-query {
  /* padding: 5px 10px; */
  overflow: hidden;
  max-height: 700px;
  scrollbar-width: none;
  /* firefox */
  -ms-overflow-style: none;

  /* IE 10+ */
  @media (max-width: 1000px) {
    margin: 0.8rem 0;
    padding: 0 15px;
  }

  @media (max-width: 750px) {
    margin: 0.5rem 0;
    padding: 0 10px;
    max-height: 410px;
  }

  @media (max-height: 480px) {
    margin: 0.5rem 0;
    padding: 0 15px;
    max-height: 420px;
    max-width: 280px;
  }

  @media (max-height: 300px) {
    margin: 0.5rem 0;
    padding: 0 10px;
    max-height: 280px;
    max-width: 250px;
  }

  @media (max-height: 250px) {
    max-height: 240px;
  }
}
</style>
<style lang="scss" scoped>
@import "clickQuery";

/deep/ .el-table tr {
  background: rgba(10, 25, 38, 0.5) !important;
}

/deep/ .el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
  background: rgba(10, 25, 38, 0.5) !important;

  border-bottom: 1px solid #ebeef5;
}

.el-table {
  color: #fff;
  background: rgba(10, 25, 38, 0.5) !important;
}

/deep/ .el-table__fixed-right::before,
.el-table__fixed::before {
  background: rgba(10, 25, 38, 0.9) !important;
}

/deep/ .el-table__fixed-right-patch {
  background: rgba(10, 25, 38, 0.9) !important;
}

/deep/ .el-table--border::after,
.el-table--group::after,
.el-table::before {
  background: rgba(10, 25, 38, 0) !important;
}

/deep/ .el-collapse-item__header {
  background-color: transparent !important;
  color: rgb(217, 237, 254) !important;
}

/deep/ .el-collapse {
  border: none;
  /* border-top: 1px solid #EBEEF5; */
  /* border-bottom: 1px solid #EBEEF5; */
}

/deep/ .el-collapse-item__content {
  padding-bottom: 0px;
}
</style>
