<template>
	<view class="search-address-page">
		<custom-navbar title="搜索地址" :showBack="true" backgroundColor="#FFFFFF"></custom-navbar>
		<view class="search-container">
			<text class="search-container-text" @click="goSelectCity">
				{{ city.name }}
			</text>
			<image src="/static/images/Fill.jpg" mode="aspectFit" class="text-img"></image>
			<!-- <view class="address-header">
				<image src="/static/images/search.png" mode="aspectFit" class="search-icon"></image>
				<text class="search-text">请输入你的服务地址</text>
			</view> -->
			<!-- 搜索 -->
			<view class="hao-search">
				<view class="hao-searchCent">
					<image src="/static/images/search_1.png" class="hao-searchImg"></image>
					<input type="text" v-model="inputKey" @input="searchInput" placeholder="请输入你的服务地址"
						class="hao-searchInput" />
				</view>
			</view>
		</view>
		<scroll-view scroll-y class="address-list" v-if="searchResults" style="height: 200px;"
			:style="'height: ' + listHeight + 'px'">
			<view class="address-item" v-for="(item, index) in searchResults" :key="index" @click="selectAddress(item)">
				<view class="address-info">
					<text class="address-name">{{item.name}}</text>
					<text class="address-detail">{{item.address}}</text>
				</view>
				<view class="address-distance" v-if="item.distance">
					<text class="distance-text" v-if="item.distance<10000">{{item.distance}}m</text>
					<text class="distance-text" v-else>{{item.distance/1000}}km</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				city: {
					center: '',
					name: '',
				},
				inputKey: '', //搜索关键字
				searchResults: [],
				latitude: 0, // 38.351942
				longitude: 0, // 117.320266
				listHeight: 0,
			}
		},
		onShow() {
			//判断缓存中是否存有城市数据
			let searchCity = uni.getStorageSync('searchCity')
			if (searchCity) {
				this.city = searchCity
			} else {
				this.city = {
					center: '117.330043,38.372266',
					name: '黄骅'
				}
			}
			this.getCurrentLocation()

		},
		onLoad() {
			// 获取视图高度
			this.pageHeight = uni.getWindowInfo().safeArea.height;
			this.listHeight = parseInt(this.pageHeight) - 44 - 75
		},
		methods: {
			// 选择地址
			selectAddress(item) {
				// 返回上一页并传递选中的地址信息
				const pages = getCurrentPages()
				const prevPage = pages[pages.length - 3]
				prevPage.$vm.isNeedLocation = false;
				prevPage.$vm.updateAddress(item)

				uni.navigateBack({
					delta: 2 // 返回的页面数，2表示返回上上个页面
				});
				getApp().updateAddress(item);

			},
			// 将角度转换为弧度
			rad(d) {
				return d * Math.PI / 180;
			},
			//计算两点间距离
			getDistance(lat1, lng1, lat2, lng2, kilometreFlag = false) {
				// 将经纬度从角度转换为弧度
				const radLat1 = this.rad(lat1);
				const radLat2 = this.rad(lat2);

				// 计算纬度和经度的差值（弧度）
				const a = radLat1 - radLat2;
				const b = this.rad(lng1) - this.rad(lng2);

				// 使用哈弗辛公式计算两点间的球面距离
				let s = 2 * Math.asin(
					Math.sqrt(
						Math.pow(Math.sin(a / 2), 2) +
						Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
					)
				);

				// 乘以地球半径（6378.137公里）得到距离（公里）
				s = s * 6378.137;

				// 根据单位标识返回不同单位和精度的结果
				if (kilometreFlag) {
					// 返回公里单位，保留1位小数
					s = s.toFixed(1);
				} else {
					// 返回米单位，四舍五入取整
					s = Math.round(s * 1000).toFixed(0);
				}
				return s;
			},
			//跳转城市选择页
			goSelectCity() {
				uni.navigateTo({
					url: '/pages/address/selectCity'
				})
			},
			// 获取当前位置
			async getCurrentLocation() {
				let that = this;
				let longitude = '';
				let latitude = '';
				// const locationRes = await that.getLocation();

				let searchCity = uni.getStorageSync('searchCity')
				if (searchCity) {
					let locationRes = searchCity.center.split(','); //调用默认地址
					that.longitude = locationRes[0];
					that.latitude = locationRes[1];
				} else {
					let locationRes = getApp().globalData.addressRes; //调用默认地址
					that.longitude = locationRes.longitude;
					that.latitude = locationRes.latitude;
				}

				that.markers = [{
					latitude: that.latitude,
					longitude: that.longitude,
					iconPath: '/static/images/position_icon_3x.png'
				}]
				// 请求附近地址
				// types: '060000|070000|080000|090000|100000|120000|170000'
				that.getPlaceAround();
			},
			getPlaceAround() {
				let that = this;
				let data;
				if (!that.searchKeyword) {
					data = {
						key: '30b7eb1a1b2f88edc085b9b3ee9a2188',
						location: `${that.longitude},${that.latitude}`,
						page: 1,
						offset: 20
					}
				} else {
					data = {
						key: '30b7eb1a1b2f88edc085b9b3ee9a2188',
						location: `${that.longitude},${that.latitude}`,
						keywords: that.searchKeyword,
						page: 1,
						offset: 20
					}
				}
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'https://restapi.amap.com/v5/place/around',
						method: "GET",
						data: data,
						success(res) {
							console.log(res)
							that.searchResults = res.data.pois;
						}
					})
				})
			},
			//搜索输入
			searchInput() {
				if (!this.inputKey) {
					this.getCurrentLocation()
					return
				}
				let that = this;
				let data = {
					key: '30b7eb1a1b2f88edc085b9b3ee9a2188',
					keywords: this.inputKey,
					region: this.city.name,
					page: 1,
					offset: 20
				}
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'https://restapi.amap.com/v5/place/text',
						method: "GET",
						data: data,
						success(res) {
							let pois = res.data.pois
							let cityLt = that.city.center.split(',')
							pois.forEach(item => {
								let loc = item.location.split(',')
								item.distance = that.getDistance(cityLt[1], cityLt[0], loc[1], loc[
									0])
							})
							that.searchResults = pois;
						}
					})
				})
			},
		}
	}
