<template>
	<view>
		<!-- pages/jsCase/citySel/index.wxml -->
		<!-- <sjs module="utils" src="../../../utils/formatFuc.sjs" /> -->
		<view :class="'head ' + (search && 'r_head')">
			<!-- 搜索框 -->
			<view class="flex-row search-box">
				<view class="city-block" @tap="switchCity">
					<view>{{ current_city }}</view>
					<image :class="'arrow-img ' + (cityShow ? 'arrow-up' : '')" mode="aspectFit"
						src="https://mall.zhaijieshi.cc/file/jzmall-dy/arrow-down.png"></image>
				</view>
				<view class="head_input">
					<image src="https://mall.zhaijieshi.cc/file/wx-dy/icon-search.png" class="search_icon"></image>
					<input type="text" placeholder="搜索" placeholder-class="place_holder" @input="getValue"
						:value="search" @focus="mapFocus" class="input-view" confirm-type="search"
						@confirm="confSearch" />
				</view>
				<view class="sha_icon" @tap.stop.prevent="clear_input" v-if="!mapShow">取消</view>
			</view>
			<view class="flex-row head_curr" v-if="cityShow">
				<image src="https://mall.zhaijieshi.cc/file/wx-dy/address-map.png" class="h_c_icon" />
				<view>当前定位城市: {{ current_city }}</view>
			</view>
		</view>
		<scroll-view v-if="cityShow" :scroll-y="true" class="sy_container" :scroll-into-view="scrollViewId">
			<view class="hot_city">
				<view class="title">热门城市</view>
				<view class="flex-row flex-wrap box">
					<block v-for="(item, index) in hot_city" :key="index">
						<view class="name" hover-class="sel_city" hover-stay-time="150" @tap="cityTap"
							:data-city="item.name">
							{{ item.name }}
						</view>
					</block>
				</view>
			</view>
			<view class="all_city">
				<view v-if="item.data.length > 0" v-for="(item, index) in city_list" :key="index">
					<view class="letter_name" :id="item.letter">{{ item.letter }}</view>

					<view class="city">
						<block v-for="(item0, index0) in item.data" :key="index0">
							<view class="name flex-row" hover-class="city_hover" hover-stay-time="150" @tap="cityTap"
								:data-city="item0.cityName">{{ item0.cityName }}</view>
						</block>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 侧边选择索引 -->
		<view v-if="cityShow">
			<view class="fixed_bar" :style="'height: ' + barHeight + 'px;'" @touchstart.stop.prevent="touchStart"
				@touchmove.stop.prevent="touchMove" @touchend.stop.prevent="touchEnd"
				@touchcancel.stop.prevent="touchCancel">
				<view :style="'height: ' + barHeight / 22 + 'px;'" v-for="(item, index) in city_list" :key="index">
					<view :class="'bar_item flex-column j_c ' + (curr == index && 'bar_item_active')"
						:style="'width: ' + (barHeight / 22) * 0.75 + 'px;height: ' + (barHeight / 22) * 0.75 + 'px;'">
						{{ item.letter }}
					</view>
				</view>
			</view>
			<view v-if="showLetter && city_list[curr].letter" class="fixed_letter">{{ city_list[curr].letter }}</view>
		</view>
		<view v-if="resultShow" class="result_list">
			<view v-if="result.length > 0">
				<block v-for="(item, index) in result" :key="index">
					<view class="r_item" hover-stay-time="150" hover-class="r_item_hover" @tap="resultTap"
						:data-location="item.location" :data-name="item.name">
						<view>{{ item.name }}</view>
						<view>{{ item.district + item.address }}</view>
					</view>
				</block>
			</view>
			<view v-else class="flex-column no_data">
				<image src="https://mall.zhaijieshi.cc/file/jzmall-dy/no-data.png" />
				<view>未搜到相关地址</view>
				<view>输入地址后请点击搜索</view>
			</view>
		</view>
		<!-- tt-if="{{mapShow}}" -->
		<map :enable-rotate="true" :min-scale="3" :max-scale="19" id="myMap" :enable-scroll="true"
			:enable-overlooking="true" :longitude="lng" @tap="mapTap" :show-location="true" :latitude="lat" :scale="15"
			@regionchange="regionChange" :enable-zoom="true" @updated="mapUpdated"></map>
		<view class="marker-name" v-if="mapShow && currentName && currentName.length > 0">{{ currentName }}</view>
		<image src="https://mall.zhaijieshi.cc/file/jzmall-dy/icon-marker.png" class="map-icon" v-if="mapShow"></image>

		<scroll-view class="poi-list" :scroll-y="true" v-if="mapShow">
			<view class="poi-item" @tap="poiTap" :data-poi="item" v-for="(item, index) in poiList" :key="index">
				<view class="poi-left">
					<view class="poi-name">{{ item.name }}</view>
					<view class="poi-address">{{ item.address }}</view>
				</view>

				<view class="poi-right">{{ formatDistance(item.distance) }}米</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	// pages/jsCase/citySel/index.js
	const {
		cityData
	} = require('./city.js');
	var map = require('../../../utils/map.js');
	var util = require('../../../utils/util.js');
	var api = require('../../../config/api.js');
	var app = getApp();
	export default {
		data() {
			return {
				index: 0,
				current_city: '当前定位',
				search: '',

				hot_city: [{
						name: '上海'
					},
					{
						name: '北京'
					},
					{
						name: '深圳'
					},
					{
						name: '南京'
					},
					{
						name: '苏州'
					},
					{
						name: '杭州'
					},
					{
						name: '青岛'
					},
					{
						name: '广州'
					},
					{
						name: '成都'
					},
					{
						name: '重庆'
					},
					{
						name: '昆山'
					},
					{
						name: '武汉'
					},
					{
						name: '西安'
					},
					{
						name: '长沙'
					}
				],

				city_list: [],
				barHeight: 0,
				curr: -1,
				scrollViewId: '',
				barTop: 0,
				showLetter: true,
				result: [],

				//搜索结果
				mapShow: true,

				resultShow: false,
				cityShow: false,

				currentMarker: [
					// {longitude: 116.40159,
					// latitude: 39.90511,
					// title: '当前位置',}
				],

				lng: '',
				lat: '',
				poiList: [],
				timer: '',
				loadTime: 0,
				isTouchMap: true,
				addressName: '',
				currentName: '',
				letter: ''
			};
		},
		onUnload: function() {
			// 页面关闭
			clearInterval(this.timer);
		},
		onLoad: function(options) {
			// this.getUserLocation();
			let timer = setInterval(() => {
				if (this.loadTime < 10) {
					this.setData({
						loadTime: this.loadTime + 1
					});
				} else {
					clearInterval(that.timer);
				}
			}, 1000);
			this.setData({
				timer: timer
			});
			this.setData({
				city_list: cityData
			});
			uni.getSystemInfo({
				success: (res) => {
					console.log(res);
					let winHeight = res.windowHeight;
					let barHeight = winHeight - (res.windowWidth / 750) * 300;
					this.setData({
						barHeight: barHeight,
						barTop: (res.windowWidth / 750) * 180
					});
				}
			});
			this.mapCtx = uni.createMapContext('myMap');
			let that = this;
			console.log(options);
			if (options.lng && options.lat) {
				that.setData({
					addressName: options.addressname,
					current_city: options.city,
					lng: options.lng,
					lat: options.lat
				});
				that.getPoiList();
			} else {
				// wx.authorize({
				//   scope: "scope.userLocation",
				//   success(res) {
				//     console.log("已允许授权定位权限: ", res);
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						let latitude = res.latitude;
						let longitude = res.longitude;
						app.globalData.lat = latitude; //
						app.globalData.lng = longitude; //把onload定位时候的经纬度存到全局
						app.globalData.currentLocationName = res.city;
						app.globalData.city = res.city;
						that.setData({
							addressName: app.globalData.currentLocationName,
							current_city: app.globalData.city,
							lng: app.globalData.lng,
							lat: app.globalData.lat
						});
						console.log('当前经纬度:' + longitude + ',' + latitude);
						that.getPoiList();
					},
					fail: function(res) {
						console.log('fail' + JSON.stringify(res));
					}
				});
			}

			//将地图中心移动到定位点
			// setTimeout(() => {
			//   that.mapCtx.moveToLocation({
			//     success: (res) => {
			//       console.log(res);
			//     },
			//     fail: (res) => {
			//     },
			//   });
			// }, 2000);
		},
		onReady() {},
		methods: {
			formatDistance(value) {
				var result = Number(value).toFixed(0);
				return result;
			},
			getUserLocation: function() {
				map.getUserLocation();
				console.log(app.globalData);
				let that = this;
				setTimeout(() => {
					that.setData({
						addressName: app.globalData.currentLocationName,
						current_city: app.globalData.city,
						lng: app.globalData.lng,
						lat: app.globalData.lat
					});
					this.getPoiList();
				}, 1000);
			},

			/**
			 * 获取value值
			 * @param {*} e
			 */
			getValue(e) {
				this.setData({
						search: e.detail.value
					},
					() => {
						// this.search(e.detail.value);
					}
				);
			},

			confSearch(e) {
				this.searchFun(this.search);
			},

			/**
			 * 搜索成功
			 */
			searchFun(e) {
				// let result = [], { city_list } = this.data;
				// city_list.forEach((item1) => {
				//   item1.data.forEach((item2) => {
				//     if (item2.keyword.indexOf(e.toLocaleUpperCase()) !== -1) {
				//       result.push({ name: item2.cityName })
				//     }
				//   })
				// })
				// this.setData({
				//   result,
				// })
				util.request(api.gdSearchUrl, {
					keywords: e,
					output: 'JSON',
					city: this.current_city,
					key: api.gdKey
				}).then((res) => {
					console.log(res);
					if (res.info == 'OK') {
						let list = res.tips;
						let result = list;
						if (list.length > 1) {
							//  result=list.splice(1);
							this.setData({
								result: result
							});
						} else {
							this.setData({
								result: []
							});
						}
					}
				});
			},

			/**
			 * 清空验证码
			 */
			clear_input() {
				this.setData({
					search: '',
					mapShow: true,
					cityShow: false,
					resultShow: false
				});
			},

			touch(e) {
				let pageY = e.touches[0].pageY;
				let index = Math.floor((pageY - this.barTop) / (this.barHeight / 22)); //向下取整
				let item = this.city_list[index];
				if (item) {
					this.setData({
						scrollViewId: item.letter,
						curr: index
					});
				}
			},

			touchStart(e) {
				this.setData({
					showLetter: true
				});
				this.touch(e);
			},

			touchMove(e) {
				this.touch(e);
			},

			touchEnd() {
				this.setData({
					showLetter: false
				});
			},

			touchCancel() {
				this.setData({
					showLetter: false
				});
			},

			mapFocus() {
				this.setData({
					mapShow: false,
					resultShow: true,
					cityShow: false,
					result: []
				});
			},

			switchCity() {
				if (this.cityShow) {
					this.setData({
						mapShow: true,
						cityShow: false,
						resultShow: false
					});
				} else {
					this.setData({
						mapShow: false,
						cityShow: true,
						resultShow: false,
						search: ''
					});
				}
			},

			msg(title, duration = 1500) {
				uni.showToast({
					title,
					duration,
					icon: 'none'
				});
			},

			regionChange(e) {
				console.log('isTouchMap', this.isTouchMap);
				if (this.isTouchMap == false) {
					return;
				}
				console.log(e);
				// #ifdef MP-TOUTIAO
				console.log('region变化' + this.index + ':' + e.detail.type, e);
				const {
					centerLocation
				} = e.detail;
				let latitude = Number(centerLocation.latitude).toFixed(4);
				let longitude = Number(centerLocation.longitude).toFixed(4);
				console.log('当前中心点经纬度', latitude, longitude);
				//  this.msg(this.data.index+'');
				// this.msg(`region: latitude: ${ latitude }, longitude: ${ longitude }`);
				//     经度范围：73°33′E至135°05′E 东经
				// 纬度范围：3°51′N至53°33′N 北纬
				if (this.loadTime > 3 && e.detail.type == 'end' && longitude > 72 && longitude < 136 && latitude > 3 &&
					latitude < 54) {
					if (latitude == this.lat) {
						return;
					}
					this.setData({
						lng: longitude,
						lat: latitude,
						index: this.index + 1
					});
					this.getPoiList();


				}
				// #endif
				// #ifdef MP-ALIPAY

				let latitude = Number(e.latitude).toFixed(4);
				let longitude = Number(e.longitude).toFixed(4);
				console.log('当前中心点经纬度', latitude, longitude);
				//  this.msg(this.data.index+'');
				// this.msg(`region: latitude: ${ latitude }, longitude: ${ longitude }`);
				//     经度范围：73°33′E至135°05′E 东经
				// 纬度范围：3°51′N至53°33′N 北纬
				if (this.loadTime > 3 && e.type == 'end' && longitude > 72 && longitude < 136 && latitude > 3 && latitude <
					54) {
					if (latitude == this.lat) {
						return;
					}
					this.setData({
						lng: longitude,
						lat: latitude,
						index: this.index + 1
					});
					this.getPoiList();


				}
				// #endif



			},

			mapTap(e) {
				console.log(e.detail);
			},

			getPoiList() {
				util.request(api.gdUrl, {
					// location:'116.40159,39.90511',
					location: this.lng + ',' + this.lat,
					extensions: 'all',
					// poitype:'',
					key: api.gdKey,
					radius: 3000
				}).then((res) => {
					console.log('poi', res);
					if (res.info == 'OK') {
						let list = res.regeocode.pois;
						var t = '';
						var length = list.length;
						for (var i = 0; i < length; i++) {
							for (var j = 0; j < length - i - 1; j++) {
								if (Number(list[j].distance) > Number(list[j + 1].distance)) {
									t = list[j];
									list[j] = list[j + 1];
									list[j + 1] = t;
								}
							}
						}
						this.setData({
							currentName: list.length > 0 ? list[0].name : res.regeocode.addressComponent
								.streetNumber.street,
							poiList: list
						});
					}
				});
			},

			resultTap(e) {
				//     adcode: "110101"
				// address: "1号线/八通线"
				// city: []
				// district: "北京市东城区"
				// id: "BV10006499"
				// location: "116.401216,39.907780"
				// name: "天安门东(地铁站)"
				// typecode: "150500"
				let location = e.currentTarget.dataset.location;
				let name = e.currentTarget.dataset.name;
				this.setData({
					currentName: name,
					lng: location.split(',')[0],
					lat: location.split(',')[1],
					resultShow: false,
					mapShow: true
				});
				this.getPoiList();
			},

			cityTap(e) {
				// this.setData({
				//   isTouchMap: false
				// });

				console.log('isTouchMap', this.isTouchMap);
				let city = e.currentTarget.dataset.city;
				console.log(city);
				util.request(api.gdCityUrl, {
					address: city,
					output: 'JSON',
					key: api.gdKey
				}).then((res) => {
					console.log(res);
					if (res.info == 'OK') {
						let location = res.geocodes[0].location;
						this.setData({
							current_city: city,
							lng: location.split(',')[0],
							lat: location.split(',')[1],
							cityShow: false,
							mapShow: true
						});
						this.getPoiList();

						// setTimeout(() => {
						//   this.setData({
						//     isTouchMap: true
						//   })
						// }, 500);
					}
				});
			},

			poiTap(e) {
				    // address: "菖蒲河沿9号(天安门东地铁站B东北口步行200米)"
				// businessarea: "东单"
				// direction: "东"
				// distance: "210.116"
				// id: "B0FFFLJW2Q"
				// location: "116.403456,39.908566"
				// name: "菖蒲河公园"
				// poiweight: "0.426156"
				// tel: []
				// type: "风景名胜;公园广场;公园"
				let poi = e.currentTarget.dataset.poi;
				console.log(poi);
				app.globalData.mapSelectFinish = true;
				app.globalData.mapSelectPoi = poi;
				uni.navigateBack();
			},

			mapUpdated(e) {
				console.log('mapupdated');
				console.log(e);
				// this.mapCtx = wx.createMapContext("myMap");
				this.mapCtx.getCenterLocation({
					success: (res) => {
						console.log(res);
					},
					fail: (res) => {}
				});
			}
		}
	};
