<template>
  <div class="map">
    <!-- <div class="build-btn locate" @click="getLocale">
      <img src="https://cdn.cunwuyun.cn/dvcp/h5/Location2.png" alt=""/>
      当前<br>位置
    </div> -->
    <div class="address-search">
      <div class="address-search__wrapper">
        <image src="./components/img/search.png" />
        <input placeholder-style="color: #98A6B6" placeholder="搜索地点" v-model="address" @input="onChange">
      </div>
    </div>
    <scroll-view scroll-y scroll-into-view="address-item1" v-if="addressList.length">
      <div class="address-item" :id="'address-item' + index" v-for="(item, index) in addressList" :key="index" @click="chooseAddress(index)">
        <div class="left">
          <h2>{{ item.title }}</h2>
          <p>{{ item.address }}</p>
        </div>
        <!-- <div class="right" :class="[currIndex === index ? 'active' : '']"></div> -->
      </div>
    </scroll-view>
    <div class="map-content">
      <AiTMap :map.sync="map" :lib.sync="lib" :ops="ops" :libraries="['service', 'tools']"/>
    </div>
    <div class="footer">
      <div class="btn" @click="confirm">确认定位</div>
    </div>
  </div>
</template>

<script>
import {mapState, mapActions} from 'vuex'

export default {
  data() {
    return {
      ops: {},
      lib: null,
      map: null,
      markerLayer: '',
      isFlag: false,
      latLng: {lat: '', lng: ''},
      address: '',
      addressList: []
    }
  },
  computed: {...mapState(['user'])},
  mounted() {
    this.initMap()
  },
  onShow() {
    document.title = "选择上报位置"
  },
  methods: {
    ...mapActions(['injectJWeixin']),
    initMap(retryTimes = 0) {  //初始化地图
      this.$nextTick(() => {
        let {map} = this
        if (map) {
          map.setZoom(15)
          map.on("click", (evt) => {
            this.handleMapClick(evt)
          });
        } else {
          if (retryTimes < 10)
            setTimeout(() => {
              this.initMap(++retryTimes)
            }, 500)
          else console.error("地图渲染失败")
        }
      })
    },
    onChange () {
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.timeout = setTimeout(() => {
        this.currIndex = -1
        new this.lib.service.Suggestion({
          pageSize: 20
        }).getSuggestions({
          keyword: this.address
        }).then(res => {
          this.addressList = []
          if (res.data.length) {
            this.addressList = res.data
          }
        })
      }, 500)
    },
    getAddress () {
      new this.lib.service.Search({
        pageSize: 20
      }).explore({
        center: this.latLng,
        radius: 2000,
        orderBy: '_distance'
      }).then(res => {
        this.addressList = []
        if (res.data.length) {
          this.addressList = res.data
        }
      })
    },
    chooseAddress (index) {
      this.address = this.addressList[index].address
      this.latLng = {lat: this.addressList[index].location.lat, lng: this.addressList[index].location.lng}
      this.addMarker(this.addressList[index].location)
    },
    addMarker (position) {
      if (this.marker) {
        this.marker.setMap(null)
        this.marker = null
      }
      this.marker = new this.lib.MultiMarker({
        id: 'marker-layer',
        map: this.map,
        styles: {
          marker: new this.lib.MarkerStyle({
            width: 30,
            height: 45,
            anchor: { x: 10, y: 30 }
          }),
        },
        geometries: [{
          id: 'marker',
          styleId: 'marker',
          position: position,
          properties: {
            title: 'marker'
          }
        }]
      })
      this.easeTo(position)
    },

    easeTo (position) {
      this.map.easeTo({
        center: position,
        zoom: 17
      },
      { duration: 500 })
    },
    handleMapClick(evt) {
      console.log(evt)
      let {lib: TMap, map} = this
      if (this.markerLayer) {
        this.markerLayer.setMap(null);
      }
      this.markerLayer = new TMap.MultiMarker({id: 'marker-layer', map});
      this.markerLayer.add({
        position: evt.latLng
      });
      this.latLng = evt.latLng
      var geocoder = new TMap.service.Geocoder();
      geocoder.getAddress({ location: this.latLng }).then((result) => {
        this.address = result.result.address;
      });
    },
    confirm() {
      if (!this.latLng.lat) {
        return this.$u.toast(`未获取到定位信息，无法定位`)
      }

      uni.$emit('chooseLat', {
        lat: this.latLng.lat,
        lng: this.latLng.lng, 
        address: this.address
      })
      uni.navigateBack({
        delta: 1
      })
    },
  }
}
</script>

<style lang="scss" scoped>
uni-page-body {
  height: 100%;
}

.map {
  height: 100vh;

  .build-btn {
    width: 80px;
    height: 160px;
    background: #FFF;
    box-shadow: 0 4px 8px 0 rgba(138, 138, 138, 0.5);
    border-radius: 8px;
    position: fixed;
    bottom: 136px;
    right: 24px;
    z-index: 99999;
    padding: 16px 16px 0;
    box-sizing: border-box;
    font-size: 24px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #666;
    line-height: 30px;

    &.locate {
      transform: translateY(calc(-100% - 20px));
    }

    img {
      width: 48px;
      height: 48px;
      margin-bottom: 8px;
    }
  }

  .map-content {
    width: 100%;
    height: 100%;
  }

  .footer {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 99999;
    display: flex;
    font-size: 32px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    height: 112px;
    line-height: 112px;
    text-align: center;

    .click {
      flex: 1;
      color: #333;
      background-color: #fff;
    }

    .btn {
      flex: 2;
      background: #1365DD;
      color: #FFF;
    }
  }
  .address-search {
    display: flex;
    align-items: center;
    height: 100px;
    padding: 0 32px;

    .address-search__wrapper {
      display: flex;
      align-items: center;
      width: 100%;
      height: 72px;
      padding: 0 32px;
      background: #F6F7F9;
      border-radius: 36px;

      image {
        width: 48px;
        height: 48px;
      }

      input {
        flex: 1;
        font-size: 26px;
        color: #333;
      }
    }
  }
  scroll-view {
    height: 400px;
    padding: 0 32px;

    .address-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32px 0;
      border-bottom: 1px solid #EEEEEE;

      &:last-child {
        border: none;
      }

      .left {
        flex: 1;
        margin-right: 20px;
      }

      .right {
        flex-shrink: 1;
        width: 32px;
        height: 32px;
        border-radius: 50%;
        border: 4px solid #CCCCCC;
        transition: all ease 0.3s;

        &.active {
          border: 10px solid #1365DD;
        }
      }

      h2 {
        margin-bottom: 20px;
        color: #222222;
        font-weight: 600;
        font-size: 34px;
      }

      p {
        line-height: 1.2;
        color: #999999;
        font-size: 28px;
      }
    }
  }
}
</style>
