<!-- /*
* @Author: 王尚
* @Date: 2019-07-18
*/ -->
<template>
	<scroll-view :scroll-into-view="scrollIntoId" scroll-y class="container" @scroll="scroll">

			<view class="search-container flex align-center justify-between">
        <view class="search-wrapper">
        	<image :src='STATIC_URL+"53.png"' mode=""></image>
        	<input type="text" placeholder="搜索城市名" placeholder-class="text-bf" value="" v-model="text" @confirm="handelSearch" />
        </view>
        <view class="sure" @click="handelSearch">搜索</view>
      </view>
		<view class="ocationlCity flex align-center justify-between" ref="location" >
			<view class="flex align-center">
        <text>当前城市:</text>
        <text @tap="handleChooseCurrentCity">{{cityName ? cityName : ''}}</text>
      </view>
      <!-- <view class="afresh-location" @tap="_location">重新定位</view> -->
		</view>
    <view class="search-list" v-if="searchData.length">
      <view class="search-item" v-for="(searchItem, index) in searchData" :key="index" @tap="chooseCity(searchItem)">
        <text class="name">{{searchItem.name}}</text>
      </view>
    </view>
		<!-- <view class="nearest" ref="nearest" v-if="!searchData.length && recentlylist.length > 0">
			<view class="title">定位/最近访问</view>
			<view class="list">
				<view class="item" v-for="(Re_item, index) in recentlylist" :key="index" @click="chooseCity(Re_item)">{{Re_item.name}}</view>
			</view>
		</view> -->
		<view class="hot" id="hot" v-if="!searchData.length">
			<view class="title">热门城市</view>
			<view class="list">
				<view class="item" v-for="(item, index) in hotCities" :key="index" @tap="chooseCity(item)">{{item.name}}</view>
			</view>
		</view>
		<view class="city-list" v-if="!searchData.length">
      <view class="city-group" v-for="(item, key) of cities" :key="key" :id="key">
        <view class="group-title">{{key}}</view>
        <view class="list-group">
          <view class="list-group-item" v-for="(innerItem, index) in item" :key="index" @tap="chooseCity(innerItem)">
            <text class="name">{{innerItem.name}}</text>
          </view>
        </view>
      </view>
    </view>
		<view class="list-shortcut" v-if="!searchData.length" @touchstart="onShortcutTouchStart" @touchmove.stop.prevent="onShortcutTouchMove">
      <view>
        <view v-for="(item, index) in letters" :key="index" :data-index="index" :data-item="item" class="item" :class="{'current': currentIndex == index}">{{item}}</view>
      </view>
    </view>
	</scroll-view>
</template>