</script>
<style>
	/* pages/jsCase/citySel/index.wxss */
	page {
		height: 100%;
		background: #f2f5f7;
	}

	.head {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		box-sizing: border-box;
		padding: 20rpx 20rpx 20rpx;
		background: #fff;
		z-index: 99999;
	}

	.search-box {
		display: flex;
		align-items: center;
	}

	.r_head {
		height: 90rpx;
	}

	.head_input {
		flex: 1;
		display: flex;
		align-items: center;
		height: 60rpx;
		padding-left: 16rpx;
		border-radius: 30rpx;
		background: #f2f5f7;
	}

	.search_icon {
		width: 30rpx;
		height: 30rpx;
		margin-right: 12rpx;
	}

	.head input {
		height: 60rpx;
		/* padding-left : 75rpx; */
		font-size: 28rpx;
	}

	.place_holder {
		font-size: 28rpx;
		color: #999999;
	}

	.sha_icon {
		margin-left: 18rpx;
		font-size: 28rpx;
		color: #333333;
	}

	.head_curr {
		height: 80rpx;
		display: flex;
		align-items: center;
		color: #333;
		font-size: 28rpx;
		/* padding-top: 20rpx; */
		box-sizing: border-box;
	}

	.h_c_icon {
		flex-shrink: 0;
		margin-right: 15rpx;
		width: 32rpx;
		height: 32rpx;
		margin-left: 12rpx;
	}

	.sy_container {
		box-sizing: border-box;
		width: 100%;
		height: 100vh;
		padding-top: 170rpx;
		position: relative;
		z-index: 9999;
	}

	.hot_city .title {
		padding: 10rpx 30rpx;
		color: #999;
		font-size: 26rpx;
	}

	.hot_city .box {
		background-color: #fff;
		padding: 5rpx 30rpx 15rpx 40rpx;
		box-sizing: border-box;
	}

	.hot_city .box .name {
		vertical-align: top;
		display: inline-block;
		min-width: 140rpx;
		line-height: 56rpx;
		height: 56rpx;
		border-radius: 28rpx;
		font-size: 28rpx;
		color: #333;
		text-align: center;
		padding: 0 20rpx;
		box-sizing: border-box;
		margin-top: 10rpx;
		margin-right: 20rpx;
		position: relative;
	}

	.hot_city .box .name::after {
		content: '';
		position: absolute;
		width: 200%;
		height: 200%;
		-webkit-transform-origin: 0 0;
		transform-origin: 0 0;
		-webkit-transform: scale(0.5, 0.5);
		transform: scale(0.5, 0.5);
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
		left: 0;
		top: 0;
		border-radius: 56rpx;
		border: 2rpx solid rgb(235, 225, 225);
	}

	.sel_city {
		color: #fff !important;
		background: pink;
	}

	.all_city .letter_name {
		height: 48rpx;
		font-size: 24rpx;
		color: #999;
		background: #f2f5f7;
		padding: 0 30rpx;
		line-height: 48rpx;
	}

	.all_city .city {
		background-color: #fff;
	}

	.all_city .city .name {
		width: 100%;
		padding: 30rpx;
		font-size: 28rpx;
		color: #333;
		position: relative;
		overflow: hidden;
	}

	.all_city .city .name::after {
		content: '';
		position: absolute;
		border-bottom: 1rpx solid #eaeef1;
		-webkit-transform: scaleY(0.5);
		transform: scaleY(0.5);
		bottom: 0;
		right: 0;
		left: 30rpx;
	}

	.city_hover {
		background-color: #eee !important;
	}

	.fixed_bar {
		position: fixed;
		z-index: 99999;
		top: 180rpx;
		right: 0px;
		padding-right: 10rpx;
		width: 50rpx;
		font-size: 22rpx;
		text-align: center;
	}

	.bar_item {
		background-color: rgb(233, 228, 220);
		border-radius: 50%;
	}

	@media screen and (max-width: 320px) {
		.fixed_bar {
			font-size: 20rpx;
		}
	}

	.bar_item_active {
		background-color: #fff;
		/* box-shadow      : 5rpx 5rpx 5rpx #f7c3ee; */
		box-shadow: 5rpx 5rpx 5rpx #09afff;
	}

	.fixed_letter {
		position: absolute;
		z-index: 20;
		width: 160rpx;
		height: 160rpx;
		left: 50%;
		top: 50%;
		margin-left: -80rpx;
		margin-top: -80rpx;
		border-radius: 80rpx;
		text-align: center;
		line-height: 160rpx;
		font-size: 70rpx;
		color: #fff;
		background-color: rgba(0, 0, 0, 0.5);
		/* box-shadow      : 5rpx 5rpx 5rpx #f7c3ee; */
		box-shadow: 5rpx 5rpx 5rpx #09afff;
	}

	/* 搜索结果 */
	.result_list {
		padding-top: 90rpx;
		background: #fff;
		width: 100%;
	}

	.r_item {
		width: 100%;
		position: relative;
		padding: 20rpx 20rpx 20rpx 30rpx;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
		border-bottom: 1rpx solid #eaeef1;
	}

	.r_item::after {
		/* content          : '';
  position         : absolute;
  border-bottom    : 1rpx solid #eaeef1;
  -webkit-transform: scaleY(0.5);
  transform        : scaleY(0.5);
  bottom           : 0;
  right            : 0;
  left             : 30rpx; */
	}

	.r_item_hover {
		background-color: #eee !important;
	}

	.no_data {
		margin-top: 80px;
		height: 500rpx;
		align-items: center;
		font-size: 26rpx;
		color: #999;
		display: flex;
		flex-direction: column;
	}

	.no_data image {
		width: 250rpx;
		height: 162rpx;
		margin-bottom: 30rpx;
	}

	#myMap {
		position: fixed;
		top: 80rpx;
		left: 0;
		z-index: 9;
		width: 100%;
		height: 580rpx;
		background-color: #f6f6f6;
	}

	.input-view {
		flex: 1;
	}

	.city-block {
		display: flex;
		align-items: center;
	}

	.arrow-img {
		width: 20rpx;
		height: 20rpx;
		margin: 0 8rpx;
		transform: rotate(0deg);
		transition: all 0.3s;
	}

	.arrow-up {
		transform: rotate(180deg);
		transition: all 0.3s;
	}

	.marker-name {
		z-index: 99;
		top: 282rpx;
		position: fixed;
		height: 68rpx;
		line-height: 68rpx;
		border-radius: 68rpx;
		background: #fff;
		padding: 0 20rpx;
		left: 50%;
		-webkit-transform: translate(-50%, 0);
		transform: translate(-50%, 0);
		display: inline-block;
	}

	.map-icon {
		position: fixed;
		z-index: 99;
		top: 350rpx;
		width: 70rpx;
		height: 70rpx;
		left: 340rpx;
	}

	.poi-list {
		position: fixed;
		background: #ffffff;
		z-index: 9999;
		top: 600rpx;
		width: 100%;
		left: 0;
		height: 1000rpx;
	}

	.poi-item {
		display: flex;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		align-items: center;
	}

	.poi-left {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.poi-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 12rpx;
	}

	.poi-address {
		font-size: 24rpx;
		color: #777;
	}

	.poi-right {
		margin-left: 40rpx;
	}

	.hot_city {
		position: relative;
		z-index: 9999;
		background: #f2f5f7;
	}

	.all_city {}



	.result_list {
		position: relative;
		z-index: 8888;
		min-height: 700rpx;
	}
</style>