<template>
  <el-dialog title="选择当前位置" :visible.sync="mapVisible" :fullscreen=false  id="mapDialog" :close-on-click-modal="false" style="margin-top: 8.5vh;">
    <div style="margin-bottom: 10px">
      <label>搜索关键词：
        <el-autocomplete
          v-model="keyword"
          style="width: 400px"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          @select="handleSelect"
        ></el-autocomplete></label>
    </div>
    <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler"
               :scroll-wheel-zoom="true"
               @click="clickEvent">
      <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
      <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
      <bm-view :style="{width:'100%',height: '300px',flex: 1,marginTop:'0px'}"></bm-view>
    </baidu-map>
    <div class="demo-input-suffix" style="margin-top: 2vh">
      <el-link type="info">经度：</el-link><el-input  class="lineinput"  style="width:100px" size="mini" v-model.number="locData.longitude" :disabled="true"></el-input>
      <el-link type="info"> 纬度：</el-link><el-input  class="lineinput"  style="width:100px" size="mini" v-model.number="locData.latitude" :disabled="true"></el-input>
      <el-link type="info"> 位置：</el-link><el-input  class="lineinput"  style="width:300px" size="mini" v-model="locData.address" :disabled="true"></el-input>
    </div>
    <div slot="footer" class="dialog-footer" style="margin-top: -30px">
      <el-button type="warning"  size="small" icon="el-icon-close" @click.native="mapVisible = false">取消</el-button>
      <el-button type="primary" size="small" icon="el-icon-check" @click.native="findlocation">确定</el-button>
    </div>
  </el-dialog>
</template>


<script>
    import {BaiduMap,BmNavigation,BmView,BmGeolocation,BmCityList,BmLocalSearch} from 'vue-baidu-map';
    import {SystemGetRegion} from "../../api/system/pub";
    export default {
        name: "ui-map",
        components: {
            BaiduMap,
            BmNavigation,
            BmView,
            BmGeolocation,
            BmCityList,
            BmLocalSearch
        },
        data() {
            return {
                keyword: '',
                center: {lng: 121.419054, lat: 28.659155},
                region : "台州市",
                zoom: 12,
                mapVisible:false,
                locData:{
                    longitude:'',
                    latitude:'',
                    address:'',
                },
                iconUrl:'http://api0.map.bdimg.com/images/marker_red_sprite.png',
                map : null,
                mapData : {},
                mapVal : []
            }
        },

        created() {

        },
        methods: {
            showMap:function(item){
               this.mapVisible = true;
               if(item.address == '' || item.lng == '' || item.lat == '') {
                   if(this.map != null) {
                       this.handleSelect(item);
                   }

               }
            },
            handler ({BMap, map}) {
               // this.$utils.loading(this,"加载数据中");
                let _this = this;  // 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
                let geolocation = new BMap.Geolocation();
                geolocation.getCurrentPosition((r) => {
                    console.log(r);
                    _this.center = {lng: r.longitude, lat: r.latitude};   // 设置center属性值
                    this.region = r.address.city;
                    console.log(r.address)
                    _this.autoLocationPoint = {lng: r.longitude, lat: r.latitude};  // 自定义覆盖物
                    _this.initLocation = true;
                   // this.$utils.loadingClose();
                },{enableHighAccuracy: true})
                window.map = map;
                this.map = map;
            },
            /**
             * 点击地图监听
             * @param e
             */
            clickEvent(e){
                map.clearOverlays();
                let Icon_0 = new BMap.Icon("http://api0.map.bdimg.com/images/marker_red_sprite.png", new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 25)});
                let myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat),{icon: Icon_0});
                map.addOverlay(myMarker);
                //用所定位的经纬度查找所在地省市街道等信息
                let point = new BMap.Point(e.point.lng, e.point.lat);
                let gc = new BMap.Geocoder();
                let _this = this;
                gc.getLocation(point, function (rs) {
                    let addComp = rs.addressComponents;
                    _this.locData.address = rs.address;

                });
                this.locData.longitude = e.point.lng;
                this.locData.latitude = e.point.lat;
            },
            /**
             * 检索参数
             */
            querySearchAsync(queryString, cb) {
                if(queryString == '') {
                    cb([]);
                    return;
                }
                if(this.mapData[queryString] != null) {
                    cb(this.mapData[queryString]);
                    return;
                }
                SystemGetRegion({
                    region:this.region,
                    keyword:queryString
                })
                    .then(res=>{
                        if(res.code == 200) {
                            var dAr = [];
                            for(var i in res.data) {
                                dAr.push({
                                    value   : res.data[i].name,
                                    data    : res.data[i]
                                });
                            }
                            this.mapData[queryString] = dAr;
                            cb(dAr);
                        } else {
                            cb([]);
                        }
                    })
                    .catch(err=>{});
            },
            /**
             *
             */
            handleSelect:function (data) {
                var item = data.data;
                this.map.clearOverlays();
                let Icon_0 = new BMap.Icon("http://api0.map.bdimg.com/images/marker_red_sprite.png", new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 25)});
                let myMarker = new BMap.Marker(new BMap.Point(item.location.lng, item.location.lat),{icon: Icon_0});
                console.log(myMarker);
                this.map.addOverlay(myMarker);
                this.center = {lng:item.location.lng, lat:item.location.lat};
                this.zoom = 16;
                this.locData.address = item.address == null ? item.name : item.address;
                this.locData.longitude = item.location.lng;
                this.locData.latitude = item.location.lat;
            },

            findlocation:function () {
                this.mapVisible = false;
                this.$emit('submit',this.locData);
            }

        }
    }
</script>
<style scoped>

</style>
