<template>
  <div style="position: relative;" v-loading='fullscreenLoading'>
    <div class='opensearch' @click='openSearch = true' v-if="!openSearch">
      查询
    </div>
    <div class='mapsearch' v-else>
      <span class="closeSearch" @click='openSearch = false'>
        <i class="el-icon-arrow-right"></i>
      </span>
      <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;margin-bottom:10px">
        <Input v-model="select.name" style="width: 200px;margin-right: 10px;" placeholder="搜索姓名" />
        <el-select class='street' v-model="select.street" placeholder="请选择街道" clearable>
          <el-option v-for="item in streetList" :key="item.value" :label="item.value" :value="item.value">
          </el-option>
        </el-select>
        <Button type="primary" @click="getindex">查询</Button>
      </div>
      <div>
        <Table :width="482" :max-height='280' @on-row-click='movetoperson' :height='280' highlight-row
          ref="currentRowTable" :columns="columns" :data="mapList" />
        <Page :current="select.page" :total="select.total" size="small" show-total show-elevator
          style="padding-top: 14px;display: flex;justify-content: center;" @on-change="pageChange" />
      </div>
    </div>
    <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>
  import {
    getparameter
  } from "@/api/system/dictionary";
  import {
    index
  } from "@/api/system/baseForm.js"
  export default {
    data() {
      return {
        zoom: 11,
        center: [119.597897, 31.723247],
        mapHeight: 0,
        map: null,
        makerList: [],
        infoWindow: null,
        openData: [],
        // markerList: [],
        mapList: [],
        fullscreenLoading: false,
        streetList: [],
        openSearch: false,
        select: {
          page_size: 50,
          page: 1,
          street: '',
          name: '',
          table_name: 'records',
          show_relation: ['admin', 'department'],
          total: 0
        },
        columns: [{
          title: '姓名',
          key: 'name',
        }, {
          title: '所属街道',
          key: 'street',
        }]
      }
    },
    mounted() {
      this.initHeight()
      getparameter({
        number: 'streetList'
      }).then(res => {
        this.streetList = res.detail
      })
      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, -10)
        })
      },
      // 加载金坛区
      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() {
        var that = this

        that.map.remove(that.makerList)
        that.makerList = []
        // this.map.clearMap();
        console.log("this.makerList", this.makerList)
        console.log("this.mapList", this.mapList)
        let list = this.mapList.map((m) => {
          return {
            id: m.id, //数据id
            name: m.name, //数据名称
            reside: m.reside,
            // lnglat: [m.lon, m.lat],//经纬度数据
            lnglat: [m.longitude, m.latitude], //这里我是转化一下，数据返回的是84坐标系需要转成高德坐标系否则会有偏差
            style: 0, //渲染的样式下标，关联第一步创建的样式对象数组的数据
          };
        });
        // this.$nextTick(() => {
        //   var mass = new AMap.MassMarks(list, {
        //     opacity: 0.8,
        //     zIndex: 111,
        //     cursor: 'pointer',
        //     style: {
        //       url: 'https://webapi.amap.com/images/mass/mass1.png',
        //       anchor: new AMap.Pixel(6, 6),
        //       size: new AMap.Size(11, 11),
        //       zIndex: 999,
        //     }
        //   });
        //   // var marker = new AMap.Marker({
        //   //   content: ' ',
        //   //   map: this.map,
        //   // });

        //   mass.on('mouseover', function(e) {
        //     console.log("e", e)
        //     that.openData = []
        //     // marker.setPosition(e.data.lnglat);
        //     // marker.setLabel({
        //     //   content: e.data.name
        //     // })
        //     that.openData.push(e.data)
        //     that.infoWindow.open(that.map, e.data.lnglat)
        //   });
        //   // 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())
        //   //   }),
        //   mass.setMap(this.map);
        // })

        this.mapList.forEach((item, index) => {
          // 遍历生成多个标记点
          if (!item.longitude || !item.latitude) {

            return
          }
          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())
            }),
            this.makerList.push(marker)
        });
        this.map.add(this.makerList)
      },
      closeWin() {
        this.infoWindow.close()
      },
      showInfo(id) {
        this.$router.push({
          path: "/record/personinfo",
          query: {
            id: id
          }
        })
      },
      pageChange(e) {
        this.select.page = e
        this.getindex()
      },
      movetoperson(row, index) {
        console.log(row)
        this.openData = []
        this.openData.push(row)
        this.map.panTo([row.longitude, row.latitude])
        this.infoWindow.open(this.map, [row.longitude, row.latitude])
      },
      async getindex() {
        this.fullscreenLoading = true;
        this.mapList = []
        // this.map.remove(this.marker)
        let res = await index({
          page_size: this.select.page_size,
          page: this.select.page,
          table_name: this.select.table_name,
          show_relation: this.select.show_relation,
          filter: [{
            "key": "name",
            "op": "like",
            "value": this.select.name
          }, {
            "key": "street",
            "op": "eq",
            "value": this.select.street
          }],
        })
        this.select.total = res.total
        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)
            }
          }
        }
        // return
        this.mapList = _data
        var geocoder = null
        let that = this
        AMap.plugin("AMap.Geocoder", function() {
          geocoder = new AMap.Geocoder({
            city: '常州市' // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
          })
          _nolng.map((k, index) => {
            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
              }
              if (index == _nolng.length - 1) {
                that.mapList.push(..._nolng)
                that.setMapMarker()
                that.fullscreenLoading = false;
              }
            })

          })
          // for (let k of _nolng) {

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



      },



    }

  }
</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;
  }

  .opensearch {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 99;
    color: #fff;
    width: 50px;
    height: 50px;
    background: #147d38;
    border-radius: 50px;
    text-align: center;
    line-height: 50px;
    cursor: pointer;
    font-weight: bold;
  }

  .mapsearch {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 99;
    background: #fff;
    padding: 10px;
  }
  .closeSearch{
    position: absolute;
    top: 40%;
    left: -20px;
    /* border: 1px solid red; */
    width: 40px;
    height: 40px;
    border-radius: 40px 0 0 40px;
    text-align: center;
    line-height: 40px;
    font-size: 22px;
    background: #fff;
    z-index: 99;
    cursor: pointer;
  }
  .street {
    margin-right: 10px
  }

  /deep/ .street .el-input__inner {
    height: 32px;
  }

  /deep/ .street .el-select__caret {
    line-height: 32px;
  }
</style>
