<template>
	<view class="container" v-if="total !== null">
		<!-- 每一个订单区域 -->
		<uni-swipe-action>
			<uni-swipe-action-item v-for="item in orderList" :key="item.id">
				<!-- 右侧选项内容区域 -->
				<template v-slot:right>
					<view class="order_right" @click="handleDelete(item)">
						<img class="img" src="../../static/my/delete.png" />
					</view>
				</template>
				<view class="order_box" @click="goPageOrderDetail(item)">
					<!-- 标题区域 -->
					<view class="box_header">
						<img class="img" src="../../static/my/hotel.png" />
						<view class="title">{{ item.hotelName }}</view>
						<view class="type type2" v-if="item.orderStatus === '1'">
							待支付，剩余
							<uv-count-down v-if="item.countDownTime" :time="item.countDownTime" format="mm:ss" @finish="finish(item)"></uv-count-down>
						</view>
						<view class="type" v-if="item.orderStatus === '2'">已支付</view>
						<view class="type" v-if="item.orderStatus === '3'">待入住</view>
						<view class="type" v-if="item.orderStatus === '4'">已入住</view>
						<view class="type" v-if="item.orderStatus === '5'">已消费</view>
						<view class="type" v-if="item.orderStatus === '6'">支付超时</view>
						<view class="type" v-if="item.orderStatus === '7'">已取消</view>
						<view class="type" v-if="item.orderStatus === '8'">已退单</view>
						<view class="type" v-if="item.orderStatus === '9'">已退款</view>
						<view class="type" v-if="item.orderStatus === '10'">退款中</view>
					</view>

					<!-- 酒店信息区域 -->
					<view class="box_info">
						<img class="img" mode="aspectFill" :src="item.houseFileInfoList[0].url" />
						<view class="info_right">
							<view class="info_right_item">{{ item.houseOrderNumber }}间，{{ item.houseName }}</view>
							<view class="info_right_item">{{ (item.orderStartTime || '').slice(0, 10) }} - {{ (item.orderEndTime || '').slice(0, 10) }}</view>
							<view class="info_right_item">总价：¥{{ item.houseTotalPrice }}</view>
						</view>
					</view>

					<!-- 按钮区域 -->
					<view class="box_btn" v-if="item.orderStatus === '1' || item.orderStatus === '6' || item.orderStatus === '5'">
						<view class="btn_item" v-if="item.orderStatus === '5'" @click.stop="handleEvaluate(item)">去评价</view>
						<view class="btn_item pay" v-if="item.orderStatus === '1'" @click.stop="goPagePay(item)">去支付</view>
						<view class="btn_item" v-if="item.orderStatus === '6'" @click.stop="goPageDetail(item)">再次预定</view>
					</view>
				</view>
			</uni-swipe-action-item>
		</uni-swipe-action>

		<view class="noData" v-if="!orderList.length">
			<img src="../../static/images/noData.png" />
			暂无订单数据
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			// 订单列表
			orderList: [],
			// 倒计时时间（毫秒）
			countDownTime: 1000 * 60 * 15,
			// 当前页
			page: 1,
			// 每页多少条数据
			rows: 6,
			// 一共多少条数据
			total: null,
			// 是否显示距离差
			showdDistance: false,
			// 用户定位经度
			myLng: 0,
			// 用户定位纬度
			myLat: 0,
			// 删除数组
			deleteList: []
		}
	},
	onLoad() {},
	onUnload() {
		this.handleDeleteList()
	},
	onHide() {
		this.handleDeleteList()
	},
	onShow() {
		let openid = uni.getStorageSync('openid')
		if (openid) {
			this.total = null
			this.page = 1
			this.orderList = []
			this.getLocation()
		} else {
			uni.showToast({
				title: '请先登录',
				icon: 'none',
				mask: true
			})
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}, 1500)
		}
	},
	// 下拉刷新
	onPullDownRefresh() {
		this.handleDeleteList()
		setTimeout(() => {
			this.orderList = []
			this.page = 1
			this.getLocation()
			uni.stopPullDownRefresh()
		}, 2000)
	},
	// 上拉加载
	onReachBottom() {
		if (this.orderList.length < this.total - this.deleteList.length) {
			this.page++
			this.getOrderList()
		} else {
			uni.showToast({
				title: '没有更多数据了',
				icon: 'none',
				mask: true
			})
		}
	},
	methods: {
		// 获取用户当前位置
		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.getOrderList()
									}
								})
							},
							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.getOrderList()
											uni.showToast({
												title: '获取定位权限失败',
												icon: 'none'
											})
										}
									}
								})
							}
						})
					} else {
						uni.getLocation({
							type: 'gcj02',
							success: (res) => {
								this.myLat = res.latitude
								this.myLng = res.longitude
								this.showdDistance = true
								this.getOrderList()
							}
						})
					}
				}
			})
		},
		// 获取订单列表数据
		async getOrderList() {
			const res = await this.$myRequest({
				url: '/mhotel/ampgetBookingList.action',
				data: {
					userId: uni.getStorageSync('userInfo').id,
					page: this.page,
					rows: this.rows
				}
			})
			// console.log(res)
			if (res.code === 200) {
				this.total = res.data.total
				this.orderList = [...this.orderList, ...res.data.pageList]
				// 如果是待支付状态,算出剩余支付时间
				this.orderList.forEach((ele) => {
					if (ele.orderStatus === '1') {
						let temLockTime = ele.lockTime ? ele.lockTime * 1 : 15
						// 兼容ios部分系统转换时间格式
						let createTime = ele.createTime.slice(0, 19).replace(/-/g, '/')
						ele.countDownTime = new Date(createTime).getTime() + temLockTime * 60 * 1000 - new Date().getTime()
					}
				})

				// 如果定位成功则获取和民宿之间的距离
				if (this.showdDistance && this.orderList.length) {
					this.orderList.forEach((ele) => {
						let lat = ele.hotelHpositionWens.split(',')[0]
						let lng = ele.hotelHpositionWens.split(',')[1]
						ele.distance = this.calculateDistance(lat, lng)
					})
				}
			}
		},
		// 倒计时结束回调
		async finish(item) {
			const res = await this.$myRequest({
				url: '/mhotel/abkupdateOrderStatus.action',
				data: {
					bookingId: item.id
				}
			})
			// console.log(res)
			if (res.code === 200) {
				item.orderStatus = '6'
			}
			// uni.showModal({
			// 	title: '提示',
			// 	content: '订单已超过可支付时间',
			// 	showCancel: false,
			// 	success: async (res) => {
			// 		if (res.confirm) {
			// 			const res = await this.$myRequest({
			// 				url: '/mhotel/abkupdateOrderStatus.action',
			// 				data: {
			// 					bookingId: item.id
			// 				}
			// 			})
			// 			// console.log(res)
			// 			if (res.code === 200) {
			// 				uni.switchTab({
			// 					url: '/pages/my/my'
			// 				})
			// 			}
			// 		}
			// 	}
			// })
		},
		// 点击去支付按钮回调
		goPagePay(item) {
			console.log(item.countDownTime)
			if (item.countDownTime <= 0) {
				uni.showModal({
					title: '提示',
					content: '订单已超过可支付时间',
					showCancel: false,
					success: async (res) => {
						if (res.confirm) {
							const res = await this.$myRequest({
								url: '/mhotel/abkupdateOrderStatus.action',
								data: {
									bookingId: item.id
								}
							})
							// console.log(res)
							if (res.code === 200) {
								this.page = 1
								this.orderList = []
								this.getOrderList()
							}
						}
					}
				})
			} else {
				this.handleDeleteList()
				uni.navigateTo({
					url: `/pages/pay/pay?id=${item.id}`
				})
			}
		},
		// 点击再次预定按钮回调
		goPageDetail(item) {
			this.handleDeleteList()
			uni.navigateTo({
				url: `/pages/detail/detail?id=${item.hotelId}&distance=${item.distance}`
			})

			// if (item.hstatus === 1 && item.hotelStatus === 1) {
			// 	uni.showModal({
			// 		title: '提示',
			// 		content: '确定再次预定吗？',
			// 		success: async (res) => {
			// 			if (res.confirm) {
			// 				const result = await this.$myRequest({
			// 					url: '/mhotel/abkcreateOrder.action',
			// 					data: {
			// 						houseId: item.houseId,
			// 						startTime: item.orderStartTime.slice(0, 10),
			// 						endTime: item.orderEndTime.slice(0, 10),
			// 						houseOrderNumber: item.houseOrderNumber,
			// 						userName: item.userName,
			// 						userPhone: item.userPhone,
			// 						userId: uni.getStorageSync('userInfo').id
			// 					}
			// 				})
			// 				if (result.code === 200) {
			// 					uni.navigateTo({
			// 						url: `/pages/pay/pay?id=${result.data}`
			// 					})
			// 				}
			// 			}
			// 		}
			// 	})
			// } else {
			// 	uni.showToast({
			// 		title: '该民宿暂时无法预定',
			// 		icon: 'none',
			// 		mask: true
			// 	})
			// }
		},
		// 点击每一个订单回调
		goPageOrderDetail(item) {
			this.handleDeleteList()
			// console.log(item)
			uni.navigateTo({
				url: `/pages/orderDetail/orderDetail?id=${item.id}&distance=${item.distance}`
			})
		},
		// 右侧选项内容删除按钮回调
		handleDelete(item) {
			// console.log(item)
			if (
				item.orderStatus === '1' ||
				item.orderStatus === '5' ||
				item.orderStatus === '6' ||
				item.orderStatus === '7' ||
				item.orderStatus === '8' ||
				item.orderStatus === '9'
			) {
				uni.showModal({
					title: '提示',
					content: '确定删除吗？删除后不可恢复',
					// async
					success: (res) => {
						if (res.confirm) {
							// const res = await this.$myRequest({
							// 	url: '/mhotel/abkdelBooking.action',
							// 	data: {
							// 		bookingId: item.id
							// 	}
							// })
							// // console.log(res)
							// if (res.code === 200) {
							// 	uni.showToast({
							// 		title: '删除成功',
							// 		icon: 'success',
							// 		mask: true
							// 	})
							// 	setTimeout(() => {
							// 		this.orderList = []
							// 		this.page = 1
							// 		this.getOrderList()
							// 	}, 1500)
							// }

							this.deleteList.push(item.id)
							const num = this.orderList.findIndex((v) => v.id === item.id)
							this.orderList.splice(num, 1)
							if (this.orderList.length < this.rows && this.total - this.deleteList.length > this.orderList.length) {
								this.page++
								this.getOrderList()
							}
							// this.total = this.total - this.deleteList.length
							// console.log(this.total)
							uni.showToast({
								title: '删除成功',
								icon: 'success',
								mask: true
							})
						}
					}
				})
			} else {
				uni.showToast({
					title: '当前状态订单不可删除',
					icon: 'none',
					mask: true
				})
			}
		},
		// 批量删除
		handleDeleteList() {
			this.deleteList.forEach(async (ele) => {
				const res = await this.$myRequest({
					url: '/mhotel/abkdelBooking.action',
					data: {
						bookingId: ele
					}
				})
				// console.log(res)
				if (res.code === 200) {
					const num = this.deleteList.findIndex((v) => v === ele)
					this.deleteList.splice(num, 1)
					// uni.showToast({
					// 	title: '删除成功',
					// 	icon: 'success',
					// 	mask: true
					// })
					// setTimeout(() => {
					// 	this.orderList = []
					// 	this.page = 1
					// 	this.getOrderList()
					// }, 1500)
				}
			})
		},
		handleEvaluate(item) {
			this.handleDeleteList()
			uni.navigateTo({
				url: `/pages/evaluate/evaluate?bookingId=${item.id}&hotelId=${item.hotelId}&houseId=${item.houseId}`
			})
		},
		// 计算两个点之间的距离
		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 {
	box-sizing: border-box;
	padding: 0 20rpx 40rpx;
	min-height: 100vh;
	background-color: #f2f3f5;
	overflow-y: auto;

	.order_right {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 20rpx;
		width: 126rpx;
		background-color: #d43030;

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

	.order_box {
		margin-top: 20rpx;
		box-sizing: border-box;
		padding: 0 22rpx;
		width: 710rpx;
		border-radius: 15rpx;
		background-color: #fff;

		.box_header {
			display: flex;
			align-items: center;
			height: 94rpx;

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

			.title {
				margin-left: 16rpx;
				width: 350rpx;
				font-size: 32rpx;
				font-weight: bold;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			.type {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				margin-left: auto;
				width: 285rpx;
				color: #808080;
				font-size: 28rpx;
			}

			.type2 {
				color: #ff5733;
			}
		}

		.box_info {
			display: flex;
			height: 140rpx;

			.img {
				width: 100rpx;
				height: 100rpx;
				border-radius: 9rpx;
			}

			.info_right {
				display: flex;
				flex-direction: column;
				justify-content: space-around;
				margin-top: -5rpx;
				margin-left: 18rpx;
				height: 120rpx;
				color: #808080;
				font-size: 28rpx;

				.info_right_item {
					flex: 1;
				}
			}
		}

		.box_btn {
			display: flex;
			justify-content: flex-end;
			margin-top: -10rpx;
			height: 100rpx;

			.btn_item {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-left: 20rpx;
				width: 178rpx;
				height: 68rpx;
				border-radius: 64rpx;
				color: #808080;
				font-size: 28rpx;
				border: 1rpx solid #808080;
			}

			.pay {
				color: #fff;
				border: none;
				background-color: #096562;
			}
		}
	}

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

		img {
			margin-top: 150rpx;
			width: 600rpx;
			height: 600rpx;
		}
	}
}

// 修改倒计时字体颜色
::v-deep .uv-count-down .uv-count-down__text {
	color: #ff5733;
}
</style>
