<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="handlerFlyTo"
          @handle-tool="handlerTool"
          @on-opacity-change="handlerChangeLayerOpecity"
      />
      <div class="cim-compon" style="position: absolute;top: 150px" :style="{'left': roleInfo.positionLeft + 'px' }" v-drag v-if="roleInfo.slotview">
        <img class="cim-component-close-img" @click="componentClose" src="/images/closex.png" alt="">
        <component  :is="roleInfo.slotview"></component>
      </div>
        <!-- <component  is="Sm3dMvtlayerStyle"></component> -->
  
      <!-- 气泡HTML -->
      <div class="bubblecontainer" :style="{'bottom':roleInfo.bubbleBottom,'left':roleInfo.bubbleLeft}" v-if="roleInfo.BubbleShow">
          <div id="tools" style="height:25px;">
              <span style="color: rgb(95, 74, 121);padding: 5px;position: absolute;left: 10px;top: 4px;">对象属性</span>
              <span style="color: rgb(95, 74, 121);padding: 5px;position: absolute;right: 10px;top: 4px;" @click="closeBubble">
                <img style="width: 20px;height: 20px;" src="/images/closex.png" />
              </span>
          </div>
          <div style="overflow-y:scroll;height:150px" id="tableContainer">
            <table id="tab">
              <tr v-for="(item,index) in roleInfo.tableDataList" :key="index">
                  <td>{{item.name}}</td>
                  <td class="ta-l">{{item.value}}</td>
              </tr>
            </table>
          </div>
      </div>
      <div class="bubblecontainer" :style="{'bottom':roleInfo.mvtbubbleBottom,'left':roleInfo.mvtbubbleLeft}" v-if="roleInfo.MVTBubbleShow">
          <div id="tools" style="height:25px;">
              <span style="color: rgb(95, 74, 121);padding: 5px;position: absolute;left: 10px;top: 4px;">对象属性</span>
              <span style="color: rgb(95, 74, 121);padding: 5px;position: absolute;right: 10px;top: 4px;" @click="closeMVTBubble">
                <img style="width: 20px;height: 20px;" src="/images/closex.png" />
              </span>
          </div>
          <div style="overflow-y:scroll;height:150px" id="tableContainer">
            <table id="tab">
              <tr v-for="(item,index) in roleInfo.tableDataList" :key="index">
                <td>{{item.name}}</td>
                <td class="ta-l">{{item.value}}</td>
              </tr>
            </table>
          </div>
      </div>
      <!-- 房屋信息 -->
      <div style="position: absolute;z-index: 9;right: 100px;top: 150px;"  v-if="roleInfo.houseInfoIsShow">
        <houseInfo @close="roleInfo.houseInfoIsShow = false"></houseInfo>
      </div>
  
      <div style="position: absolute;z-index: 9;left: 100px;top: 100px;" v-if="roleInfo.tabsToggleIsShow">
        <tablesinfo :tableDatas="tableDatas1"></tablesinfo>
      </div>
      <div style="position: absolute;z-index: 9;left: 100px;top: 350px;" v-if="roleInfo.tabsToggleIsShow">
        <barcharts  @close="roleInfo.tabsToggleIsShow = false"></barcharts>
      </div>
      <div style="position: absolute;z-index: 9;left: 100px;top: 650px;" v-if="roleInfo.tabsToggleIsShow">
        <piecharts  @close="roleInfo.tabsToggleIsShow = false"></piecharts>
      </div>
      <div style="position: absolute;z-index: 9;left: 500px;top: 650px;" v-if="roleInfo.tabsToggleIsShow">
        <linecharts  @close="roleInfo.tabsToggleIsShow = false"></linecharts>
      </div>
    </el-container>
    <!-- 行政区划 -->
    <el-select v-model="roleInfo.villageValue" class="m-2 villageDia" placeholder="Select" @change="villageChange" :style="{'left':roleInfo.posVisible?'450px':'50px'}">
      <el-option
        v-for="item in roleInfo.allVillageData"
        :key="item.name"
        :label="item.name"
        :value="item.name"
      />
    </el-select>
    <Loading/>
  </template>
  <script>
  /**
   * MAP_SERVER_CONFIG ：图层服务配置文件
   *
   * **/
  import {defineComponent, onMounted, reactive, ref, watch} from "vue";
  import { useRoute } from "vue-router";
  import {ElMessage} from 'element-plus'
  import Loading from "../loading/Loading.vue";
  import LayerTreeLocal from "./widget/layer-tree/toolTreeLocal.vue";
  import houseInfo from "./widget/echartsbox/houseinfo.vue";
  import tablesinfo from "./widget/echartsbox/tablesinfo.vue";
  import barcharts from "./widget/echartsbox/barcharts.vue";
  import piecharts from "./widget/echartsbox/piecharts.vue";
  import linecharts from "./widget/echartsbox/linecharts.vue";
  import {MAP_SERVER_CONFIG, DEFAULT_BASEMAP, TDT_KEY, BING_MAP_KEY, BASE_IMAGE_URL,SUPER_MAP_KEY,ZHENJIE_BORDER_SERVER } from '/public/config/server'
  import { postMethodCommonMap,getMethodCommonMap } from "../../api/mapcommon"
  import { postMethodCommon,getMethodCommon } from "../../api/common"
  import axios from 'axios'
  import xianjiegeojson from '../../../public/geojson/xianjie.json'
  import { get, set } from "@vueuse/core";
  
  import ZhenJieGeoJson from '../../../public/geojson/上冶镇镇界.json'
  import TaiPingZhenJieGeoJson from '../../../public/geojson/太平街道镇界.json'
  import ShangYeCunJieGeoJson from '../../../public/geojson/上冶村界.json'
  import TaiPingCunJieGeoJson from '../../../public/geojson/太平村界.json'
  
  export default defineComponent({
    components: {LayerTreeLocal, houseInfo, Loading, tablesinfo, barcharts,piecharts,linecharts},
  
    props: ['menuid','location','newPosition','layerVisible','showSearchPoint','currentImageLayerObj','drawPolygonRandom','deletePolygonRandom','currentShpfile','currentIserverLayer'],
    emits:["getBuildInfo","getHistoryCaseInfo","searchService"],
    setup(props,context) {
      const layerTreeLocal = ref(null)
      const data = reactive({
        initMap: 'Sm3dViewer',
        isFirstLoad:true,
        MAP_SERVER: MAP_SERVER_CONFIG,
        // MAP_TOOL: MAP_TOOL_CONFIG,
        baseLayerObj: {},
        roleInfo:{
          layersVisible: true,
          posVisible: props.location,
          positionLeft: '535',
          mapVisible: false,
          appId: '',
          slotview: '',
          BubbleShow: false,
          MVTBubbleShow: false,
          s3mvisible:false,
          bubbleBottom: 0,
          bubbleLeft: 0,
          mvtbubbleBottom: 0,
          mvtbubbleLeft: 0,
          tableDataList:[],
          houseInfoIsShow: false,
          tabsToggleIsShow: false,
          currentImageLayer:null,
          currentImageLayerCollection:null,
          historyImageLayers:[],
          handlerPoint:null,//绘图
          localShpfileArray:[],
          promise:null,
          villageValue: '请选择',
          allVillageData:[]
        },
        tableDatas1:{
          title: '实时汇聚',
          labesData: [
              { name: '单位名称' , field: 'name' },
              { name: '信息名称' , field: 'typename' },
              { name: '接入方式' , field: 'accesstype' },
              { name: '时间' , field: 'date' }
          ],
          tablesData:[
              { name: '民政局', typename: '服务机构' , accesstype: '网络接入' , date: '2020-8-1'},
              { name: '民政局', typename: '服务机构' , accesstype: '网络接入' , date: '2020-8-1'},
              { name: '民政局', typename: '服务机构' , accesstype: '网络接入' , date: '2020-8-1'},
              { name: '民政局', typename: '服务机构' , accesstype: '网络接入' , date: '2020-8-1'},
              { name: '民政局', typename: '服务机构' , accesstype: '网络接入' , date: '2020-8-1'},
              { name: '民政局', typename: '服务机构' , accesstype: '网络接入' , date: '2020-8-1'}
          ]
        },
        searchPoint:null,
        attributeTableData: null,
        imageryLayers:[],
        sceneLayers:[],
        dataserviceArr:[], //存放数据服务entity实体
        landmarkArr:[],//存放地标entity实体
        shangYeZhenVillage:[
            { lng: '117.93597265189402' , lat: '35.380373506599987' , name: '民义社区'},
            { lng: '117.91624646899473' , lat: '35.340906553926615' , name: '城南头社区'},
            { lng: '117.92267634909874' , lat: '35.405901894221167' , name: '兴国庄村'},
            { lng: '117.91930631116651' , lat: '35.418960309458917' , name: '仲口村'},
            { lng: '117.90770175083081' , lat: '35.394442635569831' , name: '仲口屯'},
            { lng: '117.91923780890082' , lat: '35.374924020969459' , name: '万仓'},
            { lng: '117.90201948978697' , lat: '35.383518989054693' , name: '永兴庄'},
            { lng: '117.91238976178046' , lat: '35.363066494586022' , name: '顺合村'},
            { lng: '117.92806665894146' , lat: '35.351974508172795' , name: '古城村'},
            { lng: '117.94243610294021' , lat: '35.366078080276232' , name: '西毕城'},
            { lng: '117.89253781539419' , lat: '35.372962652838844' , name: '东西沟村'},
            { lng: '117.87927016033062' , lat: '35.36071635054364' , name: '刘官庄'},
            { lng: '117.9687644071461' , lat: '35.380633083656633' , name: '双邱村'},
            { lng: '117.97653890696716' , lat: '35.366945726273421' , name: '平安曲池村'},
            { lng: '117.96243746365495' , lat: '35.369639950782002' , name: '大青太村'},
            { lng: '117.94926178104691' , lat: '35.396041782721788' , name: '上冶一村'},
            { lng: '117.95783300751999' , lat: '35.398256680371034' , name: '上冶二村'},
            { lng: '117.95494497459968' , lat: '35.406876993319244' , name: '上冶三村'},
            { lng: '117.96676493060492' , lat: '35.4055415293682' , name: '上冶四村'},
            { lng: '117.94565195670745' , lat: '35.402334367183521' , name: '上冶五村'},
            { lng: '117.96964392193436' , lat: '35.429616595475885' , name: '坝前村'},
            { lng: '117.95694610525472' , lat: '35.42015157588969' , name: '北村'},
            { lng: '117.95270347492897' , lat: '35.384023405253863' , name: '埠后'},
            { lng: '117.89947075167198' , lat: '35.353623581505516' , name: '蔡庄'},
            { lng: '117.96811138227814' , lat: '35.3928015354482' , name: '东岭'},
            { lng: '117.93189058662415' , lat: '35.392180069850227' , name: '里仁庄村'},
            { lng: '117.89930740691105' , lat: '35.339778426081487' , name: '姚河庄'},
            { lng: '117.94246534169937' , lat: '35.416965452823746' , name: '翟家村'},
        ],
        taiPingZhenVillage:[
          { lng: '118.47582822307281' , lat: '35.23880455881352' , name: '新兴村'},
          { lng: '118.48291977710664' , lat: '35.235186243886645' , name: '解庄村'},
          { lng: '118.49291538508949' , lat: '35.232033169728901' , name: '毛官庄村'},
          { lng: '118.48575822083173' , lat: '35.226189124513056' , name: '白塔街村'},
          { lng: '118.49376064444935' , lat: '35.219754220045168' , name: '大姚家庄村'},
          { lng: '118.46800022524612' , lat: '35.214595803443075' , name: '东王庄村'},
          { lng: '118.47942469983963' , lat: '35.210860562110192' , name: '前姚家庄村'},
          { lng: '118.49476563132983' , lat: '35.207527096876987' , name: '东南白塔村'},
          { lng: '118.46133779869396' , lat: '35.204209023552579' , name: '沙岭子村'},
          { lng: '118.47959609673848' , lat: '35.198428655388838' , name: '罗家官庄村'},
          { lng: '118.4950208597713' , lat: '35.19354211308103' , name: '光沂庄村'},
          { lng: '118.44746369242263' , lat: '35.190615944799326' , name: '徐太平村'},
          { lng: '118.47559265231875' , lat: '35.18863368240541' , name: '郭太平村'},
          { lng: '118.4602848708838' , lat: '35.191495121574455' , name: '郭家街村'},
          { lng: '118.46064226952723' , lat: '35.184287080601202' , name: '王太平村'},
          { lng: '118.45215532947942' , lat: '35.180453197828164' , name: '申太平村'},
          { lng: '118.49805515126356' , lat: '35.181234828150401' , name: '八间屋村'},
          { lng: '118.42467877228241' , lat: '35.168450112659485' , name: '亭子头村'},
          { lng: '118.44403207255966' , lat: '35.172331888192851' , name: '大太平村'},
          { lng: '118.47104175109915' , lat: '35.174342966347467' , name: '东张屯村'},
          { lng: '118.47848210843725' , lat: '35.165133492504879' , name: '大张家寨子'},
          { lng: '118.44790120267386' , lat: '35.159196614937933' , name: '东水湖崖村'},
          { lng: '118.48505660411115' , lat: '35.158692723667343' , name: '沙岭官庄村'},
          { lng: '118.43712361193153' , lat: '35.15254408396774' , name: '西水湖崖村'},
          { lng: '118.45955024381303' , lat: '35.153266948252551' , name: '大刘家寨子村'},
          { lng: '118.48231762382019' , lat: '35.153521841203229' , name: '大徐家寨子村'},
          { lng: '118.45988461262529' , lat: '35.147300958256395' , name: '小徐家寨子村'},
          { lng: '118.48444987447776' , lat: '35.151034241783776' , name: '郭家寨子'},
          { lng: '118.47670128232397' , lat: '35.147440402385399' , name: '尹家寨子村'},
          { lng: '118.47025870710155' , lat: '35.145153788305272' , name: '小刘家寨子村'},
          { lng: '118.45554800903953' , lat: '35.142981539921976' , name: '葛家寨子村'},
          { lng: '118.46936463606109' , lat: '35.14059201135111' , name: '小张家寨子村'},
          { lng: '118.4439030631636' , lat: '35.142186348648444' , name: '陈家庄村'},
        ]
      })
      const route = useRoute();
      watch(
        ()=>props.drawPolygonRandom,
         (newVal, oldVal) => {
           methods.drawPolygon();
          }
      )
      watch(
        ()=>props.currentShpfile,
        (newVal,oldVal)=>{
          methods.addLocalShpfile(props.currentShpfile);
        },
        {deep: true}
      )
      watch(
        ()=>props.currentIserverLayer,
        (newVal,oldVal)=>{
        
          if(props.currentIserverLayer.state == 1){
            methods.addWebServe(props.currentIserverLayer);
          }else{
            methods.handlerDelLayer(props.currentIserverLayer);
          }
          // methods.addLocalShpfile(props.currentIserverLayer);
        },
        {deep: true}
      )
      
      watch(
        ()=>props.deletePolygonRandom,
         (newVal, oldVal) => {
           methods.deletePolygon();
           
          }
      )
      watch(
        () => props.menuid,
        (newVal, oldVal) => {
          if(newVal.key){
            methods.componentClose()
          }else{
            data.roleInfo.slotview = newVal.id
          }
        }
      )
      watch(
        ()=>props.currentImageLayerObj,
        (newVal, oldVal) => {
           
            methods.changeSpaceTimeImageLayer(props.currentImageLayerObj);
        }
      )
      watch(
        ()=>props.showSearchPoint,
        (newVal,oldVal)=>{
          if(newVal == false){
            if(data.searchPoint){
              viewer.entities.remove(data.searchPoint);
            }
          }
        }
      )
       watch(   //监听搜索点结果 进行定位跳转
        () => props.newPosition,
        (newVal, oldVal) => {
          let coor = newVal.lonlat.split(",");
  
          if(data.searchPoint != null){
            viewer.entities.remove(data.searchPoint);
          }
  
          data.searchPoint = new Cesium.Entity({
            position:Cesium.Cartesian3.fromDegrees(parseFloat(coor[0]),parseFloat(coor[1])),
            billboard:{
              image:"/images/mapsearchicon.png",
              height:40,
              width:40,
              scale:1,
              pixelSize:20,
              heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
              show:true,
              disableDepthTestDistance:99000000,
              clampToGround: true,
            },
            label:{
              text:newVal.name,
              font : '12pt monospace',
              style : Cesium.LabelStyle.FILL_AND_OUTLINE,
              color :Cesium.Color.WHITE,
              outlineColor:Cesium.Color.BLACK,
              outlineWidth : 2,
              pixelOffset:new Cesium.Cartesian2(0,-40),
              heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
              disableDepthTestDistance:99000000,
              clampToGround: true,
            },
          })
          viewer.entities.add(data.searchPoint);
          // 跳转到搜索的点Entity实体
          // window.viewer.flyTo(data.searchPoint,{duration:5});
            window.viewer.camera.flyTo({
              destination: new Cesium.Cartesian3.fromDegrees(parseFloat(coor[0]),parseFloat(coor[1])-0.002, 500),
              orientation:{
                // heading: 0.19596697944080823,
                pitch: -0.99
                // roll: 2.0370372055822372e-11
              }
            })
              
  
        }
      )
      watch(
        () => props.location,
        (newVal, oldVal) => {
          data.roleInfo.posVisible = newVal
          if(!newVal){
            data.roleInfo.positionLeft = '135'
          }else{
            data.roleInfo.positionLeft = '535'
          }
        }
      )
      watch(
        () => props.layerVisible,
        (newVal, oldVal) => {
          data.roleInfo.layersVisible = !data.roleInfo.layersVisible
        }
      )
      onMounted(() => {
        if(route.query.type == 'shangyezhen'){
          data.roleInfo.allVillageData = data.shangYeZhenVillage
          data.roleInfo.villageValue = "上冶镇"
          let obj = {
            position:{
              x: 117.90682,
              y: 35.22804,
              z: 0
            }
          }
          methods.searchFlyTo(obj,12000)
        }
        if(route.query.type == 'taipingzhen'){
          data.roleInfo.allVillageData = data.taiPingZhenVillage
          data.roleInfo.villageValue = "太平镇"
          let obj = {
              x: 118.50105,
              y: 35.07507,
              z: 0
          }
          viewer.scene.camera.flyTo({
              destination: new Cesium.Cartesian3.fromDegrees(obj.x, obj.y, 10000),
              orientation:{
                heading: -0.29596697944080823,
                pitch: -0.7,
                roll: 2.0370372055822372e-11
              },
              duration: 0.5,
            });
        }
        
        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)
            
            
          }else{
            ElMessage({
              message: '在线底图配置不正确',
              type: 'warning',
            })
          }
        }
        
        
  
        setTimeout(function(){
          data.roleInfo.appId = route.query.id
          methods.controlViewer();
          methods.getBoundServerData()
          methods.getAttributeList()
          methods.addPointMask()
          
        },1000)
      })
      /**
       * methods方法
       * 
       * 
       * 
       *  ————  handlerChangeBasemap 切换底图
       *  ————  handlerLoadWebServer  添加服务图层
       * **/
      const methods = {
        villageChange(e){
          data.roleInfo.allVillageData.forEach(item =>{
            if(item.name == e){
              viewer.scene.camera.flyTo({
                destination: new Cesium.Cartesian3.fromDegrees(item.lng, item.lat, 2000),
                duration: 2
              });
            }
          })
        },
        //上冶镇标注
        addPointMask(){
          data.roleInfo.allVillageData.forEach(item =>{
            viewer.entities.add({
              position: Cesium.Cartesian3.fromDegrees(item.lng, item.lat, 0),
              // 文字
              label: {
                // 文本。支持显式换行符“ \ n”
                text: item.name,
                // 字体样式，以CSS语法指定字体
                font: '10pt Source Han Sans CN',
                // 字体颜色
                fillColor: Cesium.Color.WHITE,
                // 相对于坐标的水平位置
                verticalOrigin: Cesium.VerticalOrigin.CENTER,
                // 相对于坐标的水平位置
                horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
                pixelOffset: new Cesium.Cartesian2(10, 0),
                // 显示在距相机的距离处的属性，多少区间内是可以显示的
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 28000),
                // 是否显示
                show: true,
                clampToGround: true,
              }
            });
          })
        },
        changeSpaceTimeImageLayer(obj){
            // 如果是关闭历史影像或者删除历史影像 就删除当前历史影像图层
            if(obj == 'delete'){
              // 循环删除所有图层
              for(let i=0;i<data.roleInfo.historyImageLayers.length;i++){
                data.roleInfo.currentImageLayerCollection.remove(data.roleInfo.historyImageLayers[i].layer,true);
              }
              return;
            }
  
            //当前
           data.roleInfo.currentImageLayerCollection = window.viewer.imageryLayers;
        
            //查找当前图层是否已经添加到地球
            let currentHistoryLayer = data.roleInfo.historyImageLayers.find((item,index)=>{
              return item.id == obj.id;
            })
  
            if(currentHistoryLayer){
              for(let i=0;i<data.roleInfo.historyImageLayers.length;i++){
                if(data.roleInfo.historyImageLayers[i].id == currentHistoryLayer.id){
                  data.roleInfo.historyImageLayers[i].layer.show = true;
                }else{
                  data.roleInfo.historyImageLayers[i].layer.show = false;
                }
               
              }
            }else{
              for(let i=0;i<data.roleInfo.historyImageLayers.length;i++){
                data.roleInfo.historyImageLayers[i].layer.show = false;
              }
              //如果没有就添加
              let historyLayer = {
                id:obj.id,
                layer:null,
              }
              //如果没有历史影像 添加新的历史影像
              let provider_mec = new Cesium.SuperMapImageryProvider({
                  url:obj.url,
                  name:obj.id
              });
              historyLayer.layer = data.roleInfo.currentImageLayerCollection.addImageryProvider(provider_mec);
              data.roleInfo.historyImageLayers.push(historyLayer);
              
            }
  
          
  
            // //判断图层是否存在如果存在就隐藏当前图层
            // if(currentHistoryLayer){
            //   console.log("currentHistoryLayer",data.roleInfo.historyImageLayers,currentHistoryLayer);
            //   currentHistoryLayer.layer.show = false;
            // }else{
  
              
            // }
  
           
  
            return;
  
            if(data.roleInfo.currentImageLayer == null){
              // imageLayerCollection imageLayer集合
              data.roleInfo.currentImageLayerCollection = window.viewer.imageryLayers;
              let provider_mec = new Cesium.SuperMapImageryProvider({
                  url:obj.url,
                  name:obj.name
              });
              data.roleInfo.currentImageLayer = data.roleInfo.currentImageLayerCollection.addImageryProvider(provider_mec);
              console.log("noaddImageryProvider",data.roleInfo.currentImageLayer);
            }else{
              data.roleInfo.currentImageLayerCollection.remove(data.roleInfo.currentImageLayer,true);
  
              data.roleInfo.currentImageLayer = null;
              let opacity = 1;
              let currentOpacity = 0;
  
              let provider_mec = new Cesium.SuperMapImageryProvider({
                  url:obj.url,
                  name:obj.name
              });
  
              data.roleInfo.currentImageLayer = data.roleInfo.currentImageLayerCollection.addImageryProvider(provider_mec);
  
              console.log("addImageryProvider",data.roleInfo.currentImageLayer);
  
  
            return;
              layer.alpha = 0;
  
              console.log("data.roleInfo.currentImageLayerCollection",data.roleInfo.currentImageLayerCollection);
              let timer = setInterval(function(){
                opacity = opacity - 0.1;
                currentOpacity = currentOpacity + 0.1;
                if(opacity <= 0){
                  clearInterval(timer);
                  
                  // alert(data.roleInfo.currentImageLayerCollection.length);
                  data.roleInfo.currentImageLayer = layer;
                  data.roleInfo.currentImageLayer.alpha = 1;
                }else{
                  layer.alpha = currentOpacity;
                  data.roleInfo.currentImageLayer.alpha = opacity;
                }
              },150)
            }
           
            // layerObj.layer.alpha = 1.0;
        },
        //controlViewer
        controlViewer(){
          let minPitch = -Cesium.Math.PI_OVER_TWO;
          let maxPitch = 0;
          let minHeight = 200;
          viewer.camera.changed.addEventListener(
            function(){
              if(viewer.camera._suspendTerrainAdjustment && viewer.scene.mode === Cesium.SceneMode.SCENE3D) {
                viewer.camera._suspendTerrainAdjustment = false;
                viewer.camera._adjustHeightForTerrain();
              }
              let pitch = viewer.camera.pitch;
              if (pitch > maxPitch || pitch < minPitch) {
                viewer.scene.screenSpaceCameraController.enableTilt = false;
                if(pitch > maxPitch) {
                   pitch = maxPitch
                }else if(pitch < minPitch) {
                  pitch = minPitch
                }
                var destination = Cesium.Cartesian3.fromRadians(
                  viewer.camera.positionCartographic.longitude,
                  viewer.camera.positionCartographic.latitude,
                  Math.max(viewer.camera.positionCartographic.height, minHeight))
                  viewer.camera.setView({
                    destination: destination,
                    orientation: { pitch: pitch }
                  })
                  viewer.scene.screenSpaceCameraController.enableTilt = true;
              }
            }
          )
        },
        componentClose(){
          data.roleInfo.slotview = ''
          viewer.scene.multiViewportMode = Cesium.MultiViewportMode['NONE'];  //去除分屏
          // viewer.scene.primitives.removeAll()  //去除粒子特效
        },
        getAttributeList(){
          let param = {
            isLimit:true,
            page: 1,
            limit: 10000,
            key: "",
            name:"",
          }
          postMethodCommon("/CimEncndesc/Load",param).then(res=>{
            if(res.code == 200){
              data.attributeTableData = res.data;
            }
          })
        },
        handlerTool(){
          context.emit('handle-tool')
        },
        closeBubble(){
          data.roleInfo.BubbleShow = false
        },
        closeMVTBubble(){
          data.roleInfo.MVTBubbleShow = false
        },
        getBoundServerData(){
            data.MAP_SERVER[1].children = []
            postMethodCommon("/CimApplication/GetCimAppServiceById?AppId="+data.roleInfo.appId).then(res =>{
                let arr = []
                res.result.forEach((item,index) =>{
                  if(item.data_service_url){
                    arr.push({
                      dataServiceUrl: item.data_service_url,
                      dataSetName: item.data_set_name,
                      dataSourceName: item.data_source_name,
                      id: item.id,
                      coverImg:item.coverImg,
                      layersName: item.id,
                      dataType: item.data_type,
                      layersUrl: item.url,
                      name: item.name,
                      parentId: "webServe",
                      proxiedUrl: item.url,
                      state: 0,
                      sort: item.sort,
                      type: item.service_type_value,
                      type_name: item.big_type_name
                    })
                  }else{
                    arr.push({
                      dataServiceUrl: item.data_service_url,
                      dataSetName: item.data_set_name,
                      dataSourceName: item.data_source_name,
                      coverImg: item.coverImg,
                      id: item.id,
                      dataType: item.data_type,
                      layersName: item.id,
                      layersUrl: item.url,
                      name: item.name,
                      parentId: "webServe",
                      proxiedUrl: item.url,
                      state: 0,
                      sort: item.sort,
                      type: item.service_type_value,
                      type_name: item.big_type_name
                    })
                  }
                })
                arr.forEach((item,index) =>{
                  if(item.coverImg){
                    item.image = BASE_IMAGE_URL + '/' + item.coverImg
                  }else{
                    item.image = '/img/webServeImg/'+index+'.png'
                  }
                })
                if(res.result.length==0){
                  arr.push({
                    state: 1,
                    name: '暂无数据',
                    parentId: "webServe",
                    image: '/images/baseLayer/SuperMapLight.jpg'
                  })
                }
                // let firstLayer = null;
                // for(let i=0;i<arr.length;i++){
                //   if(arr[i].name == '费县乡镇界线'){
                //     firstLayer = arr[i];
                //     firstLayer.opacity = 50;
                //     arr.splice(i, 1);
                //     break;
                //   }
                // }
                // arr.unshift(firstLayer);
                let arr1 = []
                arr.forEach(item =>{
                  if(!item.name.includes("高清影像")){
                      arr1.push(item)
                    }
                })
                arr.forEach(item =>{
                  if(item.name.includes("高清影像")){
                      arr1.push(item)
                    }
                })
                arr1.forEach((item,index) =>{
                  item.priorityScale = arr1.length - index
                  if(item.type == 'S3M'){
                    // arr1[index].state = 1
                  }
                })
              
                arr1[arr1.length-1].state = 1
              
                data.MAP_SERVER[1].children = arr1
                data.roleInfo.mapVisible = true
                methods.addWebServe(arr1[arr1.length-1])
  
                arr.forEach(item =>{
                  if(item.type == 'S3M'){
                    // methods.addWebServe(item)
                  }
                  
                })
  
            })
        },
        // 切换底图
        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));
          }
  
          // let  labelayer = new Cesium.TiandituImageryProvider({
          //     mapStyle: Cesium.TiandituMapsStyle.CIA_C, // 天地图全球中文注记服务
          //     token: TDT_KEY,
          //   })
          // imageryLayerCollection.addImageryProvider(labelayer)
          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",
                  tileMatrixSetID: "w",
                  show: false,
                  subdomains:['t1','t2','t3','t4','t5','t6','t7','t0']
                });
  
              
              // 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.TiandituTerrainProvider({
          //     token:"b6585bc41ee16251dbe6b1af64f375d9"
          // });
  
          // viewer.terrainProvider = provider;
          
          // 添加底图
          let layers = viewer.scene.imageryLayers;
  
          layers.addImageryProvider(new Cesium.MapboxStyleImageryProvider({
            // url: 'https://api.mapbox.com/styles/v1',
            // username: 'xujingliang',
            // styleId: 'cli9o6tl500zh01r8fpbx2n1s',
            accessToken: 'pk.eyJ1IjoieHVqaW5nbGlhbmciLCJhIjoiY2w3bzFzZnZqMjdieTN1cG92N2I1d2huOSJ9.aQqMz4S-cTziUYizIH_gNg',
            scaleFactor: false,
            show: false
          }));
  
          // layers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
          //   subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          //     url: "https://t{s}.tianditu.gov.cn/cva_w/wmts?tk=b6585bc41ee16251dbe6b1af64f375d9&service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",
          //     layer: "tdtAnnoLayer",
          //     style: "default",
          //     format: "image/jpeg",
          //     show: true
          //   })
          // )
  
  
          viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
              url : "http://223.99.16.253:8090/iserver/services/3D-fxdxt/rest/realspace/datas/%E8%B4%B9%E5%8E%BF%40fxdxt",
              isSct : true,//地形服务源自SuperMap iServer发布时需设置isSct为true
              invisibility:true
  
              // url: 'https://www.supermapol.com/realspace/services/3D-stk_terrain/rest/realspace/datas/info/data/path',
              // url:"http://223.99.16.253:8090/iserver/services/3D-fxdxt/rest/realspace/datas/费县%40fxdxt",
              // isSct: false
          });
          viewer.scene.globe.depthTestAgainstTerrain = false;
          Cesium.Credential.CREDENTIAL = new Cesium.Credential(SUPER_MAP_KEY);  //令牌
  
          // var carto=new Cesium.Cartographic.fromDegrees(lon,lat);　　//输入经纬度
          // var h2=viewer.scene.sampleHeight(carto);
  
        },
        //加载村界
        drawLineLayer(){
          let coords
          
          if(route.query.type == 'shangyezhen'){
            coords = ShangYeCunJieGeoJson.features;
          }else{
            coords = TaiPingCunJieGeoJson.features;
          }
  
          
          coords.forEach((item,index)=>{
            let position = [];
            item.geometry.rings[0].forEach(val =>{
              position.push(val[0],val[1])
            })
            
            viewer.entities.add({
              id: item.attributes.BSM,
              polyline: {
                // fromDegrees返回给定的经度和纬度值数组（以度为单位），该数组由Cartesian3位置组成。
                // Cesium.Cartesian3.fromDegreesArray([经度1, 纬度1, 经度2, 纬度2,])
                // Cesium.Cartesian3.fromDegreesArrayHeights([经度1, 纬度1, 高度1, 经度2, 纬度2, 高度2])
                positions: Cesium.Cartesian3.fromDegreesArray(position),
                // 宽度
                width: 2,
                // 线的颜色 
                material: Cesium.Color.fromCssColorString('rgba(255,191,2, 0.8)'),
                // 显示在距相机的距离处的属性，多少区间内是可以显示的
                distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 100000),
                disableDepthTestDistance:99000000,
                clampToGround: true,
                // 是否显示
                show: true
              }
            });
          })
          
          
        },
        // 加载立体墙效果
        drawWallLayer() {
          let coords 
          if(route.query.type == 'shangyezhen'){
            coords = ZhenJieGeoJson.features[0].geometry.coordinates[0];
          }else{
            coords = TaiPingZhenJieGeoJson.features[0].geometry.coordinates[0];
          }
          let position = [];
          coords[0].forEach((item,index)=>{
            position.push(item[0],item[1],100)
          })
            
          viewer.entities.add({
              show: true,
              name: "fire-poi",
              wall: {
                  positions: Cesium.Cartesian3.fromDegreesArrayHeights(position),
                  shadows: Cesium.ShadowMode.ENABLED,
                  // material: methods.getColorRamp([0.0, 0.045, 0.1, 0.15, 0.37, 0.54, 1.0],true),
                  material: new Cesium.ImageMaterialProperty({
                      image:'/images/wall-2.png',
                  }),
                  heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                  disableDepthTestDistance:99000000,
                  clampToGround: true,
                  fill: true,     // 是否被提供的材质填充
              },
          });
          
  
        },
  
        // 添加服务
        handlerLoadWebServer(obj) {
         
          data.roleInfo.BubbleShow = false
          data.roleInfo.MVTBubbleShow = false
          methods.addWebServe(obj)
        },
        handlerDelLayer(obj){
          console.log('oooooooo',obj)
          data.roleInfo.BubbleShow = false
          data.roleInfo.MVTBubbleShow = false
          if(obj.type == 'S3M'){
            viewer.scene.layers.remove(obj.layersName)
            data.landmarkArr.forEach((item,index)=>{
              viewer.entities.remove(data.landmarkArr[index])
            })
            data.roleInfo.s3mvisible = false
          }else if(obj.type == 'MVT'){
            window.viewer.scene.removeVectorTilesMap(obj.layersName);
            // if(viewer.scene.layers.find('1718895930196885504').coverImageryLayer){
            //   viewer.scene.layers.find('1718895930196885504').coverImageryLayer=''
            // }
          }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
            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
                  }
                })
              })
              let arr = []
              tableData.forEach(item =>{
                if(item.name!=='图层id'&&item.name!=='SMUSERID'&&item.name!=='SMAREA'&&item.name!=='SMPERIMETER'&&item.name!=='SMGEOMETRY'&&item.name!=='Id'&&item.name!=='用户ID'){
                  arr.push(item)
                }
              })
              
              let obja = {}
  
              arr.forEach((item, index) => {
                if (item.name == '姓名') {
                  obja = item
                  arr.splice(index, 1)
                    return
                }
              })
              arr.unshift(obja)
              data.roleInfo.tableDataList = arr
              data.roleInfo.MVTBubbleShow = true
            }
          }else{
  
          }
        },
        // 如果是违建专题加载违建图斑数据
        addHistoryCaseLayer(){
          // 读取违建图斑geojson文件 绘制违建图斑
          for(let i=0;i<historycasegeojson.features.length;i++){
            let points = [];
            historycasegeojson.features[i].geometry.coordinates[0][0].forEach((item,index)=>{
              let obj = {
                x:item[0],
                y:item[1]
              }
              points.push(obj);
            })
            let lonLatArr = methods.getLonLatArray(points);
            viewer.entities.add({
                id: "illegal"+i,
                name: historycasegeojson.features[i].properties.Id,
                polygon: {
                    hierarchy: Cesium.Cartesian3.fromDegreesArray(lonLatArr),
                    fill:true,
                    material: new Cesium.Color(1.0, 0.0, 0.0,0.3),
                    // material:Cesium.Color.RED.withAlpha(0.1),
                    //  clampToGround: true,
                    // heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                    classificationType: Cesium.ClassificationType.S3M_TILE // 贴在S3M模型表面
                },
                heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
            });
            viewer.entities.add({
                id: "illegal-line"+i,
                name: historycasegeojson.features[i].properties.Id,
                polyline: {
                    fill:true,
                    positions: Cesium.Cartesian3.fromDegreesArray(lonLatArr),
                    width:2,
                    material: new Cesium.Color(1.0, 0.0, 0.0, 1),
                    heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                    clampToGround: true,
                },
            });
          }
          // 添加点击事件 如果点击获取到的实体类中有“illega”则获取id属性 进行违建数据查询
          let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
          handler.setInputAction(function(movement) {
              let pick = viewer.scene.pick(movement.position);
            
              if(pick && pick.id._name){
                let case_id = pick.id._name
                // 查询案件记录
                if(pick.id._id.match("illega")){
                  methods.getHistoryCaseInfo(case_id);
                }else{
                  return null;
                }
              }
          },Cesium.ScreenSpaceEventType.LEFT_CLICK);
        },
        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(){
          const maskpointArray = []
          let features = ZhenJieGeoJson.features;
            for (let i = 0; i < features[0].geometry.coordinates[0][0].length; i++) {
                let coor = features[0].geometry.coordinates[0][0][i];
                maskpointArray.push(coor[0]);
                maskpointArray.push(coor[1]);
            }
            
            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.BLUE.withAlpha(0.1)
                material:new Cesium.Color(15 / 255.0, 38 / 255.0, 84 / 255.0, 1)
              }
            })
            const entity2 = new Cesium.Entity({
              id: 2,
              polyline: {
                clampToGround: true,
                positions: maskspoint,
                width: 10,
                // material: Cesium.Color.fromCssColorString('#0EF8EC'),
                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);
        
        },
        // 加载镇边界MVT图层 穿透显示
        addZhenJieMvtLayer(){
          window.viewer.scene.addVectorTilesMap({
            url: ZHENJIE_BORDER_SERVER,
            canvasWidth: 512,
            viewer:window.viewer,
            name:"zhenjiexian",
            // mapboxStyle:{
            //   version:8,
            //   name:"zhenjiestyle",
            //   metadate:{      
            //     "mapbox:name":"demo"
            //   },
            //   "paint": { // 绘制类属性  //分类数据展示 文章数据展示 标签数据展示 链接数据展示 用户数据展示 
            //       "fill-antialias": true, // 填充时是否反锯齿（可选，默认值为 true）
            //       "fill-opacity": 1, // 填充的不透明度（可选，取值范围为 0 ~ 1，默认值为 1）
            //       "fill-pattern": "", // 填充用的图案（可选，这里填写在 sprite 雪碧图中图标名称。为了图案能无缝填充，图标的高宽需要是 2 的倍数）
            //       "fill-color": "#000000", // 填充的颜色（可选，默认值为 #000000。如果设置了 fill-pattern，则 fill-color 将无效）
            //       "fill-outline-color": "#000000", // 描边的颜色（可选，默认和 fill-color 一致。如果设置了 fill-pattern，则 fill-outline-color 将无效。为了使用此属性，还需要设置 fill-antialias 为 true）
            //       "fill-translate": [0, 0], // 填充的平移（可选，通过平移 [x, y] 达到一定的偏移量。默认值为 [0, 0]，单位：像素。）
            //       "fill-translate-anchor": "map" // 平移的锚点，即相对的参考物（可选，可选值为 map、viewport，默认为 map）
            //   }
            // }
  
            // 分类数据展示 
  
  
  
          });
        },
        addDataServe(){//name,url,datasource,features
              axios.post("http://223.99.16.253:8090/iserver/services/data-wushui/rest/data/featureResults.rjson?returnContent=true",
               {"datasetNames":["wushui:点要素_2000"],"getFeatureMode":"SQL","queryParameter":{"attributeFilter":"SMID<500"}}
              ).then(res=>{
                if(res.data.features.length>0){
                  res.data.features.forEach((item,index)=>{
                     let entity = new Cesium.Entity({
                        position:Cesium.Cartesian3.fromDegrees(parseFloat(item.geometry.center.x),parseFloat(item.geometry.center.y)),
                        billboard:{
                          image:"/images/wushui.png",
                          height:40,
                          width:40,
                          scale:1,
                          pixelSize:20,
                          heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                          show:true,
                        },
                        label:{
                          text:"",
                          font : '14pt monospace',
                          style : Cesium.LabelStyle.FILL_AND_OUTLINE,
                          color :Cesium.Color.WHITE,
                          outlineColor:Cesium.Color.BLACK,
                          outlineWidth : 2,
                          pixelOffset:new Cesium.Cartesian2(0,0),
                          heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                        },
                      })
                      data.dataserviceArr.push(entity);
                      viewer.entities.add(entity);
                  })
                }
                
              })
        },
         addCommunityEntity(){
          let list = [
            {
              position:[117.913513,35.362111],
              name:"顺河村"
            },{
              position:[117.919537,35.342111],
              name:"城南头社区",
            }, {
              position:[117.936454,35.380893],
              name:"民义社区"
            }, {
              position:[117.911806,35.39689],
              name:"仲口村",
            },{
              position:[117.884215,35.361263],
              name:"刘官庄"
            },{
              position:[117.940513,35.393580],
              name:"里仁庄村"
            }
            
          ];
          let canvasArr=[];
          for(let i=0;i<list.length;i++){
                list[i].height = 0;
                // 经纬度转笛卡尔
                var position3 = new Cesium.Cartographic(Cesium.Math.toRadians(list[i].position[0]),Cesium.Math.toRadians(list[i].position[1]));
             
                //获取模型高度
              
                list[i].height = window.viewer.scene.sampleHeight(position3);
                canvasArr[i] = document.createElement('canvas');
                canvasArr[i].width = 150;
                canvasArr[i].height = 30;
                // canvasArr[i].getContext('2d');
                 let ctx = canvasArr[i].getContext('2d');
                   //矩形
                  var g=ctx.createLinearGradient(0,0,40,0);
                  g.addColorStop(0,'rgba(0,0,0,0.4)');
                  g.addColorStop(1,'rgba(0,0,0,0.4)');
                  ctx.fillStyle=g;
                  ctx.fillRect(35,0,150,30)
                  //文字
                  ctx.font = "12px 微软雅黑 bolder"
                  ctx.fillStyle = "#fff"
                  ctx.textAlign = "center"
                  ctx.fillText(list[i].name,95,21);
                  //图标
                  var imgObj = new Image();
                  imgObj.src = "/images/community.png";
                  imgObj.onload = function(){
                      ctx.drawImage(this, 0, 0,30,30);//this即是imgObj,保持图片的原始大小：470*480
                      //ctx.drawImage(this, 0, 0,1024,768);//改变图片的大小到1024*768
                               
                let entity = new Cesium.Entity({
                  // 117.97473,35.274898
                  position:Cesium.Cartesian3.fromDegrees(parseFloat(list[i].position[0]),parseFloat(list[i].position[1]),parseFloat(list[i].height+1)),
                  // height:107,n
                  billboard:{
                    image:canvasArr[i],
                    // image:"/images/wushui.png",
                    height:30,
                    width:150,
                    // height:40,
                    // width:40,
                    // scale:1,
                    // pixelSize:20,
                    pixelOffset:new Cesium.Cartesian2(75,-15),
                    heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance:99000000,
                    // clampToGround:true
                  },
                })
                data.landmarkArr.push(entity);
                viewer.entities.add(entity);
                }
            
          }
        },
        addSchoolEntity(){
          let list = [
            {
              position:[117.963558,35.39894],
              name:"上冶镇中心小学"
            } 
            // {
            //   position:[117.98512611573159,35.25364337631628],
            //   name:"东关中学"
            // }, 
            // {
            //   position:[117.96415391365807,35.26292122125022],
            //   name:"费县实验中学",
            // },
            // {
            //   position:[117.95830322815323,35.2698094923481],
            //   name:"西关小学",
            // },
            // {
            //   position:[117.9553245528308,35.26961841496414],
            //   name:"费县职业中专",
            // },
            // {
            //   position:[117.94721838453447,35.26606553073805],
            //   name:"费县第二中学"
            // }
          ];
          let canvasArr=[];
          for(let i=0;i<list.length;i++){
                list[i].height = 0;
                // 经纬度转笛卡尔
                var position3 = new Cesium.Cartographic(Cesium.Math.toRadians(list[i].position[0]),Cesium.Math.toRadians(list[i].position[1]));
                
                list[i].height = window.viewer.scene.sampleHeight(position3);
                canvasArr[i] = document.createElement('canvas');
                canvasArr[i].width = 150;
                canvasArr[i].height = 30;
                // canvasArr[i].getContext('2d');
                 let ctx = canvasArr[i].getContext('2d');
                   //矩形
                  var g=ctx.createLinearGradient(0,0,40,0);
                  g.addColorStop(0,'rgba(0,0,0,0.4)');
                  g.addColorStop(1,'rgba(0,0,0,0.4)');
                  ctx.fillStyle=g;
                  ctx.fillRect(35,0,150,30)
                  //文字
                  ctx.font = "12px 微软雅黑 bolder"
                  ctx.fillStyle = "#fff"
                  ctx.textAlign = "center"
                  ctx.fillText(list[i].name,95,21);
                  //图标
                  var imgObj = new Image();
                  imgObj.src = "/images/school.png";
                  imgObj.onload = function(){
                      ctx.drawImage(this, 0, 0,30,30);//this即是imgObj,保持图片的原始大小：470*480
                      //ctx.drawImage(this, 0, 0,1024,768);//改变图片的大小到1024*768
                               
                let entity = new Cesium.Entity({
                  // 117.97473,35.274898
                  position:Cesium.Cartesian3.fromDegrees(parseFloat(list[i].position[0]),parseFloat(list[i].position[1]),parseFloat(list[i].height+1)),
                  // height:107,n
                  billboard:{
                    image:canvasArr[i],
                    // image:"/images/wushui.png",
                    height:30,
                    width:150,
                    // height:40,
                    // width:40,
                    // scale:1,
                    // pixelSize:20,
                    pixelOffset:new Cesium.Cartesian2(75,-15),
                    heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance:99000000,
                    // clampToGround:true
                  },
                })
                data.landmarkArr.push(entity);
                viewer.entities.add(entity);
                }
              
          }
        },
        addCustomEntity(){
          let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
          handler.setInputAction(function(event) {
            
            let selectedEntity = window.viewer.selectedEntity;
            var position = viewer.scene.pickPosition(event.position);
  
            let cartographic = Cesium.Cartographic.fromCartesian(position);
            let lng = Cesium.Math.toDegrees(cartographic.longitude) + 0.003; // 经度
            let lat = Cesium.Math.toDegrees(cartographic.latitude) - 0.018; // 纬度
            if(selectedEntity.id == "zhezhao"){
              
            }else{
              // window.viewer.flyTo(selectedEntity,{duration:5});
              window.viewer.flyTo(selectedEntity,{
                duration:3,
                offset : {
                  heading: Cesium.Math.toRadians(0.0),	// 以弧度为单位的航向角。
                  pitch: -Math.PI / 2 + 1,					// 以弧度为单位的俯仰角。
                  range: 700								// 到中心的距离，以米为单位。								
                }
              });
            }
             
            // pickResult = selectedEntity.billboard ? selectedEntity.billboard : null;
            // if(pickResult){
            // }
             
              
              
  
              var position2 = new Cesium.Cartographic.fromCartesian(position);
              var height2 = viewer.scene.sampleHeight(position2);
              var position3 = new Cesium.Cartographic(Cesium.Math.toRadians(117.973724),Cesium.Math.toRadians(35.278375));
              var height2 = viewer.scene.sampleHeight(position3);
          }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  
          let list = [
            {
              position:[117.954836,35.396238],
              name:"上冶镇人民政府"
            }, 
            {
              position:[117.969785,35.398552],
              name:"上冶镇社区教育中心"
            } , 
            {
              position:[117.958197,35.398924],
              name:"上冶中心卫生院"
            } 
  
            
          ];
          let canvasArr=[];
          for(let i=0;i<list.length;i++){
                list[i].height = 0;
                // 经纬度转笛卡尔
                var position3 = new Cesium.Cartographic(Cesium.Math.toRadians(list[i].position[0]),Cesium.Math.toRadians(list[i].position[1]));
              
                //获取模型高度
         
                list[i].height = window.viewer.scene.sampleHeight(position3);
                canvasArr[i] = document.createElement('canvas');
                canvasArr[i].width = 150;
                canvasArr[i].height = 67;
                // canvasArr[i].getContext('2d');
                 let ctx = canvasArr[i].getContext('2d');
                  //  矩形
                  ctx.fillStyle ="#409EFF";
                  ctx.fillRect(20,0,150,30)
                  // ctx.fillRect(0,0,150,65)
                  // ctx.fillRect(0,0,150,75)
                  ctx.strokeStyle = "blue";
                  //文字
                  ctx.font = "14px 微软雅黑 bolder"
                  ctx.fillStyle = "#fff"
                  ctx.textAlign = "center"
                  ctx.fillText(list[i].name,85,20);
                  // 图片
                  let imgObj = new Image();
                  imgObj.src = "/images/popupLbl.png";
                  imgObj.onload = function(){
                      ctx.drawImage(imgObj, 0, 30);//this即是imgObj,保持图片的原始大小：470*480
                      //ctx.drawImage(this, 0, 0,1024,768);//改变图片的大小到1024*768
                               
                let entity = new Cesium.Entity({
                  // 117.97473,35.274898
                  position:Cesium.Cartesian3.fromDegrees(parseFloat(list[i].position[0]),parseFloat(list[i].position[1]),parseFloat(list[i].height+1)),
                  // height:107,n
                  billboard:{
                    image:canvasArr[i],
                    // image:"/images/wushui.png",
                    height:67,
                    width:150,
                    // height:40,
                    // width:40,
                    // scale:1,
                    // pixelSize:20,
                    pixelOffset:new Cesium.Cartesian2(75,-15),
                    heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance:99000000,
                  },
                })
                data.landmarkArr.push(entity);
                viewer.entities.add(entity);
                }
             
          }
        },
        deletePolygon(){
          if(data.roleInfo.handlerPoint){
            data.roleInfo.handlerPoint.clear();
            methods.changeSpaceTimeImageLayer("delete");
            // data.roleInfo.currentImageLayerCollection.removeAll();
          }
        },
        drawPolygon(){ //历史影像框选绘图操作
          // 绘图前清空已存在的图案
          if(data.roleInfo.handlerPoint){
            data.roleInfo.handlerPoint.clear();
            methods.changeSpaceTimeImageLayer("delete");
          }
          data.roleInfo.handlerPoint = new Cesium.DrawHandler(viewer,Cesium.DrawMode.Polygon);
          data.roleInfo.handlerPoint.activeEvt.addEventListener(function(isActive){
            if(isActive == true){
                viewer.enableCursorStyle = false;
                viewer._element.style.cursor = '';
            }
            else{
                viewer.enableCursorStyle = true;
            }
          });
  
          let polygan = "POLYGON(("
          data.roleInfo.handlerPoint.drawEvt.addEventListener(function(result){
              // result.object._polygon.material = Cesium.Color.BLUE
              result.object._polygon.material = Cesium.Color.TRANSPARENT;
         
              for(let i=0;i<result.object.positions.length;i++){
                let cartographic = Cesium.Cartographic.fromCartesian(result.object.positions[i]);
                let x=Cesium.Math.toDegrees(cartographic.longitude);
                let y=Cesium.Math.toDegrees(cartographic.latitude);
                polygan = polygan+x+" "+y+","
              }
              let cartographic = Cesium.Cartographic.fromCartesian(result.object.positions[0]);
              let x=Cesium.Math.toDegrees(cartographic.longitude);
              let y=Cesium.Math.toDegrees(cartographic.latitude);
              polygan = polygan+x+" "+y+"))"
              context.emit("searchService",polygan);
          });
          data.roleInfo.handlerPoint.activate();
        },
        addLocalShpfile(geojson){
          if(geojson.show){  // 如果是添加 执行添加函数
            methods.addLocalShpfileLayer(geojson);
          }else{    //如果是删除 则执行删除函数
            viewer.dataSources.remove(viewer.dataSources.getByName(geojson.layerId)[0]);
          }
        },
        formatColor(color){
          let number = color.slice(color.indexOf("(")+1,color.indexOf(")"));
          let numberArray = number.split(",");
          let object = {
            red:parseFloat((numberArray[0]/255).toFixed(3)),
            green:parseFloat((numberArray[1]/255).toFixed(3)),
            blue:parseFloat((numberArray[2]/255).toFixed(3)),
            opacity:parseFloat(numberArray[3])
          }
          return object;
        },
        addLocalShpfileLayer(geojson){
  
     
          data.roleInfo.promise = new Cesium.GeoJsonDataSource.load(geojson.data);    
          if(geojson.type=="点"){
            data.roleInfo.promise.then((datasource) => {
              datasource.name = geojson.layerId;
              viewer.dataSources.add(datasource);   // 加载这个geojson资源 
              let entities = datasource.entities.values;
              for (let index = 0; index < entities.length; index++) {
                let entity = entities[index];
                
                entity.billboard.image = "/images/wushui.png";
                entity.billboard.width = 50;
                entity.billboard.height = 50;
                // entity.polygon.outline = true;
                // entity.polygon.outlineColor = Cesium.Color.RED;
              }
            })
          }else if(geojson.type=="线"){
            data.roleInfo.promise.then((datasource) => {
              datasource.name = geojson.layerId;
              viewer.dataSources.add(datasource);   // 加载这个geojson资源 
              let entities = datasource.entities.values;
              let color = methods.formatColor(geojson.style.lineColor);
                // console.log("colorcolor",color);
              for (let index = 0; index < entities.length; index++) {
                let entity = entities[index];
                entity.polyline.material = new Cesium.Color(color.red, color.green, color.blue, color.opacity);
                entity.polyline.width = geojson.style.width;
  
                entity.polyline.clampToGround = true;
                entity.polyline.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND;
              }
            })
          }else if(geojson.type=="面"){
            
            data.roleInfo.promise.then((datasource) => {
              datasource.name = geojson.layerId;
              viewer.dataSources.add(datasource);   // 加载这个geojson资源 
              let entities = datasource.entities.values;
              let fillColor = methods.formatColor(geojson.style.fillColor);
              let outlineColor = methods.formatColor(geojson.style.fillColor);
              
              for (let index = 0; index < entities.length; index++) {
                let entity = entities[index];
                
  
                entity.polygon.fill = true;
                entity.polygon.fillColor = new Cesium.Color(fillColor.red, fillColor.green, fillColor.blue, fillColor.opacity);
                // entity.polygon.outline = true;
                entity.polygon.outlineWidth = 5;
                entity.polygon.outlineColor = Cesium.Color.BLUE.withAlpha(0.5);
  
                // entity.material = new Cesium.Color(fillColor.red, fillColor.green, fillColor.blue, fillColor.opacity);
                // 
                // entity.polygon.outlineColor = new Cesium.Color(outlineColor.red, outlineColor.green, outlineColor.blue, outlineColor.opacity);
              }
            })
          }
        },
        addWebServe(obj) {
            console.log("layerObjInfo",obj);
            
            if(data.isFirstLoad){
             
              data.isFirstLoad=false;
              // 开局跳转视角
              // methods.searchFlyTo({position:{x:117.886725,y:34.773011}},60000); //,
  
              // 添加图层点击事件获取点击实体信息
              let handler = new Cesium.ScreenSpaceEventHandler(window.viewer.scene.canvas);
              handler.setInputAction(function (e) {
                // 获取选中实体信息
                // 获取点击位置笛卡尔坐标
                let position = window.viewer.scene.pickPosition(e.position);
                
                window.viewer.scene.postRender.addEventListener(function(){
                    let canvasHeight = viewer.scene.canvas.height;
                    let windowPosition = new Cesium.Cartesian2();
                    let scenePosition = position;
                    new Cesium.SceneTransforms.wgs84ToWindowCoordinates(window.viewer.scene, scenePosition, windowPosition);
                    data.roleInfo.mvtbubbleBottom = (canvasHeight - windowPosition.y + 75) + 'px';
                    data.roleInfo.mvtbubbleLeft = (windowPosition.x - 50) + 'px';
                })
                methods.handlerSelectedEntityProperties();
              }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  
              // 加载地图遮罩
              // methods.addMaskLayer();
  
              // 加载立体墙效果
              methods.drawWallLayer();
  
              //加载村界
              methods.drawLineLayer()
  
              //  如果是违建专题 加载违建图斑数据
              if(route.query.title == "违建监测专题"){
                methods.addHistoryCaseLayer();
              }
              // 穿透显示镇边界图层
              // methods.addZhenJieMvtLayer();
            }
  
            if(obj.type == 'S3M'){
              // methods.getPosition(obj)
              let dataServiceUrl = obj.dataServiceUrl + '&token=' + SUPER_MAP_KEY
              let dataSourceName = obj.dataSourceName
              let dataSetName = obj.dataSetName
              data.roleInfo.s3mvisible = true
              // 原始加载方式
              // 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)
              // let promises = window.viewer.scene.open("http://223.99.16.253:8090/iserver/services/3D-shangyeL18all/rest/realspace")
              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(){
                    methods.addCustomEntity();
                    methods.addSchoolEntity();
                    methods.addCommunityEntity();
                  },10000)
                }
              })
  
              /*　
                
              */ 
  
              // promises.setLodRangeScale(15)
              methods.addS3mTilesLayer(dataServiceUrl,dataSourceName,dataSetName,promises)
            }else if(obj.type == 'MVT'){
               let 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.alpha = 0.8;
              
                let layerReadyPromise = mvtMap.readyPromise;
                // if(window.viewer.scene.layers.find('1718895930196885504')){
                //   window.viewer.scene.layers.find('1718895930196885504').coverImageryLayer=mvtMap
                // }
                
                Cesium.when(layerReadyPromise, function (data) {
                  var bounds = mvtMap.rectangle;
                  // 添加图层跳转图层
                  // window.viewer.scene.camera.setView({
                  //     destination: new Cesium.Cartesian3.fromRadians((bounds.east + bounds.west) * 0.5, (bounds.north + bounds.south) *
                  //         0.5, 10000),
                  //     orientation: {
                  //         heading: 0,
                  //         roll: 0
                  //     }
                  // });
                  // window.viewer.camera.flyTo({destination: bounds,orientation:{
                  //     // heading: 0.09596697944080823,
                  //     // pitch: -0.1854952805486341,
                  //     // roll: 2.0370372055822372e-11
                  //   }
                  // })
                    
                  let mapboxStyle = mvtMap.mapboxStyle
                   
                  for (let id in mapboxStyle.layers) {
                      let layer = mapboxStyle.layers[id];
                     
                      if(layer.type === "symbol"){
                          // mvtMap.setLayoutProperty(layer.id, 'text-max-width', 5);
                      }else if(layer.type == "fill"){
                          // mvtMap.setPaintProperty(layer.id, "fill-color", "r");
                          // mvtMap.setLayoutProperty(layer.id,"fill-opacity",0.01);
                          // mvtMap.setPaintProperty(layer.id,"fill-opacity",1);
                          // mvtMap.setPaintProperty(layer.id, "fill-color", "rgba(255,0,0,0.3)");
                      }
                  }
                 
                  console.log("layers",window.viewer.scene.layers)
                })
            }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.searchFlyTo(res.data,500)
          })
        },
        addMVTTilesLayer(bounds){
          viewer.scene.camera.setView({
              destination: new Cesium.Cartesian3.fromRadians((bounds.east + bounds.west) * 0.5, (bounds.north + bounds.south) *
                  0.5, 10000),
              orientation: {
                  heading: 0,
                  roll: 0
              }
          });
        },
        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);
          });
        },
        // 获取自然幢信息
        getBuildInfo(id){
          context.emit("getBuildBaseInfo",id);
        },
        // 获取历史案件记录
        getHistoryCaseInfo(case_id){
          context.emit("getHistoryCaseInfo",case_id);
        },
        // 通过点击查询用于表示单体化的面要素，添加到场景中高亮显示。
        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]
                  })
                })
                let arr = []
                tableData.forEach(item =>{
                  if(item.name!=='图层id'&&item.name!=='SMUSERID'&&item.name!=='SMAREA'&&item.name!=='SMPERIMETER'&&item.name!=='SMGEOMETRY'&&item.name!=='Id'&&item.name!=='用户ID'){
                    arr.push(item)
                  }
                })
                let obja = {}
              
                arr.forEach((item, index) => {
                  if (item.name == '姓名') {
                    obja = item
                    arr.splice(index, 1)
                      return
                  }
                })
                arr.unshift(obja)
                data.roleInfo.tableDataList = arr
             
                if(!data.roleInfo.s3mvisible){
                   return 
                }
                
  
                methods.addClapFeature(resultObj.features[0]);
  
                // 获取不动产单元号 弹窗显示自然幢信息
             
                let buildNumber = tableData.find((item,index)=>{
                  return item.ename == "BDCDYH"
                })
                if(buildNumber){
                  methods.getBuildInfo(buildNumber.value);
                }
              }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模型表面
                },
            });
            // methods.handlerFlyTo()
     
            // window.viewer.flyTo(currentEntity,{duration:3});
        },
        // 得到[经度,纬度,经度,纬度...]形式的数组，用于构造面。
        getLonLatArray(points) {
            let point3D = [];
            points.forEach(function (point) {
                point3D.push(point.x);
                point3D.push(point.y);
            });
            return point3D;
        },
        // 跳转
        handlerFlyTo(obj){
          // methods.flyTo(obj)
        },
        //图层透明度改变
        handlerChangeLayerOpecity(e){
          if(e.type=="MVT"){  // mvt图层
            
            let mvtMap = viewer.scene.getVectorTilesMap(e.id);
            mvtMap.alpha = e.opacity*0.01;
          }else if(e.type == 'IMAGE'){        // imagery图层
            let layerObj = data.imageryLayers.find((item,index)=>{
              return item.name == e.id;
            })
            if(layerObj){
              layerObj.layer.alpha = e.opacity*0.01;
            }
          }
        },
        // 清除开场动画
        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),
              orientation:{
                heading: 0.09596697944080823,
                pitch: -0.1854952805486341,
                roll: 2.0370372055822372e-11
              }
              // destination: new Cesium.Cartesian3(
              //     cameraParam.Cartesian3.x,
              //     cameraParam.Cartesian3.y,
              //     cameraParam.Cartesian3.z
              // ),
              // orientation: {
              //   heading: cameraParam.heading,
              //   pitch: cameraParam.pitch,
              //   roll: cameraParam.roll
              // },
              // duration: 0
            });
            return false;
          }
        },
        // 搜索后定位
        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: -0.6,
                roll: 2.0370372055822372e-11
              },
              duration: 0.5,
            });
            return false;
          }
        },
      }
      return {
        layerTreeLocal,
        ...data,
        ...methods
      }
    },
  });
  </script>
  
  <style scoped>
  .cim-map {
    height: 100vh;
    padding:0px;
  }
  
  .cim-aside {
    position: fixed;
    left: 0;
    top: 0;
    height: 100vh;
    width: 200px;
    padding-top: 80px;
    background: #222222;
  }
  
  .bubblecontainer {
      text-align:center;
      position: absolute;
      padding: 15px;
      margin: 0;
      background: rgba(255,255,255,0.5);
      width : 330px;
      max-height: 200px;
      border-radius: 4px;
      cursor: pointer;
      box-shadow: 2px 2px 6px rgba(26, 26, 26, 0.5);
  }
  .bubblecontainer:after {
      content: "";
      position: absolute;
      bottom: -50px;
      left: 50px;
      border-width: 0 20px 50px 0px;
      border-style: solid;
      border-color: transparent #fff;
      display: block;
      width: 0;
  }
  .cim-component-close-img{
    position: absolute;
    left: 10px;
    top: 8px;
    width: 20px;
    z-index: 100;
  }
  
  /* Border styles */
  #tab thead, #tab tr {
      border-top-width: 1px;
      border-top-style: solid;
      border-top-color: rgb(211, 202, 221);
  }
  #tab {
      border-bottom-width: 1px;
      border-bottom-style: solid;
      border-bottom-color: rgb(211, 202, 221);
      /*height: 400px;*/
      width: 100%;
  }
  
  /* Padding and font style */
  #tab td, #tab th {
      padding: 5px 10px;
      font-size: 12px;
      font-family: Verdana;
      color: #000;
      border: 1px solid rgba(193, 168, 223,0.8);
  }
  
  /* Alternating background colors */
  #tab tr:nth-child(even) {
      background: rgba(223, 216, 232,0.8)
  }
  #tab tr:nth-child(odd) {
      background: rgba(255,255,255,0.8);
  }
  
  ::v-deep #echarts_box{
    position: fixed !important;
  }
  .villageDia{
    position: absolute;
    z-index: 9;
    left: 450px;
    top: 120px;
    width: 330px;
  }
  
  ::v-deep .el-input__inner{
    color: #fff;
    background: rgba(0, 0, 0, 0.2);
    border-color: #409eff;
  }
  ::v-deep .el-input__inner{
    box-shadow: 0 0 0 1px #409eff inset;
  }
  
  </style>
  