<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar title="选择地址" pervent @back="handleCancel">
        <!-- #ifndef MP-WEIXIN -->
        <!-- <button
					v-if="!showSearch"
					class="button white-btn"
					@click="handleConfirm">
					确定
				</button> -->
        <!-- #endif -->
      </wk-nav-bar>
			
      <view v-if="!showSearch" class="container">
        <view class="search-box">
          <view class="search" @click="handleToggleSearch">
            <image :src="$static('images/icon/search.png')" alt="" class="search-icon" />
            <text>搜索地点</text>
          </view>
        </view>

        <map
          id="chooseMap"
          :style="{
            width: mapStyle.width,
            flex: mapStyle.flex
          }"
          :longitude="centerPoint.longitude"
          :latitude="centerPoint.latitude"
          :markers="markers"
          @tap="handleMapClick" />

        <view class="poi-container">
          <view
            v-for="(poi, index) in poiList"
            :key="poi.id"
            class="poi-item"
            @click="handleChoosePoi(index, $event)">
            <view class="left">
              <view class="poi-item-name">
                {{ poi.name }}
              </view>
              <view class="poi-item-address">
                {{ poi.address || '' }}
              </view>
            </view>
            <view class="right">
              <text v-if="activeIndex === index" class="wk wk-check icon" />
            </view>
          </view>
        </view>
      </view>
			
      <view v-else class="container">
        <wk-search-box @search="handleSearch" />
				
        <view class="list-view">
          <wk-scroll-view
            :status="listStatus"
            :refresh="false"
            class="list-scroll"
            @loadmore="searchPois()">
            <template v-if="listData.length > 0">
              <view
                v-for="(poi, index) in listData"
                :key="poi.id"
                class="cell"
                @click="handleChooseSearchPoi(index, $event)">
                <view class="cell-title">
                  {{ poi.name }}
                </view>
                <view class="cell-desc">
                  {{ poi.address }}
                </view>
              </view>
            </template>
          </wk-scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    getLocation,
    searchPois,
    searchAroundPois,
    getNearbyPois
  } from '@/utils/map.js'

  /**
   * 模仿uni.chooseLocation
   */
  export default {
    name: 'ChooseLocation',
    data() {
      return {
        mapStyle: {
          width: 0,
          flex: 1
        },
        centerPoint: {},

        markers: [],
        poiList: [],
        activeIndex: null,
				
        showSearch: false,
        listStatus: 'more',
        listData: [],
        page: 0,
        keyword: ''
      }
    },
    onLoad(options = {}) {
      this.mapStyle = {
        width: uni.upx2px(750) + 'px',
        flex: 1
      }
      if (this.$isEmpty(options)) {
        this.getLocation()
      } else {
        this.centerPoint = options
        this.searchAroundPois(this.centerPoint)
      }
    },
    methods: {
      /**
       * 定位
       */
      getLocation() {
        getLocation().then(data => {
          console.log('定位结果：', data)
          const city = data.hasOwnProperty('address_component') ? data.address_component.city : data.address.city
          this.centerPoint = {
						...data,
						city
          }
          this.searchAroundPois(data)
        }).catch(() => {
          this.$toast('定位失败')
        })
				
        // this.centerPoint = {
        // 	city: '郑州',
        //   latitude: 34.762279,
        // 	longitude: 113.77765
        // }
        // this.searchAroundPois(this.centerPoint)
      },

      /**
       * 获取附近500米的POI点
       */
      searchAroundPois(data) {
        // >> 高德地图 <<
        // searchAroundPois({
        // 	location: `${data.longitude},${data.latitude}`,
        // 	radius: 500
        // }).then(data => {
        // 	console.log('位置信息: ', data)
        // 	this.poiList = data.pois.map(o => {
        // 		return {
        // 			...o,
        // 			longitude: o.location.split(',')[0],
        // 			latitude: o.location.split(',')[1]
        // 		}
        // 	})
        // 	if (this.poiList.length > 0) {
        // 		this.handleChoosePoi(0)
        // 	} else {
        // 		this.activeIndex = -1
        // 		this.markers = []
        // 	}
        // }).catch(() => {
        // 	this.$toast('获取位置信息失败')
        // })
				
        // >>  腾讯地图 <<
        console.log('getNearbyPois---', `${data.latitude},${data.longitude}`)
        getNearbyPois({
          location: `${data.latitude},${data.longitude}`,
          get_poi: 1,
          poi_options: 'radius=500'
        }).then(res => {
          this.poiList = res.result.pois.map(o => {
            return {
							...o,
							name: o.title,
							longitude: o.location.lng,
							latitude: o.location.lat,
            }
          })
          if (this.poiList.length > 0) {
            this.handleChoosePoi(0)
          } else {
            this.activeIndex = -1
            this.markers = []
          }
        }).catch(() => {
          this.$toast('获取位置信息失败')
        })
      },
			
      /**
       * 根据关键字搜索POI
       */
      searchPois() {
        this.page++
        this.listStatus = 'loading'
				
        // >> 高德地图 <<
        // searchPois({
        // 	page: this.page,
        // 	keywords: this.keyword
        // }).then(data => {
        // 	console.log('搜索结果: ', data)
        // 	if (this.page === 1) {
        // 		this.listData = []
        // 	}
        // 	data.pois = data.pois.map(o => {
        // 		return {
        // 			...o,
        // 			longitude: o.location.split(',')[0],
        // 			latitude: o.location.split(',')[1]
        // 		}
        // 	})
        // 	this.listData = this.listData.concat(data.pois)
        // 	this.listStatus = data.count == this.listData.length ? 'noMore' : 'more'
        // }).catch(() => {
        // 	this.$toast('服务异常，请稍后重试')
        // 	this.listStatus = 'more'
        // })
				
        // >>  腾讯地图 <<
        searchPois({
          keyword: this.keyword,
          region: this.centerPoint.city || '',
          region_fix: 0,
          page_index: this.page,
          page_size: 15
        }).then(res => {
          console.log('search res: ', res)
          if (this.page === 1) {
            this.listData = []
          }
          res.data = res.data.map(o => {
            return {
							...o,
							ad_info: o,
							name: o.title,
							longitude: o.location.lng,
							latitude: o.location.lat
            }
          })
          this.listData = this.listData.concat(res.data)
          this.listStatus = res.data.length === 0 ? 'noMore' : 'more'
        }).catch(() => {
          this.$toast('服务异常，请稍后重试')
          this.listStatus = 'more'
        })
      },
			
      handleMapClick(evt) {
        console.log('tap', evt)
      },
			
      /**
       * 选择POI点
       * @param {Object} index
       */
      handleChoosePoi(index, evt = null) {
        this.activeIndex = index
        const point = this.poiList[index]
        this.markers = [{
					...point,
					width: 30,
					height: 30,
					iconPath: this.$static('images/map/location.png')
        }]
        this.centerPoint = {
          latitude: point.latitude,
          longitude: point.longitude
        }
        if (evt) {
          this.handleConfirm()
        }
      },
			
      /**
       * 切换搜索状态
       */
      handleToggleSearch() {
        this.showSearch = !this.showSearch
        this.page = 0
        this.listData = []
        this.listStatus = 'more'
      },
      /**
       * 去搜索
       */
      handleSearch(keyword = '') {
        this.page = 0
        this.listData = []
        this.listStatus = 'more'
        this.keyword = keyword
        if (keyword) {
          this.searchPois()
        }
      },
      /**
       * 选择搜索的POI点
       */
      handleChooseSearchPoi(index, evt = null) {
        this.poiList = [...this.listData]
        this.handleToggleSearch()
        this.handleChoosePoi(index, evt)
      },
			
      /**
       * 取消
       */
      handleCancel() {
        if (this.showSearch) {
          this.handleToggleSearch()
        } else {
          uni.$off('choose-location')
          this.$Router.navigateBack()
        }
      },
			
      /**
       * 确定
       */
      handleConfirm() {
        let data = null
        if (this.activeIndex >= 0 && this.poiList[this.activeIndex]) {
          data = this.poiList[this.activeIndex]
        }
        uni.$emit('choose-location', data)
        this.$Router.navigateBack()
      }
    }
  }
