<template>
  <div>
    <div id="container" tabindex="0"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
export default {
  name: 'amap',
  data() {
    return {
      AMap: null,
      map: null,
      lngLat: [106.628201, 26.646694],
      adName: '',
      zoom: 8,
      adcode: '贵州省',
      mapLevel: 'province',
      province: '',
      districtExplorer: null,
      tipMarker: null,
      $tipMarkerContent: null,
      currentAreaNode: null
    };
  },

  mounted() {
    // this.initMAp();
    this.initAMap();
  },
  created() {},
  methods: {
    initAMap() {
      let _this = this;
      window._AMapSecurityConfig = {
        securityJsCode: '4a6a8d8ea053d9aa8f4677ee1179fe57' // 密钥
      };
      AMapLoader.load({
        key: '58f9d9f14f2700689ddbc618495693b7', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '1.4.15', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        AMapUI: {
          // 是否加载 AMapUI，缺省不加载
          version: '1.1', // AMapUI 缺省 1.1
          plugins: ['overlay/SimpleMarker'] // 需要加载的 AMapUI ui插件
        }
        // plugins:['AMap.ToolBar','AMap.DistrictSearch','AMap.Object3DLayer','AMap.Object3D'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        _this.AMap = AMap;
        _this.map = new AMap.Map('container', {
          //设置地图容器id
          viewMode: '3D', //是否为3D地图模式
          terrain: true,
          zoom: _this.zoom, //初始化地图级别
          center: _this.lngLat, //初始化地图中心点位置
          pitch: 30,
          layers: [
            new AMap.TileLayer.Satellite(),
            new AMap.TileLayer.RoadNet()
          ],
          features: ['road', 'bg', 'building'] //地图要素
        });
        AMapUI.load(
          ['ui/geo/DistrictExplorer', 'lib/$'],
          function (DistrictExplorer) {
            _this.loadMapData(DistrictExplorer, $);
          }
        );
        // this.$nextTick(() => {
        //   // this.getDistrict()
        // });
      });
    },
    getDistrict(adName, mapLevel) {
      let that = this;
      AMap.plugin(['AMap.DistrictSearch'], function () {
        var district = new AMap.DistrictSearch({
          // 返回行政区边界坐标等具体信息
          extensions: 'all',
          // 设置查询行政区级别为 区 （district）
          level: mapLevel,
          //  显示下级行政区级数，1表示返回下一级行政区
          subdistrict: 1
        });
        district.search(adName, function (status, result) {
          var outer = [
            new AMap.LngLat(-360, 90, true),
            new AMap.LngLat(-360, -90, true),
            new AMap.LngLat(360, -90, true),
            new AMap.LngLat(360, 90, true)
          ];
          var holes = result.districtList[0].boundaries;
          var pathArray = [outer];
          pathArray.push.apply(pathArray, holes);
          var polygon = new AMap.Polygon({
            pathL: pathArray,
            strokeColor: '#00eeff',
            strokeWeight: 1,
            fillColor: '#1c212a', // 遮罩背景色黑色
            fillOpacity: 0.8
          });
          polygon.setPath(pathArray);
          that.map.add(polygon);

          // AMap.plugin(['AMap.Object3DLayer', 'AMap.Object3D'], function () {
          //   //object3Dlayer可以看做一个容器,用来放多个3d对象
          //   let object3Dlayer = new AMap.Object3DLayer();
          //   //把object3Dlayer添加到map对象中
          //   that.map.add(object3Dlayer);
          //   var wall = new AMap.Object3D.Wall({
          //     //版块边界线
          //     path: holes,
          //     //墙的高度
          //     height: 80000,
          //     //墙的颜色
          //     color: '#0dcdd1'
          //   });
          //   //wall 有两个面,该属性表示哪个面可见,可选值:back ,front ,both表示两面  默认为front
          //   wall.backOrFront = 'both';
          //   // 是否允许使用透明颜色
          //   wall.transparent = true;
          //   //将wall放到object3Dlayer中
          //   object3Dlayer.add(wall);
          //   console.log('object3Dlayer');
          // });
        });
      });
    },
    loadMapData(DistrictExplorer, $) {
      let that = this;
      //创建一个实例
      that.districtExplorer = window.districtExplorer = new DistrictExplorer({
        eventSupport: true, //打开事件支持
        map: that.map
      });
      //当前聚焦的区域
      this.$tipMarkerContent = $('<div class="tipMarker top"></div>');
      this.tipMarker = new AMap.Marker({
        content: this.$tipMarkerContent.get(0),
        offset: new AMap.Pixel(0, 0),
        bubble: true
      });
      //监听feature的hover事件
      this.districtExplorer.on(
        'featureMouseout featureMouseover',
        (e, feature) => {
          this.toggleHoverFeature(
            feature,
            e.type === 'featureMouseover',
            e.originalEvent ? e.originalEvent.lnglat : null
          );
        }
      );
      //监听鼠标在feature上滑动
      this.districtExplorer.on('featureMousemove', (e) => {
        //更新提示位置
        this.tipMarker.setPosition(e.originalEvent.lnglat);
      });
      var adName = that.adcode; //贵州省
      var mapLevel = that.mapLevel;
      var adcode = '520000';
      //feature被点击
      this.districtExplorer.on('featureClick', (e, feature) => {
        that.map.clearMap();
        const props = feature.properties;
        this.switch2AreaNode(props.adcode);
        mapLevel = props.level;
        adName = props.name;
        that.getDistrict(adName, mapLevel);
      });
      this.switch2AreaNode(adcode);
      that.getDistrict(adName, mapLevel);
    },
    //根据Hover状态设置相关样式
    toggleHoverFeature(feature, isHover, position) {
      if (feature.properties.subFeatureIndex != null) {
        this.tipMarker.setMap(isHover ? this.map : null);
        if (!feature) {
          return;
        }
        const props = feature.properties;
        if (isHover) {
          //更新提示内容
          this.$tipMarkerContent.html(props.name);
          //更新位置
          this.tipMarker.setPosition(position || props.center);
        }
        //更新相关多边形的样式
        const polys = this.districtExplorer.findFeaturePolygonsByAdcode(
          props.adcode
        );
        polys.forEach((elemnt) => {
          elemnt.setOptions({
            fillOpacity: isHover ? 0.5 : 0
          });
        });
      }
    },
    //绘制某个区域的边界
    renderAreaPolygons(areaNode) {
      //更新地图视野
      if (!this.aReContry) {
        this.map.setBounds(areaNode.getBounds(), null, null, true);
      } else {
        this.map.setZoom(4);
        this.map.setCenter(new AMap.LngLat(103.714129, 38.150339));
      }
      //清除已有的绘制内容
      this.districtExplorer.clearFeaturePolygons();
      //绘制子区域
      this.districtExplorer.renderSubFeatures(areaNode, () => {
        return {
          cursor: 'default',
          bubble: true,
          strokeColor: 'yellow', //线颜色
          strokeOpacity: 1, //线透明度
          strokeWeight: 2, //线宽
          fillOpacity: 0 //填充透明度
        };
      });
      //绘制父区域
      this.districtExplorer.renderParentFeature(areaNode, {
        cursor: 'default',
        bubble: true,
        strokeColor: '#00eeff', //线颜色
        strokeOpacity: 1, //线透明度
        strokeWeight: 2, //线宽
        fillOpacity: 0 //填充透明度
      });
    },
    //切换区域后刷新显示内容
    refreshAreaNode(areaNode) {
      this.districtExplorer.setHoverFeature(null);
      this.renderAreaPolygons(areaNode);
    },
    //切换区域
    switch2AreaNode(adcode, callback) {
      if (
        this.currentAreaNode &&
        '' + this.currentAreaNode.getAdcode() === '' + adcode
      ) {
        return;
      }
      this.loadAreaNode(adcode, (error, areaNode) => {
        if (error) {
          if (callback) {
            callback(error);
          }
          return;
        }
        this.currentAreaNode = areaNode;
        //设置当前使用的定位用节点
        this.districtExplorer.setAreaNodesForLocating([this.currentAreaNode]);
        this.refreshAreaNode(areaNode);
        if (callback) {
          callback(null, areaNode);
        }
      });
    },
    // 加载区域
    loadAreaNode(adcode, callback) {
      this.districtExplorer.loadAreaNode(adcode, (error, areaNode) => {
        if (error) {
          if (callback) {
            callback(error);
          }
          window.console.error(error);
          return;
        }

        if (callback) {
          callback(null, areaNode);
        }
      });
    }
  }
};
</script>

<style  lang='scss' scoped>
#container {
  width: 100%;
  height: 100vh;
  /deep/ .tdt-pane {
    z-index: auto;
  }
}
/deep/ .amap-marker-content {
  .tipMarker {
    color: #555;
    background-color: rgba(255, 254, 239, 0.8);
    border: 1px solid #7e7e7e;
    padding: 2px 6px;
    font-size: 12px;
    white-space: nowrap;
    display: inline-block;
    &:before,
    &:after {
      content: '';
      display: block;
      position: absolute;
      margin: auto;
      width: 0;
      height: 0;
      border: solid transparent;
      border-width: 5px 5px;
    }
    &.top {
      transform: translate(-50%, -110%);
      &:before,
      &:after {
        bottom: -9px;
        left: 0;
        right: 0;
        border-top-color: rgba(255, 254, 239, 0.8);
      }
      &:before {
        bottom: -10px;
        border-top-color: #7e7e7e;
      }
    }
  }
}
/deep/ .amap-logo,
.amap-copyright {
  display: block !important;
  visibility: inherit !important;
}
</style>
