<template>
  <div v-loading='fullscreenLoading'>
    <div class="map" id="map" :style="{'height':mapHeight+'px'}"></div>
    <div ref='infoWindow' id="infoWindow">
      <i @click='closeWin' class="el-icon-close"></i>
      <div v-for="item in openData">
        <p>姓名：<span>{{item.name}}</span></p>
        <p>现居住地：<span>{{item.reside}}</span></p>
        <p class="showInfo" @click="showInfo(item.id)">人员视图</p>
      </div>
    </div>
  </div>

</template>
<script>
  // 建议将zoom,center等可配置的项均写在配置文件中，方便打包之后进行修改。
  import {
    index
  } from "@/api/system/baseForm.js"
  export default {
    data() {
      return {
        zoom: 11,
        center: [119.597897, 31.723247],
        mapHeight: 0,
        map: null,
        infoWindow: null,
        openData: [],
        // markerList: [],
        mapList: [],
        fullscreenLoading: false
      }
    },
    mounted() {
      this.initHeight()
      this.$nextTick(function() {
        this.mapInit()
      })
      this.getindex()
    },
    methods: {
      // openFullScreen() {
      //   this.fullscreenLoading = true;
      //   setTimeout(() => {
      //     this.fullscreenLoading = false;
      //   }, 2000);
      // },
      async initHeight() {
        let winHeight = document.body.clientHeight
        this.mapHeight = winHeight - 50 - 20
      },
      // 初始化地图，并加载行政区域
      async mapInit() {
        this.map = new AMap.Map("map", {
          center: this.center,
          mapStyle: "amap://styles/bfb1bb3feb0db7082367abca96b8d214", // 设置地图的显示样式
          zoom: this.zoom
        });
        // 行政区域加载
        let that = this
        let adcode = ['320413'];
        this.areaBG(this.map, adcode);
        this.infoWindow = new AMap.InfoWindow({
          isCustom: true,
          autoMove: true,
          avoid: [20, 20, 20, 20],
          content: this.$refs.infoWindow,
          closeWhenClickMap: true,
          offset: new AMap.Pixel(-10, -40)
        })
      },
      // 加载金坛区
      areaBG(map, adcode) {
        AMap.service('AMap.DistrictSearch', function() {
          let opts = {
            subdistrict: 1, // 返回下一级行政区
            extensions: 'all', // 返回行政区边界坐标组等具体信息
            level: 'city', // 查询行政级别为市
            // adcode:'320413'
          };
          // 实例化DistrictSearch
          let district = new AMap.DistrictSearch(opts);
          district.setLevel('district');
          // 行政区查询
          district.search(`${adcode}`, function(status, result) {
            // 获取边界信息
            let bounds = result.districtList[0].boundaries;
            let polygons = [];
            if (bounds) {
              for (let i = 0, l = bounds.length; i < l; i++) {
                // 生成行政区划polygon
                let polygon = new AMap.Polygon({
                  map: map,
                  strokeWeight: 1,
                  path: bounds[i],
                  fillOpacity: 0.2,
                  fillColor: 'rgba(71,228,194,1)',
                  strokeColor: '#147d38'
                });
                polygons.push(polygon);
              }
            }
          });
        });
      },
      // 增加点位
      setMapMarker() {
        let makerList = []
        this.mapList.forEach((item) => {
          // 遍历生成多个标记点
          let marker = new AMap.Text({
            map: this.map,
            text: item.name,
            zIndex: 9999999,
            offset: new AMap.Pixel(-13, -30),
            position: [item.longitude, item.latitude],
            clickable: true,
            extData: item.id,
            style: {
              'border': '1px solid red',
              'padding': '0px 5px'
            }
          })
          marker.on('click', (e) => {
              this.openData = []
              if (e.target.w.extData === item.id) {
                this.openData.push(item)
              }
              this.infoWindow.open(this.map, e.target.getPosition())
            }),
            makerList.push(marker)
        });
        this.map.add(makerList)
        // 自动适应显示想显示的范围区域
      },
      closeWin() {
        this.infoWindow.close()
      },
      showInfo(id) {
        this.$router.push({
          path: "/record/personinfo",
          query: {
            id: id
          }
        })
      },
      async getindex() {
        this.fullscreenLoading = true;
        let res = await index({
          page_size: 99999,
          page: 1,
          table_name: 'records',
        })
        let _data = []
        let _nolng = [] //只有地址没有经纬度
        for (var k of res.data) {
          if (k.longitude && k.latitude) {
            _data.push(k)
          } else {
            if (k.reside == null || k.reside == '') {
              // return
            }else{
              _nolng.push(k)
            }
          }
        }
        console.log(_nolng)
        // return
        this.mapList = _data
        var geocoder = null
        let that = this
        AMap.plugin("AMap.Geocoder", function() {
          geocoder = new AMap.Geocoder({
            city: '常州市' // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          })
          for (let k of _nolng) {
            geocoder.getLocation(k.reside, function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                // result中对应详细地理坐标信息

                k.longitude = result.geocodes[0].location.lng
                k.latitude = result.geocodes[0].location.lat
              }
            })

          }
        })
        setTimeout(function() {
          that.mapList.push(..._nolng)
          that.setMapMarker()
          that.fullscreenLoading = false;
        }, 1000);



      },



    }

  }
</script>
<style scoped>
  #infoWindow {
    position: relative;
  }

  #infoWindow>div {
    background: #fff;
    border: 1px solid red;
    padding: 10px;
    width: 180px;
  }

  /deep/ #infoWindow .el-icon-close {
    position: absolute;
    top: 5px;
    right: 5px;
    cursor: pointer;
  }

  .showInfo {
    text-align: center;
    cursor: pointer;
    color: #147d38;
  }
</style>