<script>
  import amap from '@/common/amap-wx.js'
	const citys = require('@/common/city.json')
  // import Api from '@/common/api/url.js'
	const ANCHOR_HEIGHT = 18
	const TITLE_HEIGHT = 40
	export default {
		data() {
			return {
        amapPlugin: null, //new地图
        key: '886bfe2d6c32bd8eac97c2e6d821ed0b',
        // key: '4d70fc05da7c6ed10e71eb274029ee31',
				cities: [],             //城市数据源
				hotCities: [],          //热门城市
				scrollIntoId: '',       //滚动的某个ID
				currentIndex: 0,        //当前是第几个模块
				nearCity: [1],          //最近访问城市列表
        cityName: '',        //当前定位城市
        text: ''                ,//搜索框输入内容
        addr: '',               // 位置
        recentlylist: [],       //最近访问
        searchData: [],
        lat: '',
        lng: ''
			};
		},
		onLoad(options) {
      this.cityName = options.city || '';
			this.touch = {}
			this._normalizeCitys()
      this.amapPlugin = new amap.AMapWX({
        key: this.key
      });
      // this.cityName = uni.getStorageSync('DUCHE_RECEPTION_CITY') || '暂无定位'
      // this.recentlylist = uni.getStorageSync('DUCHE_RECEPTION_RECENTLY') || []
		},
		onReady() {
			this._calculateHeight()
		},
		computed: {
      /** 计算右侧字母列表 */
			letters () {
				const letters = ['热']
				for (let item in this.cities) {
					letters.push(item)
				}
				return letters
			}
		},
    /**
     * 当 searchInput 输入时触发
     */
    onNavigationBarSearchInputChanged(e) {
    	this.text = e.text;
      console.log(e)
      if (!this.text) {
        this.searchData = []
      }
    },
    /**
     * 点击软键盘搜索按键触发
     */
    onNavigationBarSearchInputConfirmed(e) {
    	this.search(e.text);
    },
    /**
     *  点击导航栏 buttons 时触发
     */
    onNavigationBarButtonTap() {
    	let text = this.text;
    	this.search(text);
    },
		methods: {
      _location() {
        uni.getLocation({
            type: 'gcj02',
            success: (res) => {
              // this.lat = res.latitude;
              // this.lng = res.longitude;
              this.amapPlugin.getRegeo({
              	location: `${res.longitude},${res.latitude} `,
              	success: (addr) => {
                    console.log(addr[0])
              			this.cityName = addr[0].regeocodeData.addressComponent.city;
              			this.lat = res.latitude;
              			this.lng = res.longitude;
              	},
              	fail: (err) => {

              	}
              });
            }
        });
      },
      handelSearch() {
        let text = this.text;
        this.search(text);
      },
      /*** 选择城市 */
			chooseCity(item) {
        console.log('~~~~~~~', item)
				let that = this
        //缓存最近搜索城市
        // let len = this.recentlylist.length
        // let isRepeat = false
        // this.recentlylist.map((city) => {
        //   if (city.name == item.name) {
        //     isRepeat = true
        //   }
        // })
        // if (len >= 6 && !isRepeat) {
        //   this.recentlylist.shift()
        //   this.recentlylist.push(item)
        // }
        // if (len < 6 && !isRepeat) {
        //   this.recentlylist.push(item)
        // }

        // console.log(item)
        // uni.setStorageSync('DUCHE_RECEPTION_RECENTLY', this.recentlylist);
        uni.$emit('CHOOSE_CITY', item)
        uni.navigateBack({
          delta: 1
        });
			},

      handleChooseCurrentCity() {
        if (!this.cityName) return false;
        uni.$emit('CHOOSE_CITY', {name: this.cityName, lat: this.lat, lng: this.lng});
        uni.navigateBack({
          delta: 1
        });
      },

      /***  初始化城市列表数据 */
			_normalizeCitys () {
        // this.$api.post(global.apiUrls.getCityList).then(res => {
        //   if (res.data.code == 1) {
        //     this.cities = res.data.data.city_list;
        //     this.hotCities = res.data.data.hot;
        //     setTimeout(() => {
        //       this._calculateHeight()
        //     }, 300)
        //   }
        // })
				if (citys.ret && citys.data) {
					const data = citys.data
					this.cities = data.cities
					this.hotCities = data.hotCities
				}
			},
      /***  城市列表滚动时边界处理 */
			scroll(e) {
				this.scrollY = -e.detail.scrollTop
				const listHeight = this.listHeight
				// 当滚动到顶部， newY大于0
				if (this.scrollY > 0) {
					this.currentIndex = 0
				}
				// 滚动到中间部分
				for (let i = 0; i < listHeight.length - 1; i++) {
					let height1 = listHeight[i]
					let height2 = listHeight[i + 1]
					if (-this.scrollY < height1 && -this.scrollY >=0) {
						this.currentIndex = i
						// this.diff = height2 + this.scrollY
						return
					}
					if (-this.scrollY >= height1 && -this.scrollY < height2) {
						this.currentIndex = i
						// this.diff = height2 + this.scrollY
						return
					}
				}

				// 滚动到底部，且-newY大于最后一个元素的上限
				this.currentIndex = listHeight.length - 2
			},
      /***  计算每一个城市模块的高度 */
			_calculateHeight() {
				this.listHeight = []
				let height = 0
				let view = uni.createSelectorQuery().select(".hot");
				view.boundingClientRect(data => {
					this.listHeight.push(data.top)
				}).exec();
				for(var k in this.cities){
					let view = uni.createSelectorQuery().select("#" + k);
					view.boundingClientRect(data => {
						this.listHeight.push(data.top)
					}).exec();
				}
			},
      /***  点击右侧字母时左侧城市列表的联动 */
			onShortcutTouchStart(e) {
				let anchorIndex = parseInt(e.target.dataset.index)
				let anchorItem
				if (anchorIndex === 0) {
					anchorItem = 'hot'
				} else{
					anchorItem = e.target.dataset.item
				}
				let firstTouch = e.touches[0]
				this.touch.y1 = firstTouch.pageY
				this.touch.anchorIndex = anchorIndex
				this.scrollIntoId = anchorItem
			},
      /**
       *  手指在右侧字母列表上滑动时处理函数
       */
			onShortcutTouchMove(e) {
				let firstTouch = e.touches[0]
				this.touch.y2 = firstTouch.pageY
				let delta = (this.touch.y2 - this.touch.y1) / ANCHOR_HEIGHT | 0
				let anchorIndex = parseInt(this.touch.anchorIndex) + delta
				let anchorItem
				if (anchorIndex === 0) {
					anchorItem = 'hot'
				} else{
					anchorItem = this.letters[anchorIndex]
				}
				this.scrollIntoId = anchorItem
			},
      /*** 搜索功能的实现 */
      search(text) {
      	if(text == ''){
      	  uni.showToast({
      	      icon:"none",
      	      title:"请输入搜索内容"
      	  })
      	  return;
      	}else{
      	  let cities = this.cities
      	  let searchData = []
      	  for(let k in cities) {
      	    cities[k].forEach((item) => {
      	      if (item.name.indexOf(text) > -1) {
      	        searchData.push({
      	          id: item.id,
      	          spell: item.spell,
      	          name: item.name
      	        })
      	      }
      	    })
      	  }
      	  this.searchData = searchData
      	}
      }
		}
	}
