<template>
  <el-container class="cim-map el-main">
    <component
      :is="initMap"
      :opening-animation="true"
      :after-initviewer="removeLoad"
    />
    <!-- <LayerTreeLocal
      v-if="roleInfo.mapVisible"
      :server="MAP_SERVER"
      ref="layerTreeLocal"
      :location="roleInfo.posVisible"
      :layersVisible="roleInfo.layersVisible"
      @change-basemap="handlerChangeBasemap"
      @on-add-layer="handlerLoadWebServer"
      @on-del-layer="handlerDelLayer"
      @on-layer-fly="flyTo"
      @handle-tool="handlerTool"
    /> -->
    <!-- 监控 -->
  <div style="z-index:99;top:0;left:0;background:rgba(0,0,0,0.2)" class="flex max-w max-h ai-c jc-c pos-f" @click="monitorClose" v-if="roleInfo.monitorVisible">
    <video width="500" height="400" id="videoElement" controls autoplay></video>
  </div>
  </el-container>
</template>
<script>
/**
 * MAP_SERVER_CONFIG ：图层服务配置文件
 *
 * **/
import { defineComponent, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import LayerTreeLocal from "./widget/layer-tree/toolTreeLocal.vue";
import { postMethodCommonMap, getMethodCommonMap } from "../../api/mapcommon";
import { postMethodCommon, getMethodCommon } from "../../api/common";
import axios from "axios";
import xianjiegeojson from "../../../public/config/临沂市县界.json";
import LinYiShiJieJson from "../../../public/config/临沂市边界.json";

import {
  MAP_SERVER_CONFIG,
  DEFAULT_BASEMAP,
  TDT_KEY,
  BING_MAP_KEY,
  BASE_IMAGE_URL,
  SUPER_MAP_KEY,
  ZHENJIE_BORDER_SERVER,
  S3MLayersArr,
} from "/public/config/server";
import flvjs from 'flv.js';
import mpegts from 'mpegts.js'
export default defineComponent({
  components: {
    LayerTreeLocal,
  },
  props: [ "location", "search", "sessionId" ],
  setup(props, context) {
    const layerTreeLocal = ref(null);
    const data = reactive({
      initMap: "Sm3dViewer",
      MAP_SERVER: MAP_SERVER_CONFIG,
      // MAP_TOOL: MAP_TOOL_CONFIG,
      baseLayerObj: {},
      markEntityArr:[],
      roleInfo: {
        mapVisible: true,
        posVisible: props.location,
        layersVisible: true,
        monitorVisible: false,
        flvPlayer: null,
        timeValue: null,
      },
      cooperDatas:[], 
      monitorDataArr: [], 
      monitorPointArr: [],
      monitorMarkArr: []
    });
    const route = useRoute();
    watch(
      () => props.location,
      (newVal, oldVal) => {
        data.roleInfo.posVisible = newVal;
      }
    );
    watch(
      () => props.sessionId,
      (newVal, oldVal) => {
        methods.handleMonitorType(newVal.value)
        setTimeout(()=>{
          methods.handleMonitorType(newVal.value)
        },1000)
      }
    );
    watch(
      () => props.search,
      (newVal, oldVal) => {
        data.monitorDataArr.forEach(item =>{
          if(item.name.includes(newVal)){
            viewer.scene.camera.flyTo({
              destination: new Cesium.Cartesian3.fromDegrees(
                item.position[0],
                item.position[1],
                1000
              ),
            });
            }
          })
      }
    );
    
    onMounted(() => {
      methods.addWebServe(S3MLayersArr[1])
      setTimeout(()=>{
        methods.addWebServe(S3MLayersArr[0])
      },2000)
      
      //获取合作社数据
      methods.getCoopersData()  
      methods.getMonitorData()
      xianjiegeojson.features.forEach((item,index) =>{
        methods.addMaskLayer(item,index)
      })
      methods.addModalLayer()
      // 开局跳转视角
      viewer.scene.camera.flyTo({
        destination: new Cesium.Cartesian3.fromDegrees(
          117.886725,
          34.773011,
          400000
        ),
        duration: 0.1,
        orientation: {
          heading: 0.09596697944080823,
          pitch: -1.4,
          roll: 2.0370372055822372e-11,
        },
      });
      scene.context.memoryThreshold = 6; //显存资源占用阈值,单位是GB。
      if (!data.baseLayerObj.type) {
        // 默认展示MAP_SERVER_CONFIG的第[i,j]图层
        const defaultBaseMapIndex = DEFAULT_BASEMAP;
        if (MAP_SERVER_CONFIG[defaultBaseMapIndex[0]].id === "baseMap") {
          const defaultBaseMap =
            MAP_SERVER_CONFIG[defaultBaseMapIndex[0]].children[
              defaultBaseMapIndex[0]
            ];
          methods.handlerChangeBasemap(defaultBaseMap);
          // layerTreeLocal.value.checkRadioDefault(defaultBaseMapIndex)
        } else {
          ElMessage({
            message: "在线底图配置不正确",
            type: "warning",
          });
        }
      }
    });
    /**
     * methods方法
     *
     *
     *
     *  ————  handlerChangeBasemap 切换底图
     *  ————  handlerLoadWebServer  添加服务图层
     * **/
    const methods = {
      //获取合作社数据
      getCoopersData(){
        let param = {
          id: window.cooperId || "91dff232-6db7-463d-9d1e-ca65e6dadf7d",
          mid: window.cooperMid || "2ba308fc-f118-463d-80fe-c34b5a9121b8",
          paginationInputDto: {
            page: 1,
            rows: 1000,
          }
        }
        postMethodCommon("/FormScheme/GetFormDataPage?id=" + param.id + "&mid="+param.mid, param).then(res =>{
          data.monitorDataArr = []
          let rel = res.data.result.items
          rel.forEach(item =>{
            
            if(item._input_55207a5c87374273a3cefaa01a0a3e3b && item._input_a48a224492e94fd5ae4d6c8568d86807){
              let arr = []
              arr.push(item._input_55207a5c87374273a3cefaa01a0a3e3b)
              arr.push(item._input_a48a224492e94fd5ae4d6c8568d86807)
              data.monitorDataArr.push({
                name: item._input_f3861411ceda40a8bfb6c6fa34fca4c4,
                position: arr,
                id: item._input_guid_056977778c2643468aaae7a1c4606547
              })
            }
          })
          setTimeout(function () {
            methods.addCramePoint()
          }, 2000);
          
        })
      },
      //获取监控点位数据
      getMonitorData(){
        let param = {
          id: "0ff538f2-0948-4aa5-bdf8-51110471a8d0",
          mid: "4a64406c-dedc-4c55-86eb-8bb106967244",
          paginationInputDto: {
            page: 1,
            rows: 1000,
          }
        }
        data.monitorPointArr = []
        postMethodCommon("/FormScheme/GetFormDataPage?id=" + param.id + "&mid="+param.mid, param).then(res =>{
          let rel = res.data.result.items
          rel.forEach(item =>{
            let arr = []
              arr.push(item.lng)
              arr.push(item.lat)
              data.monitorPointArr.push({
                name: item.name,
                position: arr,
                ownerhzs: item.ownerhzs,
                code: item.code,
                id: item._input_guid_e1e8900d1b7d47188c34e53b6d89469f
              })
          })
          
        })
      },
      handleMonitorType(id){
        let url = "http://60.213.43.243:20400/vss/realplay?chanpubid=" + id + "&videourltype=rtmp&transport=udp"
        axios.get(url).then((result) => {
          console.log('result', result)
          
          // 处理成功情况
          if(result.data.flvurl){
            data.roleInfo.monitorVisible = true  
            methods.addMonitorFlvVideo(result.data.flvurl)
            methods.handleKeepLive(result.data.sessionid)
          }       
          
        })
        .catch((err) => {
          // 处理错误情况
          console.log('err', err);
        });
      },
      handleKeepLive(id){
        data.roleInfo.timeValue = setInterval(()=>{
          let url = "http://112.36.21.16:18207/vss/keepalive?sessionid=" + id
          axios.get(url).then((result) => {
            
          })
          .catch((err) => {
            // 处理错误情况
            console.log(err);
          });
        },50000)
      },
      //监控视频
      addMonitorFlvVideo(src){
        if (mpegts.isSupported()) {
            var videoElement = document.getElementById('videoElement')           
            data.roleInfo.flvPlayer = mpegts.createPlayer(
              {
                type: 'flv',
                isLive: true,
                hasAudio: false,
                cors: true,
                hanVideo: true,
                url: src   // 自己的flv视频流
              },
              {
                enableWorker: false, //不启用分离线程
                enableStashBuffer: false, //关闭IO隐藏缓冲区
                reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
                autoCleanupSourceBuffer: true, //自动清除缓存
              }
            )
            data.roleInfo.flvPlayer.attachMediaElement(videoElement)
            data.roleInfo.flvPlayer.load()
            data.roleInfo.flvPlayer.play()
          }
      },
      monitorClose(){
        clearInterval(data.roleInfo.timeValue);
        data.roleInfo.monitorVisible = false
        data.roleInfo.flvPlayer.pause();
        data.roleInfo.flvPlayer.unload();
        data.roleInfo.flvPlayer.detachMediaElement();
        data.roleInfo.flvPlayer.destroy();
        data.roleInfo.flvPlayer = ""; 
      },
      addCramePoint(){
        let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction(function (movement) {
          let selectedEntity = window.viewer.selectedEntity;
          let position = viewer.scene.pickPosition(movement.position);

          let cartographic = Cesium.Cartographic.fromCartesian(position);
          let longitude = Cesium.Math.toDegrees(cartographic.longitude);
          let latitude = Cesium.Math.toDegrees(cartographic.latitude);

          console.log('点击位置坐标', longitude, latitude)

          data.monitorDataArr.forEach(item =>{
            if(selectedEntity && item.id == selectedEntity.id){
              let pos = { x: item.position[0], y: item.position[1]}
              methods.searchFlyTo(
                { position: pos },
                2000
              );
            }
          })
          if(selectedEntity && selectedEntity.label && selectedEntity.label.text){
            let text = selectedEntity.label.text._value
            let crameArr = data.monitorPointArr;
            let arr = [];
            crameArr.forEach(item =>{
              if(text.includes(item.ownerhzs)){
                arr.push(item)
              }
            })
            methods.addMonitorPoint(arr)
            setTimeout(function () {
              context.emit('handleEntityData', selectedEntity.id)
            }, 500)
          }else{
            if(selectedEntity && selectedEntity.id){
              methods.handleMonitorType(selectedEntity.id)
              setTimeout(function () {
                methods.handleMonitorType(selectedEntity.id)
              }, 1000)
            }  
          }
 
          
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        
        let list = data.monitorDataArr;
        let dataSource1 = new Cesium.CustomDataSource("dataSource1");
        for (let i = 0; i < list.length; i++) {
          let entitypoint = new Cesium.Entity({
            id: list[i].id,
            position: Cesium.Cartesian3.fromDegrees(
              parseFloat(list[i].position[0]),
              parseFloat(list[i].position[1])
            ),
            billboard: {
              image: "/images/hzsimg.png",
              height: 54,
              width: 40,
              scale: 1,
              pixelSize: 20,
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
              show: true,
              disableDepthTestDistance: 50000,
            },
            label: {
              text: list[i].name,
              font: "12pt monospace",
              // style: Cesium.LabelStyle.FILL_AND_OUTLINE,
              fillColor: Cesium.Color.fromCssColorString('#DCF30A'),
              outlineColor: Cesium.Color.BLACK,
              outlineWidth: 2,
              pixelOffset: new Cesium.Cartesian2(0, -40),
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
              distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 130000),
            },
          });
          data.markEntityArr.push(entitypoint)
          // viewer.entities.add(entitypoint);
          dataSource1.entities.add(entitypoint);
        }
        let dataSourcePromise = viewer.dataSources.add(dataSource1);
        // dataSourcePromise.then(function (dataSource) {
        //   const pixelRange = 15;
        //   const minimumClusterSize = 3; 
        //   const enabled = true; 
        
        //   dataSource.clustering.enabled = enabled; //聚合开启
        //   dataSource.clustering.pixelRange = pixelRange; //设置像素范围，以扩展显示边框
        //   dataSource.clustering.minimumClusterSize = minimumClusterSize; //设置最小的聚合点数目，超过此数目才能聚合
        // })

      },
      addMonitorPoint(list){
        if(data.monitorMarkArr.length>0){
          data.monitorMarkArr.forEach((item, index) => {
            viewer.entities.remove(data.monitorMarkArr[index])
          })
        }
        
        for (let i = 0; i < list.length; i++) {
          let entitypoint = new Cesium.Entity({
            id: list[i].code,
            position: Cesium.Cartesian3.fromDegrees(
              parseFloat(list[i].position[0]),
              parseFloat(list[i].position[1])
            ),
            billboard: {
              image: "/images/crame.png",
              height: 30,
              width: 20,
              scale: 1,
              pixelSize: 20,
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
              show: true,
              disableDepthTestDistance: 50000,
            }
          });
          data.monitorMarkArr.push(entitypoint)
          viewer.entities.add(entitypoint);
        }
      },
      addModalLayer() {
        const maskpointArray = [];
        let features = LinYiShiJieJson.coordinates;
        for (
          let i = 0;
          i < features[0][0].length;
          i++
        ) {
          let coor = features[0][0][i];
          maskpointArray.push(coor[0]);
          maskpointArray.push(coor[1]);
        }
        // methods._c_add_geojson_area(maskpointArray)
    
        let maskspoint = Cesium.Cartesian3.fromDegreesArray(maskpointArray);
        const entity1 = new Cesium.Entity({
          id: "zhezhao",
          polygon: {
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            hierarchy: {
              // 绘制的区域太大容易卡顿
              positions: Cesium.Cartesian3.fromDegreesArray([
                60, 0, 60, 89, 179, 89, 179, 0,
              ]),
              // holes是图形内需要挖空的区域
              holes: [
                {
                  positions: maskspoint,
                },
              ],
            },
            material: Cesium.Color.BLACK.withAlpha(1)
            // material: new Cesium.Color(15 / 255.0, 38 / 255.0, 84 / 255.0, 0.3),
          },
        });
        const entity2 = new Cesium.Entity({
          id: 2,
          polyline: {
            clampToGround: true,
            positions: maskspoint,
            width: 5,
            // material: Cesium.Color.fromCssColorString('#6dcdeb'),
            material: methods.getColorRamp(
              [0.0, 0.045, 0.1, 0.15, 0.37, 0.54, 1.0],
              true
            ),
          },
        });
        window.viewer.entities.add(entity1);
        window.viewer.entities.add(entity2);
        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
        );
      },
      // 只展示geojson地图
      _c_add_geojson_area: function(geojson){
        let arr = geojson
        var polygonWithHole = new Cesium.PolygonGeometry({
            polygonHierarchy: new Cesium.PolygonHierarchy(
              Cesium.Cartesian3.fromDegreesArray([73.0, 53.0, 73.0, 0.0, 135.0, 0.0, 135.0, 53.0]), 
              [new Cesium.PolygonHierarchy(Cesium.Cartesian3.fromDegreesArray(arr))]
            )
        });
        var geometry = Cesium.PolygonGeometry.createGeometry(polygonWithHole);
        let instances = [];
        instances.push(new Cesium.GeometryInstance({
            geometry: geometry,
            attributes: {
                color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString("#081122"))
            }
        }));
        function addRect(instances, left, down, right, up) {
          instances.push(new Cesium.GeometryInstance({
            geometry: new Cesium.RectangleGeometry({
              rectangle: Cesium.Rectangle.fromDegrees(left, down, right, up)
            }),
            attributes: {
              color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString("#081122"))
            }
          }));
        }
        addRect(instances, -180.0, -90.0, 73.0, 90.0);
        addRect(instances, 135.0, -90.0, 180.0, 90.0);
        addRect(instances, 73.0, 53.0, 135.0, 90.0);
        addRect(instances, 73.0, -90.0, 135.0, 0.0);
        viewer.scene.primitives.add(new Cesium.Primitive({
          geometryInstances: instances,
          appearance: new Cesium.PerInstanceColorAppearance({
            flat: true,
            translucent: false
          })
        }));
      },
      getColorRamp(elevationRamp) {
        var ramp = document.createElement("canvas");
        ramp.width = 1;
        ramp.height = 100;
        var ctx = ramp.getContext("2d");

        var values = elevationRamp;
        var grd = ctx.createLinearGradient(0, 0, 0, 100);
        grd.addColorStop(values[0], "rgba(27,190,200,0.9)"); //black
        grd.addColorStop(values[1], "rgba(27,190,200,0.8)"); //blue
        grd.addColorStop(values[2], "rgba(27,190,200,0.7)"); //pink
        grd.addColorStop(values[3], "rgba(27,190,200,0.6)"); //red
        grd.addColorStop(values[4], "rgba(27,190,200,0.5)"); //orange
        grd.addColorStop(values[5], "rgba(27,190,200,0.4)"); //yellow
        grd.addColorStop(values[6], "rgba(27,190,200,0.3)"); //white

        ctx.fillStyle = grd;
        ctx.fillRect(0, 0, 1, 100);
        return ramp;
      },
      addMaskLayer(features,index) {
        const maskpointArray = [];   
        for (
          let i = 0;
          i < features.geometry.coordinates[0][0].length;
          i++
        ) {
          let coor = features.geometry.coordinates[0][0][i];
          maskpointArray.push(coor[0]);
          maskpointArray.push(coor[1]);
        }
        let maskspoint = Cesium.Cartesian3.fromDegreesArray(maskpointArray);
        const entity = new Cesium.Entity({
          polyline: {
            clampToGround: true,
            positions: maskspoint,
            width: 2,
            // material: Cesium.Color.fromCssColorString('#6dcdeb'),
            material: Cesium.Color.fromCssColorString("#0AF6F4"),
          },
        });
        window.viewer.entities.add(entity);
        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
          Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
        );
      },
      // 切换底图
      handlerChangeBasemap(obj) {
        if (data.baseLayerObj.type === obj.type) return false;
        data.baseLayerObj.state = 0;
        obj.state = 1;
        data.baseLayerObj = obj;
        let type = obj.type;
        let url = obj.proxiedUrl;
        let imageryLayerCollection = viewer.scene.globe._imageryLayerCollection;
        let layer = imageryLayerCollection.get(0);
        let imageryProvider;
        if (imageryLayerCollection.get(2)) {
          imageryLayerCollection.remove(imageryLayerCollection.get(2));
        }
        if (imageryLayerCollection.get(1)) {
          imageryLayerCollection.remove(imageryLayerCollection.get(1));
        }
        switch (type) {
          case "BINGMAP":
            imageryProvider = new Cesium.BingMapsImageryProvider({
              url: url,
              key: BING_MAP_KEY,
            });
            break;
          case "TIANDITU":
            let urlr =
              "http://{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" +
              TDT_KEY;
            imageryProvider = new Cesium.WebMapTileServiceImageryProvider({
              url: urlr,
              layer: "name",
              style: "default",
              format: "image/jpeg",
              maximumLevel: 18,
              tileMatrixSetID: "w",
              show: false,
              subdomains: ["t1", "t2", "t3", "t4", "t5", "t6", "t7", "t0"],
            });
            var TDT_CIA_W =
              "http://{s}.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0" +
              "&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
              "&style=default.jpg&tk=" +
              TDT_KEY;
            let labelProvider = new Cesium.WebMapTileServiceImageryProvider({
              // 影像注记
              url: TDT_CIA_W,
              subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
              layer: "cia_w",
              style: "default",
              format: "image/jpeg",
              tileMatrixSetID: "GoogleMapsCompatible",
            })
            imageryLayerCollection.addImageryProvider(labelProvider, 0);
            // imageryProvider = new Cesium.TiandituImageryProvider({url: url, token: TDT_KEY});

            break;
          case "IMAGE":
            imageryProvider = new Cesium.SingleTileImageryProvider({
              url: url,
            });
            break;
          case "OSM":
            imageryProvider = new Cesium.createOpenStreetMapImageryProvider({
              url: url,
            });
            break;
          case "MAPBOX":
            imageryProvider = new Cesium.MapboxImageryProvider({
              mapId: "mapbox.dark",
            });
            break;
          case "SUPERMAPDARK":
            imageryProvider = new Cesium.SuperMapImageryProvider({ url: url });
            break;
          case "SUPERMAPLIGHT":
            imageryProvider = new Cesium.SuperMapImageryProvider({ url: url });
            break;
          default:
            imageryProvider = new Cesium.SingleTileImageryProvider({
              url: url,
            });
            break;
        }
        imageryLayerCollection.addImageryProvider(imageryProvider, 0);
        imageryLayerCollection.remove(layer);
        // 地形STK地形

        // var provider = new Cesium.createWorldTerrain({
        //     token:"b6585bc41ee16251dbe6b1af64f375d9"
        // });
        // viewer.terrainProvider = provider;
        
        // var  terrainProvider = new Cesium.createWorldTerrain({
        //   url: "https://t{s}.tianditu.gov.cn/mapservice/swdx",
        //   key: "b6585bc41ee16251dbe6b1af64f375d9",
        //   subdomains: "01234567"
        // });
        // viewer.terrainProvider = terrainProvider;
        // var provider = new Cesium.TiandituTerrainProvider({
        //   token: "b6585bc41ee16251dbe6b1af64f375d9",
        // })
        //   // 加载地形数据
        //   viewer.terrainProvider = provider;
          
        // viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
        //   url: "http://223.99.16.253:8090/iserver/services/3D-fxdxt/rest/realspace/datas/费县%40fxdxt",
        //   isSct: true, //地形服务源自SuperMap iServer发布时需设置isSct为true
        //   invisibility: true,
        // });
        viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
          url: "http://data.mars3d.cn/terrain",
          requestWaterMask: false,
          requestVertexNormals: false,
          isSct: false,
          invisibility: false,
        });

        viewer.scene.globe.depthTestAgainstTerrain = true;
        Cesium.Credential.CREDENTIAL = new Cesium.Credential(SUPER_MAP_KEY); //令牌

        viewer.scene.sun.show = false;
        viewer.scene.moon.show = false;
        viewer.scene.skyBox.show = false; //关闭天空盒，否则会显示天空颜色
        viewer.scene.undergroundMode = true;
        viewer.scene.globe.show = true;
        viewer.scene.backgroundColor = new Cesium.Color(0, 0, 0, 0);
        viewer.scene.screenSpaceCameraController.minimumZoomDistance = 500;
        viewer.scene.screenSpaceCameraController.maximumZoomDistance = 5600000;


      },
      // 添加服务
      handlerLoadWebServer(obj) {
        methods.addWebServe(obj);
      },
      handlerDelLayer(obj) {
        if (obj.type == "S3M") {
          viewer.scene.layers.remove(obj.layersName);
        } else if (obj.type == "MVT") {
          window.viewer.scene.removeVectorTilesMap(obj.layersName);
        } else if (obj.type == "IMAGE") {
          let layerObj = data.imageryLayers.find((item) => {
            return item.name == obj.layersName;
          });
          layerObj.layer.show = false;
        } else if (obj.type == "OTHER") {
          let layerObj = data.sceneLayers.find((item) => {
            return item.name == obj.layersName;
          });
          if (layerObj) {
            layerObj.layer.forEach((item, index) => {
              layerObj.layer[index].visible = false;
            });
          }
        } else if (obj.type == "DataService") {
          data.dataserviceArr.forEach((item, index) => {
            viewer.entities.remove(data.dataserviceArr[index]);
          });
        }
      },
      // 显示点击获取的属性信息
      handlerSelectedEntityProperties() {
        data.roleInfo.MVTBubbleShow = false;
        let selectedEntity = window.viewer.selectedEntity;
        let pickResult = null;
        // pickResult = selectedEntity.pickResult ? selectedEntity.pickResult : null;
        if (selectedEntity.pickResult) {
          pickResult = selectedEntity.pickResult;
        } else {
          pickResult = null;
        }
        if (pickResult) {
          let pickkey = pickResult.layerID;
          let pickproperties = pickResult[pickkey][0].feature.properties;
          console.log("pickproperties", pickproperties);
          let tableData = [];
          if (JSON.stringify(pickproperties) == "{}") {
            tableData.push({
              name: "属性为空",
              value: "属性值为空",
            });
            data.roleInfo.tableDataList = tableData;
            data.roleInfo.MVTBubbleShow = true;
          } else {
            for (let key in pickproperties) {
              tableData.push({
                name: key,
                value: pickproperties[key],
              });
            }
            // 英文字段转中文字段
            tableData.forEach((item) => {
              data.attributeTableData.forEach((val) => {
                if (item.name == val.en_name) {
                  item.name = val.cn_name;
                }
              });
            });
            data.roleInfo.tableDataList = tableData;
            data.roleInfo.MVTBubbleShow = true;
          }
        } else {
        }
      },
      addWebServe(obj) {
        if (obj.type == "S3M") {
          // methods.getPosition(obj);
          let dataServiceUrl = obj.dataServiceUrl + "&token=" + SUPER_MAP_KEY;
          let dataSourceName = obj.dataSourceName;
          let dataSetName = obj.dataSetName;

          // 原始加载方式
          // let promises = viewer.scene.addS3MTilesLayerByScp(obj.layersUrl,{name: obj.layersName})

          // 新加载方式
          let urlScheme = obj.layersUrl.replace("223.99.16.253:9091", "{s}");
          urlScheme = urlScheme.replace("/datas/Combine/config", "");
          var config = {
            subdomainConfig: {
              // urlScheme:"http://{s}/iserver/services/3D-feixianLCQl19/rest/realspace",
              urlScheme: urlScheme,
              subdomains: [
                "223.99.16.253:9092",
                "223.99.16.253:9091",
                "223.99.16.253:8090",
                "223.99.16.253:9098",
              ],
            },
            name: obj.layersName,
            priorityScale: obj.priorityScale,
          };
          // http://223.99.16.253:9091/iserver/services/3D-feixianLCQl19/rest/realspace/datas/Combine/config
          let promises = viewer.scene.addS3MTilesLayerByScp(
            obj.layersUrl,
            config
          );

          promises.then(function (layer) {
            // layer.visible = false;

            // 显存释放代码
            //对倾斜摄影图层设置空间索引加载模式
            // let QXlayer = layer
            viewer.scene.debugShowFramesPerSecond = true; //帧率

            // 建立索引
            layer.LoadingPriority = Cesium.LoadingPriorityMode.UsePagedLodInfo; //大区域
            // layer.LoadingPriority=Cesium.LoadingPriorityMode.Child_Priority_NonLinear  //小区域

            // var layer = scene.layers.find('Config');//打开倾斜数据的Config图层
            layer.indexedDBSetting.isGeoTilesRootNodeSave = true; //设置是否保存根节点
            layer.residentRootTile = true; //设置根节点是否驻留内存不删除

            layer.clearMemoryImmediately = true; //及时释放内存（默认）

            //layer.indexedDBSetting.isGeoTilesSave = true;
            // layer.lodRangeScale(0.5);
            // layer.residentRootTile = false;
          });

          let layerReadyPromise = promises.readyPromise;
          Cesium.when(layerReadyPromise, function (data) {
            var bounds = promises.rectangle;
            if (obj.name == "费县老城区三维影像服务") {
              setTimeout(function () {
                
              }, 10000);
            }
          });

          /*　
              
            */

          // promises.setLodRangeScale(15)
          // methods.addS3mTilesLayer(
          //   dataServiceUrl,
          //   dataSourceName,
          //   dataSetName,
          //   promises
          // );
        } else if (obj.type == "MVT") {
          mvtMap = window.viewer.scene.addVectorTilesMap({
            url: obj.layersUrl,
            canvasWidth: 512,
            id: obj.id,
            viewer: window.viewer,
            name: obj.layersName,
            isOverlapDisplayed: true,
            index: obj.priorityScale,
          });
          //   mvtMap.refresh()

          let layerReadyPromise = mvtMap.readyPromise;
          console.log("mvtMapmvtMapmvtMap", mvtMap);
          Cesium.when(layerReadyPromise, function (data) {
            var bounds = mvtMap.rectangle;

            window.viewer.camera.flyTo({
              destination: bounds,
              orientation: {
                // heading: 0.09596697944080823,
                // pitch: -0.1854952805486341,
                // roll: 2.0370372055822372e-11
              },
            });
          });
        } else if (obj.type == "IMAGE") {
          let lobj = data.imageryLayers.find((item, index) => {
            return obj.layersName == item.name;
          });
          if (lobj) {
            lobj.layer.show = true;
            return;
          }
          let imageryLayers = window.viewer.imageryLayers;

          let provider_mec = new Cesium.SuperMapImageryProvider({
            // url:obj.layersUrl,
            url: "http://{s}/iserver/services/map-fxdt-4490/rest/maps/he1@fxdt-4490",
            name: obj.layersName,
            subdomains: [
              "223.99.16.253:9092",
              "223.99.16.253:9091",
              "223.99.16.253:8090",
            ],
          });
          let layerObj = {
            name: obj.layersName,
            layer: null,
          };
          layerObj.layer = imageryLayers.addImageryProvider(provider_mec);
          layerObj.layer.alpha = 1.0;
          data.imageryLayers.push(layerObj);
        } else if (obj.type == "管线") {
          let promise = window.viewer.scene.open(obj.layersUrl);
          Cesium.when(promise, function (layer) {
            // 设置相机位置，定位至模型
            window.viewer.scene.camera.setView({
              destination: new Cesium.Cartesian3(
                -2343784.953917227,
                4546449.518116666,
                3810304.124116188
              ),
              orientation: {
                heading: 4.750885487110618,
                pitch: -0.38228770591445227,
                roll: 1.0480505352461478e-13,
              },
            });

            let line = window.viewer.scene.layers.find("纯水绿色管道优化@管线");
            line.textureUVSpeed = new Cesium.Cartesian2(0, -2); //模型纹理在UV坐标上的运动速度
          });
        } else if (obj.type == "OTHER") {
          // 如果已添加过直接显示
          let layerObj = data.sceneLayers.find((item) => {
            return item.name == obj.layersName;
          });
          if (layerObj) {
            layerObj.layer.forEach((item, index) => {
              layerObj.layer[index].visible = true;
            });
            return;
          }
          // 如果没有添加新的服务
          let promises = viewer.scene.open(obj.layersUrl);
          let layerinfo = {};
          promises.then((layers) => {
            let handler = new Cesium.ScreenSpaceEventHandler(
              viewer.scene.canvas
            );
            handler.setInputAction(function (e) {
              // 首先移除之前添加标识实体
              viewer.entities.removeById("identify-area");

              let position = viewer.scene.pickPosition(e.position);
              // 从笛卡尔坐标获取经纬度
              let cartographic = Cesium.Cartographic.fromCartesian(position);
              let longitude = Cesium.Math.toDegrees(cartographic.longitude);
              let latitude = Cesium.Math.toDegrees(cartographic.latitude);
              let height = cartographic.height;

              let queryPoint = {
                // 查询点对象
                x: longitude,
                y: latitude,
              };


              let dataServiceUrl =
                obj.dataServiceUrl + "&token=" + SUPER_MAP_KEY;
              let dataSourceName = obj.dataSourceName;
              let dataSetName = obj.dataSetName;

              // methods.queryByPoint(
              //   dataServiceUrl,
              //   dataSourceName,
              //   dataSetName,
              //   queryPoint,
              //   position
              // );
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
            layerinfo.name = obj.layersName;
            layerinfo.layer = layers;
            data.sceneLayers.push(layerinfo);
          });
        } else if (obj.type == "DataService") {
          methods.addDataServe();
        }
      },
      getPosition(obj) {
        let mpath =
          obj.layersUrl.split("rest/")[0] +
          "rest/realspace/datas/Combine/config?token=" +
          SUPER_MAP_KEY;
        getMethodCommonMap(mpath).then((res) => {
          methods.flyTo(res.data);
        });
      },
      
      addS3mTilesLayer(dataServiceUrl, dataSourceName, dataSetName, promises) {
        promises.then(function (obliqueLayers) {
          let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
          handler.setInputAction(function (e) {
            // 首先移除之前添加标识实体
            viewer.entities.removeById("identify-area");
            // 获取点击位置笛卡尔坐标
            let position = viewer.scene.pickPosition(e.position);
            // 从笛卡尔坐标获取经纬度
            let cartographic = Cesium.Cartographic.fromCartesian(position);
            let longitude = Cesium.Math.toDegrees(cartographic.longitude);
            let latitude = Cesium.Math.toDegrees(cartographic.latitude);
            let height = cartographic.height;

            let queryPoint = {
              // 查询点对象
              x: longitude,
              y: latitude,
            };
            // methods.queryByPoint(
            //   dataServiceUrl,
            //   dataSourceName,
            //   dataSetName,
            //   queryPoint,
            //   position
            // );
          }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        });
      },
      // 通过点击查询用于表示单体化的面要素，添加到场景中高亮显示。
      queryByPoint(
        dataServiceUrl,
        dataSourceName,
        dataSetName,
        queryPoint,
        position
      ) {
        if (data.roleInfo.slotview) {
          return;
        }
        let queryObj = {
          getFeatureMode: "SPATIAL",
          spatialQueryMode: "INTERSECT",
          datasetNames: [dataSourceName + ":" + dataSetName],
          geometry: {
            id: 0,
            parts: [1],
            points: [queryPoint],
            type: "POINT",
          },
        };

        let queryObjJSON = JSON.stringify(queryObj); // 转化为JSON字符串作为查询参数
        viewer.scene.postRender.addEventListener(function () {
          let canvasHeight = viewer.scene.canvas.height;
          let windowPosition = new Cesium.Cartesian2();
          let scenePosition = position;
          new Cesium.SceneTransforms.wgs84ToWindowCoordinates(
            viewer.scene,
            scenePosition,
            windowPosition
          );
          data.roleInfo.bubbleBottom =
            canvasHeight - windowPosition.y + 45 + "px";
          data.roleInfo.bubbleLeft = windowPosition.x - 70 + "px";
        });

        postMethodCommonMap(dataServiceUrl, queryObjJSON).then((result) => {
          // 获取自然幢信息
          let resultObj = result.data;
          if (resultObj.featureCount > 0) {
            let tableData = []; // 气泡内的表格
            let resultFeature = resultObj.features[0];
            resultFeature.fieldNames.forEach((item, index) => {
              let ename = item;
              data.attributeTableData.forEach((val) => {
                if (val.en_name == item) {
                  item = val.cn_name;
                }
              });
              tableData.push({
                ename: ename,
                name: item,
                value: resultFeature.fieldValues[index],
              });
            });

            data.roleInfo.tableDataList = tableData;
            // data.roleInfo.BubbleShow = true

            methods.addClapFeature(resultObj.features[0]);

            // 获取不动产单元号 弹窗显示自然幢信息
            
          } else {
            data.roleInfo.BubbleShow = false;
          }
        });
      },
      // 将数据服务查询到的要素添加到场景中高亮显示，表示选中效果。
      addClapFeature(feature) {
        let lonLatArr = methods.getLonLatArray(feature.geometry.points);
        let currentEntity = viewer.entities.add({
          id: "identify-area",
          name: "单体化标识面",
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(lonLatArr),
            material: new Cesium.Color(1.0, 0.0, 0.0, 0.3),
            // classificationType: Cesium.ClassificationType.S3M_TILE // 贴在S3M模型表面
          },
        });
      },
      // 得到[经度,纬度,经度,纬度...]形式的数组，用于构造面。
      getLonLatArray(points) {
        let point3D = [];
        points.forEach(function (point) {
          point3D.push(point.x);
          point3D.push(point.y);
        });
        return point3D;
      },
      // 清除开场动画
      removeLoad() {
        setTimeout(() => {
          let loading = document.getElementById("loadingbar");
          if (loading) loading.remove(); //移除加载动画
        }, 1000);
      },
      // 添加服务飞行函数(公共服务配置好的定位)
      flyTo(obj) {

        let cameraParam = obj.position;
        // alert(cameraParam.x +"---"+cameraParam.y)
        if (cameraParam) {
          viewer.scene.camera.flyTo({
            // destination: new Cesium.Cartesian3.fromDegrees(
            //   117.982121,
            //   35.245274,
            //   600
            // ),
            destination: new Cesium.Cartesian3.fromDegrees(
              cameraParam.x,
              cameraParam.y,
              1000
            ),
            orientation: {
              heading: 0.09596697944080823,
              pitch: -1.5,
              roll: 2.0370372055822372e-11,
            },
          });
          return false;
        }
      },
      // 清除开场动画
      removeLoad() {
        setTimeout(() => {
          let loading = document.getElementById("loadingbar");
          if (loading) loading.remove(); //移除加载动画
        }, 1000);
      },
      // 搜索后定位
      searchFlyTo(obj, height) {
        let cameraParam = obj.position;
        if (cameraParam) {
          viewer.scene.camera.flyTo({
            destination: new Cesium.Cartesian3.fromDegrees(
              cameraParam.x,
              cameraParam.y,
              height
            ),
            orientation: {
              heading: 0.09596697944080823,
              pitch: -1.5,
              roll: 2.0370372055822372e-11,
            },
          });
          return false;
        }
      },
    };
    return {
      layerTreeLocal,
      ...data,
      ...methods,
    };
  },
});
</script>

<style scoped>
.cim-map {
  width: 100%;
  height: 100vh;
  padding: 0px;
}
#cesiumContainer{
  width: 100%;
  height: 100%;
}
</style>