</script>

<style scoped lang="scss">
	.container {
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;

		.search-box {
			width: 100%;
			height: 105rpx;
			background-color: white;
			@include center;

			.search {
				width: 92%;
				height: 70rpx;
				font-size: 26rpx;
				color: $light;
				background-color: $main-bg;
				border-radius: 8rpx;
				@include center;

				.search-icon {
					width: 28rpx;
					height: 28rpx;
					margin-right: 20rpx;
				}
			}
		}

		.poi-container {
			width: 100%;
			max-height: 450rpx;
			overflow: auto;
			background-color: white;

			.poi-item {
				padding: 15rpx 32rpx;
				border-bottom: 1rpx solid $border-color;
				@include left;

				.left {
					flex: 1;
					overflow: hidden;

					.poi-item-name {
						font-size: 30rpx;
						@include ellipsis;
					}

					.poi-item-address {
						font-size: 24rpx;
						color: $light;
						@include ellipsis;
					}
				}

				.right {
					width: 50rpx;
					margin-left: 20rpx;
					@include center;

					.icon {
						font-size: 36rpx;
						color: $theme-color;
					}
				}
			}

			.poi-item::last-child {
				border-bottom: 0 none;
			}
		}
		
		.list-view {
			flex: 1;
			background-color: white;
			overflow: hidden;
			padding: 0 34rpx;
			
			.list-scroll {
				width: 100%;
				height: 100%;
				overflow: hidden;
				.cell {
					border-bottom: 1rpx solid $border-color;
					padding: 20rpx 0;
					.cell-title {
						font-size: 30rpx;
					}
					.cell-desc {
						font-size: 24rpx;
						color: $gray;
					}
				}
			}
		}
	}
</style>
