<template>
<div class="map-container">
  <div class="home-bg-container">
  </div>
  <div class="layer-container">
    <div class="search-container">
      <input type="text" id="search-input" v-model="searchKeyWord" placeholder="请输入关键字搜索">
      <div class="clear-search" @click="closeSearch()" v-show="searchKeyWord">
        &times;
      </div>
      <div class="search-btn" @click="search()">
        搜索
      </div>
    </div>
    <!-- 图层树 -->
    <!-- <VueDragResize> -->
      <!-- <div class="layers-box" v-for="(item,index) in layers" :key="index">
        <div class="layer-type-box"  @click="showTypeLayers(index)">
          <div class="image">
            <img :src="item.image" width="56px" alt="">
          </div>
          <div class="layer-type-info">
            <p>{{item.name}}</p>
            <p :style="{'color':item.theam}">{{item.children.length}}</p>
          </div>
        </div>
        <div class="child-layers" v-show="item.show" :style="{'border-color': item.children.length>0? item.theam : 'rgba(0,0,0,0)'}">
          <p v-for="(it,idx) in item.children" :key="idx"> <img src="/images/map/box.png" width="20px" height="20px" style="position:relative;top:5px;" @click="addLayer(item)" />{{it.name}}</p>
        </div>
      </div> -->
    <div class="map-layer-tree-container">
      <MapLayerTree @addLayer="addLayer" @editLayer="editLayer" v-if="show_menu_tree" :menu_tree="menu_tree" :level="1"></MapLayerTree>
    </div>
    <!-- </VueDragResize> -->
  </div>
  <!-- 搜索结果 -->
  <VueDragResize :x="0" :y="0" v-if="isShowSearchWindow">
    <div class="search-result">
      <SearchContainer :searchKeyWord="searchKeyWord"  @toPosition="toPosition"></SearchContainer>
    </div>
  </VueDragResize>
  <!-- 属性表格 -->
  <VueDragResize :x="positionX" :y="positionY" v-show="showAttributeWindow" >
    <div class="attribute-window">
      <AttributeWindow :targetObj="targetObj" @closeAttributeWindow="closeAttributeWindow"></AttributeWindow>
    </div>
  </VueDragResize>
  <!-- 图层目录树 -->
  
  <!-- <div class="maplayertree-window">
    <MapLayerTree :menu_tree="menu_tree" :level="1"></MapLayerTree>
  </div> -->
  <!-- 绘图工具 -->
  <!-- <VueDragResize :x="0" :y="0"  v-if="isEditLayer" > -->
    <div class="drawpanl-window" v-if="isEditLayer">
      <DrawPanl @addpoint="drawPoint" @delpoint="delPoint" :editRandom="editRandom" :editLayerInfo="editLayerInfo" :currentLngLat="currentLngLat" @addPointSuccess="addPointSuccess" @close="closeDrawPanl"></DrawPanl>
    </div>
  <!-- </VueDragResize> -->
  <div  id="mapContainer">
    
  </div>
</div>
  
