<template class="asMap">
  <div
      :class="{'asMapLocation':true,'showAsLocation':show}"
      :lazy-render="false"
      position="right"
      :style="{ height:'100%'}">
    <van-nav-bar
        :title="headerTitle"
        right-text="确定"
        left-arrow
        @click-left="show=!show"
        @click-right="confirm"
    />
    <van-search
        v-model="search"
        @search="handlesearch"
        :show-action="true"
        label="地址"
        placeholder="请输入搜索关键词"
    >
      <template #action>
        <div @click="handlesearch">搜索</div>
      </template>
    </van-search>
    <div class="content">
      <div id="bMap" >
        <div style="height:100%;width:100%" v-html="bMapDom"></div>
        <div class="geoLocation" @click="getNativeGPSInfo">
          <slot name="locationIcon">
            <van-icon class="geoLocationIcon" name="aim" />
          </slot>
        </div>
        <img :class="{'markerIcon':true,'jump':jump}" :src="markerIcon" alt="">
      </div>
      <ul class="addressList" v-show="addressList.length>0">
        <li class="addressItem" v-for="(item,index) in addressList" @click="updateAddress(item)" :key="index" >
          <div class="content">
            <div class="title">
              {{item.title}}
            </div>
            <div class="details">
              {{item.address}}
            </div>
          </div>
          <div v-show="pointDetail.point.lat===item.point.lat && pointDetail.point.lng===item.point.lng && pointDetail.title === item.title" class="selected"/>
        </li>
      </ul>
      <div class="noAddressList" v-show="addressList.length===0">
        未检索到附近相关建筑及商户
      </div>
    </div>
  </div>
</template>
<script>
function loadBmapScript(ak,cb){
  let script= document.createElement('script');
  if(window.BMap){
    cb()
    return ''
  }
  let funName=`asMapInit`+Date.now();
  script.type= 'text/javascript';
  script.src= `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=${funName}`;
  window[funName]=cb
  script.onload = script.onreadystatechange = function() {
    if ( !this.readyState || this.readyState === "loaded" || this.readyState === "complete" ){
      script.onload = script.onreadystatechange = null;
    }
  };
  document.body.appendChild(script);
}
import { Popup ,Toast ,NavBar ,Search , Icon } from 'vant';
export default{
  name:'AsMapLocation',
  props:{
    address:{
      type: String
    },
    getLocation:{
      type: Function
    },
    markerIcon:{
      type: Object | String,
      default: require('../../assets/images/map-marker-default.png')
    },
    ak:{
      type:String,
      require:true
    },
    headerTitle:{
      type:String,
      default:'详细地址'
    }
  },
  //     event: 'updateAddress'
  components:{
    VanIcon: Icon,
    VanNavBar: NavBar,
    VanPopup: Popup,
    VanSearch: Search
  },
  data(){
    return{
      map:'',//初始化的地图
      search:'',
      show:false,
      addressList:[],//查询过后的列表
      marker:'',//百度地图覆盖物标识对象
      localSearch:'',//智能检索对象
      gc:'',//地址解析器
      pointDetail:{},//当前是选中的是哪个点的详细信息
      cityDetail:{},
      bMapDom:'',
      bMapId:'',
      Icon:'',
      jump:false,//控制中心点的覆盖物是否跳起
    }
  },
  mounted(){
    this.bMapId='map'+Date.now();
    this.bMapDom=`<div style="overflow: hidden;height:6.4rem;width:100%" id="${this.bMapId}"></div>`;
    loadBmapScript(this.ak,()=>{
      this.$nextTick(()=>{
        this.installMap();
      })
    })
  },
  methods:{
    handlesearch(){
      this.search && this.localSearch.search(this.search)
    },
    showPop(){
      this.show=!this.show;
      this.$nextTick(()=>{
        //使用壳子的sdk定位
        if(!this.address){
          //没回显要判断一下 只有this.address===''的时候才获取定位
          this.getNativeGPSInfo();
        }else{
          this.localSearch.search(this.address)
        }
      })
    },
    confirm(){
      //更新前先附以下值给内部 避免更新Address后再次触发watch
      let address= this.pointDetail.title === '当前位置' ? this.pointDetail.address:this.pointDetail.address+this.pointDetail.title;
      this.$emit('change',this.pointDetail,this.cityDetail)
      this.show=false;
    },
    //更新绑定的值
    updateAddress(value){
      if(!value) return
      this.map.setCenter(value.point);
      this.pointDetail=value;
    },
    //获取Native定位信息
    getNativeGPSInfo() {
      this.getLocation().then(res=>{
        const point = new BMap.Point(res.lng, res.lat);
        this.addressAnalysis(point);
      }).catch(err=>{
        Toast('获取当前地址失败')
      })
    },
    installMap(){
      this.map = new BMap.Map(this.bMapId);
      let point = new BMap.Point(116.404, 39.915);  // 创建点坐标
      this.map.centerAndZoom(point,17) //初始化设置地图
      this.map.enableScrollWheelZoom(); //开启滚轮缩放
      let searchCallBack = (onSearchRes)=>{
        this.addressList = [...onSearchRes];
        this.updateAddress(this.addressList[0] || '')//搜索到值以后存储第一个智能搜索的信息
      };
      //初始化一个poi检索器
      this.gc = new BMap.Geocoder();
      //初始化智能搜索功能
      this.localSearch = new BMap.LocalSearch(this.map, { //智能搜索
        onSearchComplete: (onSearchResArr)=> {
          console.log('onSearchRes',onSearchResArr)
          let onSearchRes=[];
          for (var i = 0; i < onSearchResArr.getCurrentNumPois(); i ++){
            onSearchRes.push(onSearchResArr.getPoi(i));
          }
          //如果是通过智能搜索器这里应该再查一下因为，取城市数组是在addressAnalysis进行的
          if(onSearchRes.length>0 && !!onSearchRes){
            this.gc.getLocation(onSearchRes[0].point,(res)=>{
              console.log('getLocation',res)
              this.cityDetail=res.addressComponents;
              //     //东菀市没有区和县
              this.cityDetail.district=='' && (this.cityDetail.district=this.cityDetail.city);
              searchCallBack(onSearchRes);
            },{
              poiRadius:1000,//搜索点范围1000米
            });
          }else{
            Toast('未查找到相关信息!\n请确认您搜索的内容是否正确!')
          }
        }
      });
      //添加拖拽效果
      this.map.addEventListener('touchend',()=>{
        setTimeout(()=>{
          this.addressAnalysis(this.map.getCenter());
        },200)
        this.jump=false;
      })
      this.map.addEventListener('touchstart',()=>{
        this.jump=true
      })
    },
    //地址解析器
    addressAnalysis(point){
      this.gc.getLocation(point,(res)=>{
        this.cityDetail=res.addressComponents;
        //东菀市没有区和县
        this.cityDetail.district=='' && (this.cityDetail.district=this.cityDetail.city);
        this.addressList = [{
          address:res.address,
          point:point,//这个point不要用检索到的point
          title :res.title||'当前位置'
        },...res.surroundingPois]
        // 定位的点可能为空
        this.updateAddress(this.addressList[0]||'')//搜索到值以后存储第一个智能搜索的信息
      },{
        poiRadius:1000,//搜索点范围1000米
      });
    },
  }
}
</script>
<style scoped lang="scss">
@import "../../assets/scss/define";

