<template>
  <div class="main-header" style="z-index: 2">
    <!--响应式工具  .visible-xs 手机 (<768px)  .visible-sm 平板 (≥768px)  可见-->
    <div class="row">
      <div class="col-sm-12 col-md-12  col-xs-12 maptop">
        <div class="col-md-1 col-sm-2 col-xs-3" v-if="isshowcity">
          <button type="button" class="citybtn"  @click="showMobiCityPicker">
            <div class="city" style="">{{thiscity}}</div>
            <div class="citygly glyphicon glyphicon-menu-down" aria-hidden="true"></div>
          </button>
        </div>
        <div :class="isshowcity ? 'col-md-11 col-sm-10 col-xs-9 d1': 'col-md-12 col-sm-12 col-xs-12 d1'" >
          <div class="d2" :style="showCancel ? 'width: 80%' : 'width: 100%'">
            <div class="search">
              <svg class="icon searchicon" t="1629093714025" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2215" width="200" height="200"><path d="M990.980258 969.944422l-185.094554-185.094554c83.911344-83.23135 135.990938-198.518449 135.990938-325.781454C941.876642 205.950391 735.934251 0 482.824228 0 229.698205 0 23.747814 205.950391 23.747814 459.076413c0 253.142022 205.950391 459.060414 459.076414 459.060414 103.079195 0 198.334451-34.167733 275.037851-91.759283l188.342529 188.342528c6.183952 6.183952 14.279888 9.271928 22.383825 9.271928s16.199873-3.087976 22.391825-9.271928a31.655753 31.655753 0 0 0 0-44.77565zM87.06732 459.076413c0-218.222295 177.534613-395.748908 395.756908-395.748908 218.206295 0 395.732908 177.526613 395.732908 395.748908 0 218.198295-177.526613 395.740908-395.732908 395.740909-218.222295 0-395.756908-177.542613-395.756908-395.740909z" fill="#838384" p-id="2216"></path></svg>
            </div>
            <input type="search" placeholder="搜索地点" style="width: 90%"
                   v-model="searchText" id="mobileSearch"
                   @click="searchInputClick" @focus="showCancel = true"
                   class="col-xs-10">
            <div class="remove" v-if="searchText" @click="closeSearchList">
              <svg class="icon" t="1629094394281"  viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3295" width="200" height="200"><path d="M75.170909 160.907636L108.101818 128 937.192727 957.114182l-32.907636 32.907636z" p-id="3296"></path><path d="M75.194182 957.114182L904.308364 128l32.907636 32.907636L108.101818 990.021818z" p-id="3297"></path></svg>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  title: "地图搜索组件",
  props:{
    // 每次查询条数，最大50 大于50按50算
    pagesize:{
      type: Number,
      default: 20
    },
    // 是否返回详细地址信息
    extensions: {
      type: Boolean,
      default: true
    },
    // 是否显示城市选择组件
    isshowcity:{
      type: Boolean,
      default: true
    },
    // 当前城市
    thiscity:{
      require:true,
      type:String,
      default:'请选择城市'
    },
    // 当前城市编码
    thiscitycode: {
      require:false,
      type:String,
      default:''
    },
    // 列表中的值
    model: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      searchText: '', // 搜索框的值
      lastSearchText:'',//上次搜索框的值
      placeSearch: null,// 搜索组件的对象
      isfullSearch: '', //返回基本信息还是详细信息 base 或者 all 与extensions关联
      resResult: {}, //响应结果,未使用
      pageCount: 0, //总页数
      pagenumber: 1,//当前页
      cityPicker: null,// 城市选择组件实例
    }
  },
  methods : {
    // 输入框被点击
    searchInputClick(){
      if (this.isshowcity) { // 城市选择组件显示
        this.$emit('searchinputclick',this.thiscity) //输入框被点击返回当前选择的城市
      }else {
        this.$emit('searchinputclick')
      }
    },
    // 初始化地图POI搜索组件
    initAmapSearch(){
      this.isfullSearch = this.extensions===false?'base':'all' //是否查询详情
      AMap.plugin(['AMap.AutoComplete','AMap.PlaceSearch'],()=>{
        this.placeSearch = new AMap.PlaceSearch({
          // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
          pageSize: this.pagesize,
          lang: 'zh_cn',
          extensions: this.isfullSearch //此项默认值：base，返回基本地址信息  取值：all，返回基本+详细信息
        })
      })
      //搜索成功
      if (AMap.Event){
        AMap.Event.addListener(this.placeSearch, 'complete', (e)=>{
          this.pagenumber = this.pagenumber + 1 // 每次查询成功都会给当前页+1 也就是下次查询页
          this.pageCount=e.poiList.count;//赋值查询后的总页数
          // 抛出的值组装
          let res = {'status':'complete','result':e,'pagecount': e.poiList.count}
          this.$emit('retres',res); // 请求后触发事件，将poi搜索的值返回 --正确或者失败都会触发  在返回值的status为complete为成功，为error为失败
          this.$emit('retsuccess',res); // 搜索成功事件
        })
      } else {
        AMap.event.addListenerOnce(this.placeSearch, 'complete', (e)=>{
          this.pagenumber = this.pagenumber + 1 // 每次查询成功都会给当前页+1 也就是下次查询页
          this.pageCount=e.poiList.count;//赋值查询后的总页数
          // 抛出的值组装
          let res = {'status':'complete','result':e,'pagecount': e.poiList.count}
          this.$emit('retres',res); // 请求后触发事件，将poi搜索的值返回 --正确或者失败都会触发  在返回值的status为complete为成功，为error为失败
          this.$emit('retsuccess',res); // 搜索成功事件
        })
      }
      if (AMap.Event){
        //搜索失败
        AMap.Event.addListener(this.placeSearch, 'error', (e)=>{
          // 抛出的值组装
          let res={'status':'error','result':e,'pagecount': 0}
          this.$emit('retres',res); // 请求后触发事件，将poi搜索的值返回 --正确或者失败都会触发  在返回值的status为complete为成功，为error为失败
          this.$emit('reterror',res); // 搜索失败事件
        })
      } else {
        //搜索失败
        AMap.event.addListener(this.placeSearch, 'error', (e)=>{
          // 抛出的值组装
          let res={'status':'error','result':e,'pagecount': 0}
          this.$emit('retres',res); // 请求后触发事件，将poi搜索的值返回 --正确或者失败都会触发  在返回值的status为complete为成功，为error为失败
          this.$emit('reterror',res); // 搜索失败事件
        })
      }

    },
    // 同步搜索 （搜索内容）
    syncSearch() {
      //如果显示选择城市组件，则城市选择组件就为必选
      if (this.isshowcity===true && this.thiscity==='请选择城市') {
        this.searchText = '' //清空输入框内容
        return this.$showMessage("请选择城市！")
      }
      // 如果当前总数是0，则不判断是否到最下部最后一页
      if (this.pageCount!==0) {
        // 计算当前页 总条数除以当前页大小
        if (this.$parent.mainList.rows.length === this.pageCount){ //如果当前页等于总页数
          console.log("挖空了！已经到底了！")
          return this.$emit('endcount') //当到达最后一页触发
        }
      }
      // 设置分页参数和城市信息去搜索
      if (this.searchText.trim()) {
        this.placeSearch.setPageIndex(this.pagenumber); //页码
        this.placeSearch.setCity(this.thiscity); //设置城市
        this.placeSearch.search(this.searchText) //搜索
      }else {
        console.log('查询内容有误')
      }
    },
    // 清楚搜索结果
    clearSearch () {
      this.placeSearch.clear();
    },
    //初始化城市选择
    async initMobiCityPicker () {
      this.cityPicker = null
      await AMapUI.loadUI(['misc/MobiCityPicker'], (MobiCityPicker) => {
        //动态加载自定义的红色主题， 如果css已经写在当前页面中，可忽略此步骤
        this.cityPicker = new MobiCityPicker({
          //设置主题（同名的className会被添加到外层容器上）
          theme: 'common'
        });
        //监听城市选中事件
        this.cityPicker.on('citySelected', (cityInfo) => {
          // 输出选中城市信息
          console.log(cityInfo);
          this.thiscity = cityInfo.adcode;//设置城市编码为当前选中城市
          this.thiscity = cityInfo.name;//设置当前选中的城市名
          this.$emit("mobicity", cityInfo) //选中城市后
          this.clearMobiCityPicker()
          // 以选中的当前城市为中心并zoom为15；
          //当前地点可能并非所在城市的固定区域，考虑是否通过地点查询经纬度
          // map.setZoomAndCenter(15, [cityInfo.lng, cityInfo.lat])
          // var currentCenter = map.getCenter();
        });
      });

    },
    // 显示城市选择组件
    showMobiCityPicker(){
      if (this.cityPicker !== null) {
        this.$emit('showmobicity') //开启城市选择 （PC可手动兼容，将其他组件隐藏）
        this.cityPicker.show();
      } else {

        this.initMobiCityPicker()
      }
    },
    // 关闭城市选择组件
    clearMobiCityPicker(){
      this.$emit('clearmobicity') //关闭城市选择
      this.cityPicker.hide();
    },
    // 外部调用查询方法 判断是否分页
    whetherToPageSearch () {
      if ( (this.searchText.trim() === this.lastSearchText.trim()) && this.searchText.trim() ) {
        this.pageCount = 0
        this.pagenumber = 1
        this.syncSearch()
      }else {
        this.syncSearch()
      }
    },
    // 关闭搜索列表(点击关闭图标)
    closeSearchList () {
      this.searchText = ''
      this.$emit("closearchlist")
    }
  },
  ready () {
    this.initAmapSearch() //初始化搜索
    this.initMobiCityPicker() //初始化城市选择
    this.$nextTick(()=>{
      if (this.thiscity == null || this.thiscity==='' || this.thiscity == undefined) {
        this.thiscity = '请选择城市'
      }
    })
  },
  watch: {
    // 当值该表时执行查询
    'searchText':function (newValue,oldValue){
      //本次和上次不同，内容改变 则将总数和当前页恢复默认
      if ( (newValue.trim() !== oldValue.trim()) && newValue.trim() ) {
        this.pageCount = 0
        this.pagenumber = 1
        this.syncSearch()
        this.$emit("searchchange",this.searchText)
      }else {
        this.syncSearch()
        this.$emit("searchchange",this.searchText)
      }
      // 最后将上次的搜索框内容重新赋值
      this.lastSearchText = oldValue
    },
    "thiscity":function () {
      if (this.thiscity == null || this.thiscity==='' || this.thiscity == undefined) {
        this.thiscity = '请选择城市'
      }
    }

  },
}
</script>
<style scoped lang="less">
.maptop {
  padding-top: 5px;
  padding-bottom: 10px;
  .citybtn {
    height: 100%;
    width: 100%;
    background: #fff;
    text-align: left;
    border: none;
    float: left;
    display: flex;
    align-items:center;
    .city {
      width: 65%;
      height: auto;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      display: inline-block;
    }
    .citygly {
      height: auto;
      display: inline-block;
    }
  }
  .d2 {
    display: flex;
    align-items:center;
    height: 100%;
    width: auto;
    background: #f4f4f4;
    border-radius: 20px;
    padding: 0 10px;
    .search {
      //display: inline-block;
      float: left;
      display: flex;
      align-items:center;
      svg {
        width: 16px;
        height: 16px;
      }
    }
    input {
      width: 90%;
      padding: 0 10px;
      background: #f4f4f4;
      border: none;
      outline: none;
    }
    .remove {
      display: flex;
      align-items:center;
      float: right;
      svg {
        width: 14px;
        height: 14px;
      }
    }
  }
  .d1 {
    display: flex;
    align-items:center;
  }
  .cancel {
    width: 20%;
    display: flex;
    align-items:center;
    div {
      text-align: right;
      line-height: 200%;
      width: 100%;
    }
  }
}

</style>