</script>

<style scoped lang="less">
	::v-deep .uni-input-placeholder{
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 26rpx;
		color: #CCCCCC;
		line-height: 34rpx;
		text-align: left;
		font-style: normal;
	}
	.search-address-page {
		flex: 1;
		height: 100vh;
		overflow: hidden;
		width: 100%;
		background-color: #fafafa;
	}

	.search-container {
		// background-color: #FFFFFF;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 32rpx 30rpx 20rpx 30rpx;

		.search-container-text {
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
			line-height: 45rpx;
			text-align: left;
			font-style: normal;
		}

		.text-img {
			width: 20rpx;
			height: 12rpx;
			margin-left: 8rpx;
			margin-right: 26rpx;
		}

		/* 搜索 */
		.hao-search {
			// width: 100%;
			flex: 1;
			height: 68rpx;
			display: flex;
			// align-items: center;
			justify-content: center;

			.hao-searchCent {
				flex: 1;
				height: 68rpx;
				background: #FFFFFF;
				border: 2rpx solid #E8101E;
				background-color: #fafafa;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 68rpx;
				padding: 0 30rpx;
				box-sizing: border-box;

				.hao-searchImg {
					width: 29rpx;
					height: 32rpx;
					margin-right: 16rpx;
				}

				.hao-searchInput {
					flex: 1;
					height: 40rpx;
					font-size: 28rpx;
					color: #666;
				}
			}
		}
	}

	.address-list {
		box-shadow: 0rpx 0rpx 12rpx 0rpx rgba(0, 0, 0, 0.05);
	}

	.address-item {
		display: flex;
		flex-flow: row nowrap;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 1rpx solid #EEEEEE;
		background-color: #fff;
	}

	.address-info {
		display: flex;
		flex-direction: column;
		flex: 1;
		margin-right: 24rpx;

		&__user {
			display: flex;
			flex-direction: row;
		}
	}

	.address-name {
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 30rpx;
		color: #000000;
		line-height: 40rpx;
		text-align: left;
		font-style: normal;
		margin-bottom: 10rpx;
	}

	.address-detail {
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		font-size: 26rpx;
		color: #999999;
		line-height: 34rpx;
		text-align: left;
		font-style: normal;
	}

	.distance-text {
		font-size: 24rpx;
		color: #999999;
	}
</style>