.asMapLocation{
  position: fixed;
  top: 0;
  bottom: 0;
  width: 100%;
  box-sizing: border-box;
  left: 100%;
  transition: left .3s;
  &.showAsLocation{
    left: 0;
  }
  & /deep/ {
    .van-nav-bar{
      background:#40aeff;
      .van-icon,.van-nav-bar__title,.van-nav-bar__text{
        color:#ffffff;
      }
    }
  }
  & /deep/ .van-popup--right{
    overflow: hidden;
  }
  .content{
    flex: 1;
    display: flex;
    flex-direction: column;
    height: calc(100% - 40px - 54px);
    #bMap{
      position: relative;
      width:100%;
      margin:0 auto;
      height: 6.4rem;
      /deep/ .anchorBL{
        display: none;
      }
      .markerIcon{
        position: absolute;
        top: 50%;
        left: 50%;
        width: 0.4rem;
        height: 0.66rem;
        transform: translate(-50%, -50%);
        transition: transform .3s ease;
      }
      .jump{
        transform: translate(-50%, -100%);
      }
      .geoLocation {
        position: absolute;
        bottom: 0.5rem;
        right: 0.4rem;
        width: 0.7rem;
        height: 0.7rem;
        .geoLocationIcon{
          width: 100%;
          height: 100%;
          background: #ffffff;
          text-align: center;
          line-height: .7rem;
          border-radius: 0.4rem;
          box-shadow: 0 0 0.1rem #7e7e7e;
          font-size: .46rem;
          color: #40aeff;
        }
      }
    }
    .noAddressList{
      position: relative;
      margin-top: -0.3rem;
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex: 1;
      color: #a0a0a0;
      font-size: .4rem;
      background: #fff;
      overflow: auto;
      padding-top: 0.1rem;
      border-top-left-radius: 0.3rem;
      border-top-right-radius: 0.3rem;
    }
    .addressList{
      position: relative;
      margin-top: -0.3rem;
      width: 100%;
      flex: 1;
      background: #fff;
      overflow: auto;
      padding-top: 0.1rem;
      border-top-left-radius: 0.3rem;
      border-top-right-radius: 0.3rem;
      .addressItem{
        padding:.3rem .4rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom:1px solid rgba(221, 221, 221, 1);
        .selected{
          width: 0.16rem;
          height: 0.3rem;
          border-color: #40aeff;
          border-style: solid;
          border-width: 0 0.08rem 0.08rem 0;
          transform: rotate(45deg);
          margin-left: 0.2rem;
        }
        .content{
          flex: 1;
          .title{
            font-size: .30rem;
            font-weight: bold;
          }
          .details{
            font-size: .24rem;
            margin-top: .06rem;
            color: rgba(102, 102, 102, 1);
          }
        }

      }
    }
  }
}
</style>