<template>
	<view class="container">
		<!-- 搜索框区域 -->
		<view class="content">
			<uv-row custom-style="margin: 10px 0px" gutter="10">
				<picker @change="bindPickerChange" range-key="name" :value="placeIndex" :range="placeList">
					<view class="address">
						<view class="address_text">{{ placeList[placeIndex].name }}</view>
						<img src="../../static/index/bottom.png" />
					</view>
				</picker>

				<view class="search">
					<view class="add">
						<image class="img" src="../../static/index/search.png" mode="aspectFit"></image>
					</view>
					<input class="inp" type="text" v-model="keywords" placeholder="请输入关键字搜索" />
					<view class="btnSearch" @click="searchHandler">搜索</view>
				</view>
			</uv-row>
		</view>

		<view class="main">
			<!-- 添加一层view解决 css属性 sticky 不生效问题 -->
			<view>
				<!-- 分段器区域 -->
				<view class="control" :class="{ sticky: isSticky }">
					<uni-segmented-control :current="current" :values="items" style-type="text" active-color="#096562" @clickItem="onClickItem" />
				</view>

				<!-- 民宿列表 -->
				<view class="box" v-if="hotelList.length">
					<!-- 列表区域 -->
					<view class="box_body">
						<!-- 每一个民宿区域 -->
						<view class="box_item" v-for="item in hotelList" :key="item.id" @click="goPageDetail(item)">
							<img mode="aspectFill" :src="item.coverImg" />
							<view class="item_name">{{ item.hotel_name }}</view>
							<view class="item_rate">
								<view class="rate_left">{{ item.scoreHotel || '5.0' }}</view>
							</view>
							<view class="item_distance" v-if="item.distance">距您直线{{ item.distance }}公里</view>
							<view class="item_info">
								<view class="info_count">剩{{ item.roomNumber }}间</view>
								<view class="info_price">
									¥{{ item.min_price ? item.min_price : 0 }}
									<text>起</text>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 没有数据时展示的页面 -->
				<view class="noData" v-else>
					<img src="../../static/images/noData.png" />
					暂无数据
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			// 分段器数组
			items: ['白金级', '金宿级', '银宿级'],
			// 当前索引
			current: 0,
			// 地区数组
			placeList: [
				{
					name: '靖安县'
				}
			],
			// 当前选择地区索引
			placeIndex: 0,
			// 搜索框绑定数据
			keywords: '',
			// 是否显示距离差
			showdDistance: false,
			// 用户定位经度
			myLng: 0,
			// 用户定位纬度
			myLat: 0,
			// 当前页
			page: 1,
			// 每页多少条
			rows: 6,
			// 总条数
			total: null,
			// 民宿列表数组
			hotelList: [],
			// 当前乡镇
			town: '',
			// 分段器是否吸顶
			isSticky: false
		}
	},
	onLoad(options) {
		// console.log(options)
		this.keywords = options.keywords
		if (!options.level || options.level === '白金级') {
			this.current = 0
		} else if (options.level === '金宿级') {
			this.current = 1
		} else if (options.level === '银宿级') {
			this.current = 2
		}
		uni.setNavigationBarTitle({
			title: options.town || '靖安县'
		})
		this.getTownList(options.town)
	},
	onReachBottom() {
		if (this.hotelList.length < this.total) {
			this.page++
			this.getHotelList()
		} else {
			uni.showToast({
				title: '没有更多数据了',
				icon: 'none'
			})
		}
	},
	// 页面下拉刷新回调
	onPullDownRefresh() {
		setTimeout(() => {
			this.hotelList = []
			this.page = 1
			this.getLocation()
			uni.stopPullDownRefresh()
		}, 2000)
	},
	methods: {
		// 获取乡镇集合
		async getTownList(town) {
			const res = await this.$myRequest({
				url: '/mhotel/hotelqueryList.action',
				method: 'get',
				data: {
					code: 10
				}
			})
			// console.log(res)
			if (res.code === 200) {
				this.placeList = [...this.placeList, ...res.data]
				let temindex
				this.placeList.forEach((ele, index) => {
					if (ele.name === town) {
						temindex = index
					}
				})
				this.placeIndex = temindex || 0
				this.getLocation()
				// console.log(this.placeIndex)
			}
		},
		// 获取用户当前位置
		getLocation() {
			uni.getSetting({
				success: (res) => {
					if (!res.authSetting['scope.userLocation']) {
						uni.authorize({
							scope: 'scope.userLocation',
							success: (res) => {
								// 授权成功
								uni.getLocation({
									type: 'gcj02',
									success: (res) => {
										this.myLat = res.latitude
										this.myLng = res.longitude
										this.showdDistance = true
										this.getHotelList()
									}
								})
							},
							fail: () => {
								uni.showModal({
									content: '获取定位权限失败将会影响使用部分功能，是否去设置打开？',
									confirmText: '确认',
									cancelText: '取消',
									success: (res) => {
										if (res.confirm) {
											uni.openSetting({
												success: (res) => {
													console.log(res)
													this.getLocation()
												}
											})
										} else {
											this.showdDistance = false
											this.getHotelList()
											uni.showToast({
												title: '获取定位权限失败',
												icon: 'none'
											})
										}
									}
								})
							}
						})
					} else {
						uni.getLocation({
							type: 'gcj02',
							success: (res) => {
								this.myLat = res.latitude
								this.myLng = res.longitude
								this.showdDistance = true
								this.getHotelList()
							}
						})
					}
				}
			})
		},
		// 获取民宿列表
		async getHotelList() {
			let type
			if (this.current === 0) {
				type = 3
			} else if (this.current === 1) {
				type = 2
			} else if (this.current === 2) {
				type = 1
			}
			const res = await this.$myRequest({
				url: '/mhotel/ahphomePage.action',
				data: {
					queryValue: this.keywords,
					page: this.page,
					rows: this.rows,
					hotel_township: this.placeList[this.placeIndex].id || '',
					userId: uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').id : '',
					type
				}
			})
			// console.log(res)
			if (res.code === 200) {
				this.hotelList = [...this.hotelList, ...res.data.pageList]
				this.total = res.data.total

				// 如果定位成功则获取和民宿之间的距离
				if (this.showdDistance && this.hotelList.length) {
					this.hotelList.forEach((ele) => {
						let lat = ele.hpositionWens.split(',')[0]
						let lng = ele.hpositionWens.split(',')[1]
						ele.distance = this.calculateDistance(lat, lng)
					})
				}
			}
		},
		// 点击每一个民宿卡片回调
		goPageDetail(item) {
			uni.navigateTo({
				url: `/pages/detail/detail?id=${item.id}&distance=${item.distance}&town=${item.hotelTownshipName}`
			})
		},
		// 选择地区时的回调
		bindPickerChange(e) {
			this.placeIndex = e.detail.value
			uni.setNavigationBarTitle({
				title: this.placeList[this.placeIndex].name
			})
			this.hotelList = []
			this.page = 1
			this.getHotelList()
		},
		// 搜索按钮点击回调
		searchHandler() {
			this.hotelList = []
			this.page = 1
			this.getHotelList()
		},
		onClickItem(e) {
			if (this.current !== e.currentIndex) {
				this.current = e.currentIndex
				this.hotelList = []
				this.page = 1
				this.getHotelList()
			}
		},
		// 计算两个点之间的距离
		calculateDistance(lat, lng) {
			let centerLat = lat
			let centerLng = lng

			let red1 = (this.myLat * Math.PI) / 180.0
			let red2 = (centerLat * Math.PI) / 180.0
			let a = red1 - red2
			let b = (this.myLng * Math.PI) / 180.0 - (centerLng * Math.PI) / 180.0
			let R = 6378137
			let distance = R * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(red1) * Math.cos(red2) * Math.pow(Math.sin(b / 2), 2)))
			let res = (distance / 1000).toFixed(2) * 1

			return res
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	width: 750rpx;
	min-height: 100vh;
	padding: 0 30rpx;
	box-sizing: border-box;
	overflow-y: auto;
	background-color: #f7f7f7;

	.content {
		position: sticky;
		background-color: #f7f7f7;

		.address {
			display: flex;
			width: 152rpx;
			font-size: 28rpx;

			.address_text {
				width: 104rpx;
				text-align: center;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			img {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.search {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 538rpx;
			height: 80rpx;
			opacity: 1;
			border-radius: 70px;
			background-color: #fff;

			.add {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-left: 10rpx;
				width: 60rpx;
				font-size: 50rpx;
				height: 60rpx;
				line-height: 60rpx;
				color: rgba(30, 125, 251, 1);

				.img {
					width: 30rpx;
					height: 30rpx;
				}
			}

			.inp {
				height: 60rpx;
				line-height: 60rpx;
				flex-grow: 1;
				font-size: 28rpx;
			}

			.btnSearch {
				width: 100rpx;
				text-align: center;
				margin-right: 10rpx;
				height: 60rpx;
				line-height: 60rpx;
				opacity: 1;
				font-size: 28rpx;
				font-weight: 400;
				height: 2rem;
				color: #096562;
			}
		}
	}

	.main {
		.icons {
			display: flex;
			justify-content: space-around;
			align-items: center;
			height: 158rpx;
			border-radius: 12rpx;
			background-color: #fff;

			.icon_item {
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 20%;

				.item_top {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;

					img {
						width: 28rpx;
						height: 27rpx;
					}

					.img2 {
						width: 40rpx;
						height: 25.5rpx;
					}
					.img3 {
						width: 31rpx;
						height: 21rpx;
					}
				}

				.color {
					background-color: #d8e8e8;
				}

				.color2 {
					background-color: #c2f2d5;
				}
				.color3 {
					background-color: #f7d4ba;
				}
				.color4 {
					background-color: #fae1e2;
				}
				.color5 {
					background-color: #d0e0f2;
				}

				.item_bottom {
					margin-top: 6rpx;
					font-size: 28rpx;
				}
			}
		}

		.control {
			margin: 20rpx 0;
			height: 90rpx;
			border-radius: 8rpx;
			background-color: #fff;
		}

		.sticky {
			position: sticky;
			top: 0;
			border-radius: 0;
		}

		.box {
			.box_body {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;

				.box_item {
					margin-bottom: 20rpx;
					width: 335rpx;
					height: 446rpx;
					border-radius: 10rpx;
					background-color: #fff;

					img {
						width: 335rpx;
						height: 223rpx;
						border-radius: 10rpx 10rpx 0 0;
					}

					.item_name {
						margin-left: 22rpx;
						margin-top: 10rpx;
						line-height: 55rpx;
						font-size: 28rpx;
						font-weight: bold;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.item_rate {
						display: flex;
						align-items: center;
						margin-left: 22rpx;
						font-size: 24rpx;

						.rate_left {
							padding: 0 12rpx;
							color: #fff;
							// border-radius: 32rpx 0 0 32rpx;
							border-radius: 32rpx;
							background-color: #096562;
						}

						.rate_right {
							padding: 0 16rpx 0 7rpx;
							color: #096562;
							border-radius: 0 32rpx 32rpx 0;
							background-color: #dff2f2;
						}
					}

					.item_distance {
						margin-top: 10rpx;
						margin-left: 22rpx;
						color: #a6a6a6;
						font-size: 24rpx;
					}

					.item_info {
						box-sizing: border-box;
						padding: 0 30rpx 0 25rpx;
						margin-top: 16rpx;
						display: flex;
						justify-content: space-between;
						color: #ff5733;

						.info_count {
							font-size: 24rpx;
						}

						.info_price {
							margin-top: -5rpx;
							font-size: 36rpx;
							font-weight: bold;

							text {
								color: #a6a6a6;
								font-size: 24rpx;
								font-weight: 400;
							}
						}
					}
				}
			}
		}

		.noData {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			img {
				margin-top: 150rpx;
				width: 400rpx;
				height: 400rpx;
			}
		}
	}
}
</style>