</template>
<script>
import VueDragResize from 'vue-drag-resize'
import AttributeWindow from '../components/attributeWindow.vue'
import SearchContainer from "../components/searchResult.vue";
import MapLayerTree from '../components/MapLayerTree.vue'
import DrawPanl from '../components/DrawPanl.vue'
import { getMethodCommon } from '../api/common';
// import { getMethodCommon } from '../api/common';
export default {
  name:"Map",
  data(){
    return {
      editRandom:1,
      isEditLayer:false,
      currentLngLat:null,
      editLayerInfo:null,
      positionX:0,
      positionY:0,
      showAttributeWindow:false,
      isShowSearchWindow:false,
      searchKeyWord:null,
      searchPoint:null,
      windowDataInfo:{},
      layers:[],
      // menu_tree:null,
      show_menu_tree:true,
      menu_tree:null,
      targetObj:{
        gid:null,
        tablename:null,
      }
    }
  },
  watch:{
    searchKeyWord:function(e){
      if(e){
        this.isShowSearchWindow = true;
      }else{
        this.isShowSearchWindow = false;
      }
    },
    windowDataInfo:function(e){
      alert(e);
    }
  },
  components:{
    AttributeWindow,
    VueDragResize,
    SearchContainer,
    MapLayerTree,
    DrawPanl
  },
  created(){
    this.getMenuTree();
  },
  mounted(){
    this.initMap();
  },
  methods:{
    closeSearch(){
      this.isShowSearchWindow = false;
      this.searchKeyWord = null;
      this.searchPointResult(null,null,null);
    },
    // 绘制点
    drawPoint(){
      let layerstyle = JSON.parse(this.editLayerInfo.layerstyle);
      let _this = this;
      // 判断是否创建了图层 如果创建了移除所有事件
      if(_this.globalMap.getLayer("points")){
        _this.globalMap.off('mousemove', _this.onMove);
        _this.globalMap.off('touchmove', _this.onMove);
      }
      
      // 判断图标有无 创建图标 先移除之前的image
      if(_this.globalMap.hasImage("points")){
        _this.globalMap.removeImage("points");
      }

      _this.globalMap.loadImage('/images/map/'+layerstyle.style['icon-image'],(error, image) => {
        if (error) throw error;
        _this.globalMap.addImage("points",image);
      })
      
      
      // 设置鼠标为绘制样式
      _this.globalMap.getCanvas().style.cursor = 'crosshair';

            // e.stopPropagation();
            // clearLayerAndSource();
            var isDraw = true;
            // 禁止双击缩放
      _this.globalMap.doubleClickZoom.disable();

      var jsonPoint = {
          'type': 'FeatureCollection',
          'features': []
      };

      // 判断是否创建Source 并添加points layer
      var source = _this.globalMap.getSource('points');

      if(source) {
          _this.globalMap.getSource('points').setData(jsonPoint);
      }else{
          _this.globalMap.addSource('points', {
              type: 'geojson',
              data: jsonPoint
          });
          _this.globalMap.addLayer({
              id: 'points',
              type: 'symbol',
              source: 'points',
              'layout': {
                'icon-image':'points',
                'icon-size': 0.2,
                'visibility': 'visible'
              },		
          });
      }

      _this.globalMap.on("click","points",function(e){
          console.log(e.features[0]);
          // When the mouse leaves the `my-layer` layer,
          // reset the entire state object for the
          // feature under the mouse
          console.log("data-source",_this.globalMap.getSource("points"));
          _this.globalMap.removeFeatureState({
              source: 'points',
              sourceLayer: 'points',
              id: e.features[0].id
          });

      })

      // 鼠标移入points 图标放大 鼠标样式改为移动样式
      _this.globalMap.on("mouseenter","points",function(e){
        console.log(e);
        // _this.globalMap.setLayoutProperty('points', 'icon-size', 0.3);
        _this.globalMap.getCanvas().style.cursor = 'move';
      })
      // 鼠标离开points 图标恢复 鼠标样式改为默认样式
      _this.globalMap.on("mouseleave","points",function(e){
        console.log(e);
        // _this.globalMap.setLayoutProperty('points', 'icon-size', 0.2);
        _this.globalMap.getCanvas().style.cursor = '';
      })

      // 鼠标按下 points图层 
      _this.globalMap.on('mousedown', 'points', (e) => {
        e.preventDefault();
        // 鼠标样式设置为小手样式
        _this.globalMap.getCanvas().style.cursor = 'grab';
        // 鼠标移动 执行图标移动函数
        _this.globalMap.on('mousemove', _this.onMove);
        // 执行一次鼠标抬起函数
        _this.globalMap.once('mouseup', _this.onUp);
      });

      // 点击地图 添加point
      _this.globalMap.on('click', function (_e) {
          if (isDraw) {
              _this.globalMap.getCanvas().style.cursor = 'grab'
              isDraw=false;
              var endCoords=[_e.lngLat.lng, _e.lngLat.lat];
              jsonPoint.features.push({
                  type: 'Feature',
                  id:"123",
                  geometry: {
                      type: 'Point',
                      coordinates: endCoords
                  }
              });
              _this.currentLngLat = _e.lngLat.lng+" "+_e.lngLat.lat
              _this.globalMap.getSource('points').setData(jsonPoint);
          }
      })
    },
    // 绘制点并保存成功
    addPointSuccess(){

    },
    // 关闭绘制面板
    closeDrawPanl(){
      this.isEditLayer = false;

      this.globalMap.getCanvas().style.cursor = '';
      // 移除鼠标事件
      this.globalMap.off('mousemove', this.onMove);
      this.globalMap.off('touchmove', this.onMove);
      let geojson = {
          'type': 'FeatureCollection',
          'features': []
      }
      this.globalMap.getSource('points').setData(geojson);

    },
    // 图标移动函数
    onMove(e) {
      const coords = e.lngLat;
      this.globalMap.getCanvas().style.cursor = 'grabbing';
      let geojson = {
          'type': 'FeatureCollection',
          'features': [
            {
              'type': 'Feature',
              'geometry': {
                'type': 'Point',
                'coordinates': [0, 0]
              }
            }
          ]
      }
      geojson.features[0].geometry.coordinates = [coords.lng, coords.lat];
      this.currentLngLat = coords.lng+" "+coords.lat;
      this.globalMap.getSource('points').setData(geojson);
    },
    // 鼠标抬起移除监听事件
    onUp(e) {
      console.log(e);
      // 获取坐标信息
      // const coords = e.lngLat;
      // coordinates.style.display = 'block';
      // coordinates.innerHTML = `Longitude: ${coords.lng}<br />Latitude: ${coords.lat}`;
      // 修改鼠标样式
      this.globalMap.getCanvas().style.cursor = '';
      // 移除鼠标事件
      this.globalMap.off('mousemove', this.onMove);
      this.globalMap.off('touchmove', this.onMove);
    },
    // 删除点
    delPoint(){
      if(this.globalMap.getLayer("points")){
        let geojson = {
            'type': 'FeatureCollection',
            'features': []
        }
        this.globalMap.getSource("points").setData(geojson);
      }

      this.reloadLayer(this.editLayerInfo);


      
    },
    getMenuTree(){
      getMethodCommon("/LayerManager/LoadTree").then(res=>{
        if(res.code == 200){
          let result = res.result;
          result = this.handleMenuTree(result);
          this.menu_tree = {...result}
          this.show_menu_tree = true;
          console.log("menu_tree",this.menu_tree);
        }
      })
    },
    handleMenuTree(arr){
      if(arr.length>0){
        for(let i=0;i<arr.length;i++){
          arr[i].icon = "/images/map/layer-type-7.png";
          arr[i].color = "#8b58c7";
          arr[i].show = false;
          arr[i].isEdit = false;
          arr[i].layers = [];
          if(arr[i].children.length>0){
            arr[i].children = this.handleMenuTree(arr[i].children);
          }
        }
        return arr;
      }
    },
    showTypeLayers(index){
      this.layers[index].show=!this.layers[index].show;
    },
    initMap(){
      //mapbox 2.0以后的版本需要accessToken  到官网注册下载
      this.$mapboxgl.accessToken = "pk.eyJ1Ijoic2hpY2hhbzEyMyIsImEiOiJja3FobnI1aDEwNGF6Mm9vOXVhNnBzZmFhIn0.2fZKiMqCQHxVY74QShMEGQ";
      this.globalMap = new this.$mapboxgl.Map({
        container:"mapContainer",
        center:[117.621842,35.520241],
        zoom:13,
        maxZoom:20,
        minZoom:5,
        pitch:45,
        style:"mapbox://styles/shichao123/cl2dztvfx001g14o8n5ezc0er"
      });
      // 地图加载完毕事件
      let _this = this;
      this.globalMap.on("load",function(){
        
        // 加载天地图
        _this.globalMap.addLayer({
          'id': 'tiandituzhuji',
          'type': 'raster',
          'source':{
              "type": "raster",
              "tiles": ['http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=b6585bc41ee16251dbe6b1af64f375d9'],
              "tileSize": 256,
          }
        })

        // let layer = {
        //   id:"4a79d871-d102-4d1a-a83b-41c76c34efc9",
        //   layertype:"fill",
        //   tablename:"pingyi62745103420221126",
        //   style:'{"style":{"fill-opacity":0.8,"fill-color":"#F40A0A","fill-outline-color":"#00FF0D"},"maxZoom":18,"minZoom":8}',
        // }

        // let lineLayer = {
        //   id:"5cba0ab8-0e35-4315-bd53-74b4f62ecbc1",
        //   layertype:"symbol",
        //   tablename:"pingyi737093143420221126",
        //   style:'{"style":{"line-opacity":0.8,"line-color":"#CC00FF","line-width":5},"maxZoom":18,"minZoom":12}',
        // }
        // _this.addLayer(lineLayer);

      })
    },
    showSearchWindow(isShow){
      this.isShowSearchWindow = isShow;
    },
    closeAttributeWindow(){
      this.showAttributeWindow = false;
    },
    toPosition(info){
      console.log("info",info);
      let arr = info.lonlat.split(",");
      this.globalMap.flyTo(
        {center: [arr[0],arr[1]],zoom:16.5,pitch: 45} // 倾斜度
      );
      if(this.searchPoint){
        this.searchPoint.remove();
      }
      this.searchPointResult(arr[0], arr[1],info.name);
      // this.searchPoint = new this.$mapboxgl.Marker().setLngLat([arr[0], arr[1]]).addTo(this.globalMap);
    },
    changelayershow(val){
      console.log(val);
    },
    // 加载图层
    addLayer(layerInfo){
      console.log("addlayerinfo",layerInfo);
      if(layerInfo.show == true){
        if(this.globalMap.hasImage(layerInfo.id)){
          this.globalMap.removeImage(layerInfo.id)
        }
        if(this.globalMap.getLayer(layerInfo.id)){
          this.globalMap.removeLayer(layerInfo.id)
        }
        if(this.globalMap.getSource(layerInfo.id)){
          this.globalMap.removeSource(layerInfo.id)
        }
        return;
      }
      let layerStyle = JSON.parse(layerInfo.layerstyle);


      if(layerInfo.layertype == 'fill' || layerInfo.layertype == 'line'){

        this.globalMap.addSource(layerInfo.id,{
          type: 'vector',
            tiles: ['http://123.132.248.154:6005/api/ScreenService/QueryVectorTileByTable?z={z}&x={x}&y={y}&table='+layerInfo.tablename],
            minzoom: parseInt(layerStyle.minZoom),
            maxzoom: parseInt(layerStyle.maxZoom)
        })

        this.globalMap.addLayer({
          'id': layerInfo.id,
          'type': layerInfo.layertype,
          'source':layerInfo.id,
          "source-layer": layerInfo.tablename,
          'paint': layerStyle.style
        });

        let _this = this;

        this.globalMap.on("click",layerInfo.id,function(e){
          _this.targetObj.gid = e.features[0].properties.gid;
          _this.targetObj.tablename = e.features[0].sourceLayer;
          _this.getDetail(e.features[0].properties.gid,e.features[0].sourceLayer);
        })

      }else if(layerInfo.layertype == 'symbol'){
        console.log("layerInfo",layerInfo);
        // 加载图标
        this.globalMap.loadImage('/images/map/'+layerStyle.style['icon-image'],(error, image) => {
          if (error) throw error;
          this.globalMap.addImage(layerInfo.id,image);
        })

        this.globalMap.addSource(layerInfo.id,{
              type: 'vector',
                tiles: ['http://123.132.248.154:6005/api/ScreenService/QueryVectorTileByTable?z={z}&x={x}&y={y}&table='+layerInfo.tablename],
                minzoom: layerStyle.minZoom,
                maxzoom: layerStyle.maxZoom
        })

        this.globalMap.addLayer({
            "id": layerInfo.id,
            "type": "symbol",
            'source': layerInfo.id,
            "source-layer": layerInfo.tablename,
            'layout': {
              'icon-image':layerInfo.id,
              'icon-size': 0.2,
              'visibility': 'visible'
            },		
            "paint":{}
        });
        let _this = this;
        // 点击图标
        this.globalMap.on("click",layerInfo.id,function(e){
          console.log(e.features[0]);

          console.log("_data",_this.globalMap.getSource(layerInfo.id));

          // 删除图标
          _this.globalMap.removeFeatureState({
            source:layerInfo.id,
            sourceLayer:layerInfo.id,
            id:e.features[0].id
          })

          _this.targetObj.gid = e.features[0].properties.gid;
          _this.targetObj.tablename = e.features[0].sourceLayer;
          _this.getDetail(e.features[0].properties.gid,e.features[0].sourceLayer);
        })
        

      }
    },
    reloadLayer(layerInfo){
      // 移除图层、图标、资源后重新加载
      if(this.globalMap.getLayer(layerInfo.id)){
        this.globalMap.removeLayer(layerInfo.id);
      }
      if(this.globalMap.hasImage(layerInfo.id)){
        this.globalMap.removeImage(layerInfo.id);
      }
      if(this.globalMap.getSource(layerInfo.id)){
        this.globalMap.removeSource(layerInfo.id);
      }

      let layerStyle = JSON.parse(layerInfo.layerstyle);
      // 加载图标
      this.globalMap.loadImage('/images/map/'+layerStyle.style['icon-image'],(error, image) => {
        if (error) throw error;
        this.globalMap.addImage(layerInfo.id,image);
      })
      // 加载资源
      this.globalMap.addSource(layerInfo.id,{
            type: 'vector',
              tiles: ['http://123.132.248.154:6005/api/ScreenService/QueryVectorTileByTable?z={z}&x={x}&y={y}&table='+layerInfo.tablename],
              minzoom: layerStyle.minZoom,
              maxzoom: layerStyle.maxZoom
      })
      // 加载图层
      this.globalMap.addLayer({
          "id": layerInfo.id,
          "type": "symbol",
          'source': layerInfo.id,
          "source-layer": layerInfo.tablename,
          'layout': {
            'icon-image':layerInfo.id,
            'icon-size': 0.2,
            'visibility': 'visible'
          },		
          "paint":{}
      });
        let _this = this;
        // 点击图标
        this.globalMap.on("click",layerInfo.id,function(e){
          console.log(e.features[0]);

          console.log("_data",_this.globalMap.getSource(layerInfo.id));

          // 删除图标
          _this.globalMap.removeFeatureState({
            source:layerInfo.id,
            sourceLayer:layerInfo.id,
            id:e.features[0].id
          })

          _this.targetObj.gid = e.features[0].properties.gid;
          _this.targetObj.tablename = e.features[0].sourceLayer;
          _this.getDetail(e.features[0].properties.gid,e.features[0].sourceLayer);
        })
    },
    // 编辑图层
    editLayer(it){
      this.setNoEdit(this.menu_tree);
      it.isEdit = !it.isEdit;
      this.editLayerInfo = it;
      this.editLayerInfo.gid = null;
      this.isEditLayer = true;
    },
    setNoEdit(arr){
      for(let i=0;i<arr.length;i++){
        arr[i].isEdit = false;
        if(arr[i].children.length>0){
          this.setNoEdit(arr[i].children)
        }
      }
    },
    // 获取点击详细信息
    getDetail(gid,tablename){
        if(this.editLayerInfo && tablename == this.editLayerInfo.tablename){
          this.editRandom = gid+","+tablename;
          this.editLayerInfo.gid = gid;
        }else{
          this.showAttributeWindow = true;
        }
    },
    // 搜索结果更新
    searchPointResult(lng,lat,name){
      let _this = this;
      // 判断图标有无 创建图标
      if(!_this.globalMap.hasImage("search")){
        _this.globalMap.loadImage('/images/map/result.png',(error, image) => {
          if (error) throw error;
          _this.globalMap.addImage("search",image);
        })
      }

      let jsonPoint = {
          'type': 'FeatureCollection',
          'features': []
      };

      if(lng && lat){
        jsonPoint.features[0] = {
              'type': 'Feature',
              'geometry': {
                'type': 'Point',
                'coordinates': [lng,lat]
              },
              'properties':{
                name:name,
              }
            }
      }
      
      // 判断是否创建Source 并添加points layer
      let source = _this.globalMap.getSource('search');

      if(source) {
          _this.globalMap.getSource('search').setData(jsonPoint);
      }else{
          _this.globalMap.addSource('search', {
              type: 'geojson',
              data: jsonPoint
          });
          _this.globalMap.addLayer({
              id: 'search',
              type: 'symbol',
              source: 'search',
              'layout': {
                'icon-image':'search',
                'icon-size': 0.6,
                'visibility': 'visible',
                'text-field':'{name}',
                'text-offset':[0,-2.4],
                'text-size':14
              },		
              paint:{
                "text-color": "#fff"
              }
          });
      }
    }
  }
}
</script>
<style scoped>
.home-bg-container{
  width:100vw;
  height:100vh;
  background-image: url(/images/system/home-bg-1.png);
  background-size:100% 100%;
  position:absolute;
  top:0px;
  left:0px;
  pointer-events: none;
  z-index:2;
}
.map-container{
  width: 100vw;
  height:100vh;
  position:absolute;
  top:0px;
  left:0px;
  overflow: hidden;
}
#mapContainer{
  width:100%;
  height:100%;
}
.layer-container{
  width:318px;
  position:absolute;
  left:70px;
  top:100px;
  z-index:10;
}
.layer-container .map-layer-tree-container{
  min-width:318px;
  max-height:800px;
  overflow-y:auto;
  overflow-x:hidden;
  padding:15px;
}
.layer-container .map-layer-tree-container::-webkit-scrollbar{
  width:5px;
}
.layer-container .map-layer-tree-container::-webkit-scrollbar-thumb{
}
.layer-container .layers-box{
  width:100%;
}
.layer-container .layers-box .layer-type-box{
  height:56px;
  width:100%;
  cursor: pointer;
}
.layer-container .layers-box .layer-type-box .image{
  width:56px;
  height:56px;
  float:left;
}
.layer-container .layers-box .layer-type-box .layer-type-info{
  width:240px;
  height:56px;
  color:#fff;
  line-height: 24px;
  font-size:14px;
  font-weight: bold;
  float:left;
  margin-left:10px;
  padding-top:5px;
}
.layer-container .layers-box .child-layers{
  width:200px;
  border-left:2px solid #8b58c7;
  margin-left:28px;
  padding-bottom:20px;
}
.child-layers p{
  font-size:14px;
  font-weight: bold;
  color:#00FFB3;
  text-indent: 15px;
  line-height:25px;
}
.child-layers p:hover{
  color:#c7000c;
  cursor:pointer
}
.search-container{
  width:100%;
  height:40px;
  margin-bottom:40px;
  background: rgba(66,142,218,0.23);
  border: 2px solid #102072;
  border-radius: 5px;
}
#search-input{
  width:195px;
  height:40px;
  border:0px;
  box-shadow: none;
  outline: none;
  background:none;
  text-indent: 12px;
  color:#fff;
  float:left;
}
.clear-search{
  width:24px;
  height:24px;
  background:rgba(255,255,255,0.2);
  border-radius: 50%;
  float:left;
  margin-top:8px;
  color:#efefef;
  font-size:14px;
  line-height:24px;
  text-align: center;
  cursor:pointer;
}
.search-btn{
  width: 91px;
  float:right;
  height: 40px;
  background: #102072;
  border-radius: 0px 5px 5px 0px;
  font-size: 16px;
  font-family: SimHei, SimHei-Bold;
  font-weight: normal;
  text-align: center;
  color: #ffffff;
  line-height: 40px;
  cursor:pointer;
}

.attribute-window{
  width:400px;
  height:500px;
  position: absolute;
  top:155px;
  left:1070px;  
  z-index:100;
  background-image:url(/images/system/cate-bg.png);
  background-size:100% 100%;
}
.drawpanl-window{
  width:340px;
  height:400px;
  position:absolute;
  right:40px;
  top:150px;
  z-index:101;
}
.search-result{
  width:320px;
  height:470px;
  position:absolute;
  top:155px;
  left:70px;
  z-index: 999;
}

.maplayertree-window{
  width:300px;
  height:500px;
  position: absolute;
  top:155px;
  left:300px;  
  z-index:100;
  line-height:40px;
}
</style>