</script>

<style lang="scss">
  page {
  		position: relative;
  		width: 100%;
  		height: 100%;
  		.container {
  			width: 100%;
  			height: 100%;
        background: #fff;
  			overflow: hidden;
        .search-container {
          padding: 24rpx 32rpx;
          .sure {
            font-size: 32rpx;
            color: #FF9D00;
          }
        }
  			.search-wrapper {
          // margin: 24rpx 0;
  				display: flex;
  				flex-direction: row;
  				align-items: center;
  				// margin-left: 24upx;
  				width: 590upx;
  				height: 64upx;
  				background: #F8F9FC;
  				border-radius: 32upx;
  				image {
  					margin: 0 15upx 0 28upx;
  					width: 26upx;
  					height: 26upx;
  				}
  				input {
  					flex: 1;
  					font-size: 28upx;
  					color: #333;
  				}
  			}
  			.ocationlCity{
  				display: flex;
  				flex-direction: row;
  				align-items: center;
  				padding: 0 32upx;
          box-sizing: border-box;
  				width: 100%;
  				height: 80upx;
  				font-size: 24upx;
  				color: #333;
          background-color: #F6F7F9;
  				text {
  					&:last-child {
              display: block;
              padding: 0 32rpx;
  						margin-left: 24upx;
              height: 60upx;
              line-height: 60upx;
              text-align: center;
              // background: #F8F9FC;
              border-radius: 4upx;
              font-size: 24upx;
              color: #4B5269;
  					}
  				}
          .afresh-location {
            margin-right: 12rpx;
            color: #FF9D00;
            font-size: 24rpx;
          }
  			}
  			.nearest, .hot {
  				padding: 0 32upx 12upx;
  				box-sizing: border-box;
  				width: 100%;
          background: #fff;
  				// border-bottom: 1px solid #eee;
  				.title {
  					line-height: 86upx;
  					font-size: 26upx;
  					color: #666;
  				}
  				.list {
  					display: flex;
  					flex-direction: row;
  					flex-wrap: wrap;
  					.item {
  						margin-bottom: 20upx;
  						margin-right: 20upx;
              padding: 0 20upx;
              box-sizing: border-box;
  						width: 150upx;
  						height: 60upx;
  						line-height: 60upx;
  						text-align: center;
  						background: #F8F9FC;
  						border-radius: 4upx;
  						font-size: 24upx;
  						color: #4B5269;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
  					}
  				}
  			}
  			.city-list {
  				.city-group {
  					.group-title {
              padding: 0 32upx;
              box-sizing: border-box;
  						line-height: 70upx;
  						font-size: 26upx;
  						color: #666;
              background: #fff;
  					}
  					.list-group {
              margin: 0 auto;
              width: 686upx;
  						.list-group-item {
                position: relative;
  							line-height: 74upx;
  							color: #4B5269;
  							font-size: 30rpx;
                &:after {
                  @include bottom-line(#eee);
                }
  							// border-bottom: 1px solid #eee;
  						}
  					}
  				}
  			}
        .search-list {
          margin: 0 auto;
          width: 686upx;
          .search-item {
            position: relative;
            line-height: 72upx;
            color: #4B5269;
            font-size: 30upx;
            &:after {
              @include bottom-line(#eee)
            }
            &:last-child {
              border-bottom: none;
            }
          }
        }
  			.list-shortcut {
  				position: fixed;
  				z-index: 30;
  				right: 0;
  				top: 50%;
  				transform: translateY(-50%);
  				width: 20px;
  				padding: 20px 0;
  				border-radius: 10px;
  				text-align: center;
  				// background: #fff;;
  				font-family: Helvetica;
  				.item {
  					padding: 3px;
  					line-height: 1;
  					color: #333;
  					font-size: 28upx;
  					&.current {
  						color: #FF9D00;
  					}
  				}
  			}
  		}
  	}

</style>
