<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">距您直线{{ item.distance }}公里</view>
							<view class="item_info">
								<view class="info_count">剩{{ item.roomNumber }}间</view>
								<view class="info_price">
									¥{{ item.min_price }}
									<text>起</text>
								</view>
							</view>
						</view>
					</view>
				</view>

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

		<!-- 选择乡镇弹窗区域 -->
		<uni-popup ref="popup" :is-mask-click="false" type="center">
			<view class="popup_body">
				<view class="body_header">
					<img src="../../static/my/popup_title.png" />
					<view class="header_title">请选择乡镇</view>
					<img src="../../static/my/popup_title.png" />

					<view class="header_jump" @click="handleChooseTown()">跳过</view>
				</view>
				<view class="body_content">
					<view class="content_box" v-for="(item, index) in popList" :key="index" @click="handleChooseTown(item.name)">
						<img v-if="index === 0" src="https://chtech.ncjti.edu.cn/hotelReservation/image/1.png" mode="aspectFill" />
						<img v-if="index === 1" src="https://chtech.ncjti.edu.cn/hotelReservation/image/2.png" mode="aspectFill" />
						<img v-if="index === 2" src="https://chtech.ncjti.edu.cn/hotelReservation/image/3.png" mode="aspectFill" />
						<img v-if="index === 3" src="https://chtech.ncjti.edu.cn/hotelReservation/image/4.png" mode="aspectFill" />
						<img v-if="index === 4" src="https://chtech.ncjti.edu.cn/hotelReservation/image/5.png" mode="aspectFill" />
						<img v-if="index === 5" src="https://chtech.ncjti.edu.cn/hotelReservation/image/6.png" mode="aspectFill" />
						<img v-if="index === 6" src="https://chtech.ncjti.edu.cn/hotelReservation/image/7.png" mode="aspectFill" />
						<img v-if="index === 7" src="https://chtech.ncjti.edu.cn/hotelReservation/image/8.png" mode="aspectFill" />
						<img v-if="index === 8" src="https://chtech.ncjti.edu.cn/hotelReservation/image/9.png" mode="aspectFill" />
						<img v-if="index === 9" src="https://chtech.ncjti.edu.cn/hotelReservation/image/10.png" mode="aspectFill" />
						<img v-if="index === 10" src="https://chtech.ncjti.edu.cn/hotelReservation/image/11.png" mode="aspectFill" />
						<img v-if="index === 11" src="https://chtech.ncjti.edu.cn/hotelReservation/image/12.png" mode="aspectFill" />
						<view class="box_town">{{ item.name }}</view>
						<view class="box_count">剩{{ item.residueNumber }}间</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</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,
			// 选择乡镇弹窗数据
			popList: []
		}
	},
	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)
		// this.openPop()
		// this.getResidueCount()
	},
	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: {
		// 弹窗点击选择乡镇地址回调
		handleChooseTown(name) {
			if (!name) {
				this.town = '靖安县'
			} else {
				this.town = name
			}
			uni.setNavigationBarTitle({
				title: this.town
			})
			this.$refs.popup.close()
			uni.showTabBar()
			this.getTownList()
			this.getLocation()
		},
		// 打开选择乡镇弹窗回调
		openPop() {
			this.$refs.popup.open()
			uni.hideTabBar()
		},
		// 页面上拉到底部回调
		handleRefresh() {
			if (this.hotelList.length < this.total) {
				this.page++
				this.getHotelList()
			} else {
				uni.showToast({
					title: '没有更多数据了',
					icon: 'none'
				})
			}
		},
		// 滚动条滚动回调
		handleScroll(e) {
			if (e.detail.scrollTop > 90) {
				this.isSticky = true
			} else {
				this.isSticky = false
			}
		},
		// 获取乡镇剩余房间数
		async getResidueCount() {
			const res = await this.$myRequest({
				url: '/mhotel/ahpgetResidueCount.action'
			})
			// console.log(res)
			if (res.code === 200) {
				let residueNumber = 0
				res.data.forEach((ele) => {
					residueNumber += ele.residueNumber
				})
				res.data.unshift({
					name: '靖安县',
					residueNumber
				})
				this.popList = res.data
			}
		},
		// 获取乡镇集合
		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}`
			})
		},
		// 选择地区时的回调
		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;
			}
		}
	}

	.popup_body {
		width: 618rpx;
		height: 687rpx;
		border-radius: 21rpx;
		background-color: #fff;

		.body_header {
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;
			height: 113rpx;
			border-bottom: 1rpx solid #e6e6e6;

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

			.header_title {
				margin: 0 10rpx;
				font-size: 34rpx;
				font-weight: bold;
				color: #0f194d;
			}

			.header_jump {
				position: absolute;
				top: 38rpx;
				right: 30rpx;
				font-size: 28rpx;
				color: #a6a6a6;
			}
		}
		.body_content {
			display: grid;
			grid-template-columns: repeat(auto-fill, 160rpx);
			gap: 28rpx;
			box-sizing: border-box;
			padding: 26rpx 40rpx 50rpx;

			.content_box {
				position: relative;
				width: 160rpx;
				height: 105rpx;
				color: #fff;
				border-radius: 10rpx;

				img {
					width: 160rpx;
					height: 105rpx;
					border-radius: 10rpx;
				}

				.box_town {
					position: absolute;
					top: 17rpx;
					left: 0;
					right: 0;
					text-align: center;
					font-size: 28rpx;
					font-weight: bold;
				}

				.box_count {
					position: absolute;
					top: 57rpx;
					left: 0;
					right: 0;
					text-align: center;
					font-size: 18rpx;
				}
			}
		}
	}
}
</style>
