<!--
 * @ Author: linqiurong
 * @ Create Time: 2020-09-11 08:47:02
 * @ Modified by: linqiurong
 * @ Modified time: 2020-09-11 19:58:01
 * @ Description: 自定义图例颜色 geoJSON 获取数据  点击大区域进入到小区域(点击弹窗 与 点击缩放)   自定义按钮与事件   区域移进移出效果  点击效果  阻止事件
 -->

<template>
 <div>
   <div class="map" ref="map">
     
   </div>

 </div>
</template>

<script>
import "leaflet/dist/leaflet.css"
import L from 'leaflet/dist/leaflet'
import * as Esri from 'esri-leaflet'
import $ from 'jquery'
L.esri = Esri
// icon 显示问题
import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';
let DefaultIcon = L.icon({
    iconUrl: icon,
    shadowUrl: iconShadow
});
L.Marker.prototype.options.icon = DefaultIcon;

export default {
  name: 'CustomerColor',
  mounted() {
    this.initMap()
  },
  computed: {
    goBackDisabled() {
      //
      let btn = document.querySelector(".btn-go-back")
      if(this.parentCodeArr.length > 0) {
        btn.style = "color:red"
      }else{
        // 
        btn.style = "color:grey"
      }
      return this.parentCodeArr.length> 0 ? true: false
    }
  },
  data() {
    return {
      layer: null,
      layers: [],
      parentCode: null,
      parentCodeArr: [100000],
      zoom: 4
    }
  },
  methods: {
    getColor(d) {
      return d > 30 ? '#800026' :
          d > 25  ? '#BD0026' :
          d > 20  ? '#E31A1C' :
          d > 18  ? '#FC4E2A' :
          d > 15   ? '#FD8D3C' :
          d > 10   ? '#FEB24C' :
          d > 5   ? '#FED976' :
                    '#FFEDA0';
    },
    // 根据不同数值设置不同颜色
    getStyle(feature) {
      return {
          fillColor: this.getColor(feature.properties.childrenNum),
          weight: 2,
          opacity: 1,
          color: 'white',
          dashArray: '3',
          fillOpacity: 0.5
      }
    },
    // 获取弹窗数据
    getPopupContent(feature) {
      const properties = feature.properties
      let template = `<div class='title'>名称:${properties.name}</div><div class='content'><div>级别: ${this.getLevel(feature.properties.level)}</div><div>子集: ${properties.childrenNum}个</div><div>地区码: ${properties.adcode}</div><div>中心点:${properties.centroid}</div></div>`
      return template
    },
    // 获取级别
    getLevel(level) {
      let label = ''
      switch(level) {
        case 'province' : label = '省';break;
        case 'city': label = '市'; break;
        case 'district': label = '区'; break;
      }
      return label
    },
    //
    getZoom(level) {
      let zoom = ''
      switch(level) {
        case 'province' : zoom = 4;break;
        case 'city': zoom = 9; break;
        case 'district': zoom = 14; break;
      }
      return zoom
    },
    // 自定义按钮与按钮事件
    customerButton(map) {
      var btnGoBack = L.control({position: 'topright'});
      btnGoBack.onAdd = ()=>{
          var div = L.DomUtil.create('div', 'btn-go-back iconfont icon-shengmingzhouqi')
          // 监听事件
          L.DomEvent.on(div, 'click', (evt)=>{
            // 调用事件
            this.goBack(map,evt)
            L.DomEvent.stopPropagation(evt);
            // console.log(evt,'evt')
          });

          return div
      }
    
      btnGoBack.addTo(map)
    },
    goBack(map,evt) {

      
      if(this.parentCodeArr.length > 0) {
        let parentCode = this.parentCodeArr.pop()
        map.removeLayer(this.layer)
        //
        this.loadData(map, parentCode)
        
        console.log(evt,'goback#layer',parentCode)
      }
      // if(this.layer) {
        
       
      // }
      // if(this.layers.length <=0) {
      //   console.error("无历史数据")
      // }
      // //
   

      // let layer =  this.layers.pop()
      // console.log(layer, 'popLayer')
      // if(layer) {
      //   map.addLayer(layer)
      // }
    },
    // 自定义legend图例
    customerLegend(map) {
      var legend = L.control({position: 'bottomright'});

      legend.onAdd =  () => {

          var div = L.DomUtil.create('div', 'info legend'),
              grades = [0, 5, 10, 15, 18, 20, 25, 30];
              // labels = [];

          // loop through our density intervals and generate a label with a colored square for each interval
          for (var i = 0; i < grades.length; i++) {
              div.innerHTML +=
                  '<i style="background:' + this.getColor(grades[i] + 1) + '"></i> ' +
                  grades[i] + (grades[i + 1] ? '&ndash;' + grades[i + 1] + '<br>' : '+');
          }

          return div;
      }
      legend.addTo(map)
    },
    // 加载数据
    loadData(map, adcode = 100000 ) {
      //
      L.esri.Support.cors = true;
      let url = `https://geo.datav.aliyun.com/areas_v2/bound/${adcode}_full.json`

      $.getJSON(url, (result)=>{
        if(this.layer) {
          map.removeLayer(this.layer)
        }
        this.layer = L.geoJSON(result,{
          // style: ,
          onEachFeature: (feature, layer) => {
            layer.setStyle(this.getStyle(feature))
            // 设置图形颜色
            layer.on('mouseout',()=>{
              // console.log(e.target)
              //  layer.closePopup() 
              // 重置默认样式
              // geojson.resetStyle(e.target);
              // 重置已设置的样式
              layer.setStyle(this.getStyle(feature))
            })
            // 设置高亮
            layer.on('mouseover',(e)=>{
              // console.log(e.target,'target')
              var layer = e.target;

              layer.setStyle({
                  weight: 2,
                  color: '#666',
                  dashArray: '3', // 虚线
                  fillOpacity: 0.7
              });

              if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
                  layer.bringToFront();
              }

              // layerGroup.push(layer)
              // layer.bindPopup(this.getPopupContent(feature)).openPopup()  
            })
            layer.on('click',(e)=>{
              // console.log(e)
              
              layer.bindPopup(this.getPopupContent(feature)).openPopup()
              // 进入到feature
              map.fitBounds(e.target.getBounds());
              
              const adcode = e.target.feature.properties.adcode
              this.loadData(map, adcode)

              // const level = this.getZoom(e.target.feature.properties.level)
              // console.log(level,'level')
              // // 设置级别
              // map.setZoom(level)
              let parentCode = e.target.feature.properties.parent.adcode
              // let parentCodeArrLength = this.parentCodeArr.length
              //
              this.parentCodeArr.push(parentCode)
              //
            })
          },
        }).addTo(map)

        // 适应(居中)
        map.fitBounds(this.layer.getBounds());
        
        // this.layer = L.layerGroup(layerGroup)
        // console.log("layer", this.layer, 'group')
        this.layer.addTo(map)

        this.layers.push(this.layer)
        // console.log(this.layer, 'layer')
      })
      
    },
    // 初始化Map
    initMap() {
     
      var map = L.map(this.$refs.map).setView([36.058039,103.823557], 4);
      // L.esri.basemapLayer("Streets").addTo(map)
      this.customerButton(map)
      this.loadData(map)
      map.setMinZoom(4)
      // L.geoJSON('/assets/data/china.json').addTo(map)
      this.customerLegend(map)
    }
  }
}
</script>

<style scoped>
.map {
  height: 100vh;
  width: 100%;
}

.map >>> .info {
    padding: 6px 8px;
    font: 14px/16px Arial, Helvetica, sans-serif;
    background: white;
    background: rgba(255,255,255,0.8);
    box-shadow: 0 0 15px rgba(0,0,0,0.2);
    border-radius: 5px;
}
.map >>> .btn-go-back{
  font-size: 30px;
  cursor: pointer;
}

.info h4 {
    margin: 0 0 5px;
    color: #777;
}
/** >>> 使用因动态添加所以需要样式穿透 且 >>> 前面需要在源码中有的 不能是动态生成的*/
.map >>> .legend {
    line-height: 18px;
    color: #555;
}
.map >>> .legend i {
    width: 18px;
    height: 18px;
    float: left;
    margin-right: 8px;
    opacity: 0.7;
}
</style>