<template>
	<view>
		<view class="top">
			<!-- #ifdef MP-WEIXIN -->
			<NavigateBar :title="title" control="home" bgcolor="#a09cc4"></NavigateBar>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY -->
			<NavigateBar :title="title" bgcolor="#a09cc4"></NavigateBar>
			<!-- #endif -->
		</view>
		<view class="room-type-item">
			<view class="room-type-item-left">
				<u-image :src="roomPicPath" width="200rpx" height="200rpx" radius="10"></u-image>
			</view>
			<view class="room-type-item-middle">
				<view class="room-type-item-middle-text">
					<text>{{roomTypeName ? roomTypeName : ""}}</text>
				</view>
				<view class="room-type-item-middle-text">
					<text>{{order.room ? order.room : ""}}</text>
				</view>
			</view>
			<view class="room-type-item-right">
				<view class="room-type-item-right-text">
					<text>￥{{unitPrice ? unitPrice : 0}}</text>
				</view>
			</view>
		</view>

		<view class="checkin-date-info">
			<view class="date-selector">
				<view class="date-item">
					<u-text text="入住" color="#666666" size="15"></u-text>
					<view class="date-info">
						<u-text :text="startDate" color="#333333" size="14" bold></u-text>
						<u-text :text="startDay" color="#333333" size="14" bold></u-text>
					</view>
				</view>
				<view class="date-item">
					<u-text text="离店" color="#666666" size="15"></u-text>
					<view class="date-info">
						<u-text :text="endDate" color="#333333" size="14" bold></u-text>
						<u-text :text="endDay" color="#333333" size="14" bold></u-text>
					</view>
				</view>
			</view>
			<view class="day-num">
				<u-text :text="'共' + order.dayNum + '晚'" color="#333333" size="15" bold></u-text>
			</view>
		</view>

		<!-- #ifdef MP-WEIXIN  -->
		<u-swipe-action>
			<u-swipe-action-item :options="options" v-for="(info,index) in checkinInfo" @click="deleteGuest"
				:name="index" :disabled="index ===0">
				<u-form labelPosition="left" labelWidth="180rpx" labelAlign="center">
					<u-form-item label="姓名" prop="name">
						<u-text :text="info.name" border="none" clearable fontSize="36rpx"></u-text>
					</u-form-item>
					<u-form-item label="身份证" prop="idNumber">
						<u-text :text="info.idNumber" border="none" clearable fontSize="36rpx"></u-text>
					</u-form-item>
				</u-form>
			</u-swipe-action-item>
		</u-swipe-action>
		<!-- #endif -->

		<!-- #ifdef MP-ALIPAY -->
		<view v-for="(info,index) in checkinInfo" :key="index" class="guest-info">
			<ant-swipe-action :rightButtons="rightBtns" @swipeStart="onSwipeStart" @swipeEnd="onSwipeEnd"
				@buttonTap="deleteGuestAli" :swiped="swipeIndex === index" :data-item="index" :disabled="index ===0">
				<view class="swipe-item">
					<u-form labelPosition="left" labelWidth="180rpx" labelAlign="center">
						<u-form-item label="姓名" prop="name">
							<u-text :text="info.name" border="none" clearable fontSize="36rpx"></u-text>
						</u-form-item>
						<u-form-item label="身份证" prop="idNumber">
							<u-text :text="info.idNumber" border="none" clearable fontSize="36rpx"></u-text>
						</u-form-item>
					</u-form>
				</view>
			</ant-swipe-action>
		</view>
		<!-- #endif -->

		<view class="add-guest-btn-container">
			<u-button text="添加同住人" @click="gotoAddGuest"></u-button>
		</view>

		<view class="paymentArea" v-if="confirmDone">
			<view class="paymentArea--left">
				<view class="price">
					<text>合计:</text>
					<text>￥{{order.price ? order.price : ""}}</text>
				</view>
				<view class="deposit">
					<text text="" align="right" size="20">(注：需付押金{{order.deposit ? order.deposit : ""}}元)</text>
				</view>
			</view>
			<view class="completeBtn">
				<button class="u-button" @click="pay">支付</button>
			</view>
		</view>

		<view class="confirm-btn-container" v-else>
			<u-button text="确认" color="#9e97c3" @click="confirmOrder"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		getDay
	} from '../../utils/commonUtils.js'
	import {
		IMG_BASE_URL
	} from "../../config.js"
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import moment from "moment";
	import NavigateBar from "../../components/navigateBar/navigate-bar.vue";
	export default {
		components: {
			NavigateBar
		},
		data() {
			return {
				roomPicPath: '',
				roomTypeName: '',
				unitPrice: '',
				startDate: this.startDate,
				startDay: this.startDay,
				endDate: this.endDate,
				endDay: this.endDay,
				arrowPicPath: '/static/arrow.png',
				confirmDone: false,
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#FF0000'
					}
				}],
				title: "",
				// #ifdef MP-ALIPAY
				rightBtns: [{
					text: "删除",
					bgColor: "#FF0000",
					color: '#fff',
				}],
				swipeIndex: -1,
				// #endif
			};
		},
		computed: {
			...mapState('m_user', ['userInfo']),
			...mapState('m_business', ['order', 'currentHotel', 'checkinInfo']),
		},
		methods: {
			...mapMutations('m_business', ['updateCheckinInfo', 'updateOrder']),
			gotoAddGuest() {
				uni.navigateTo({
					url: '/subpkg_checkin/addGuest/addGuest'
				})
			},
			// #ifdef MP-WEIXIN
			deleteGuest(info) {
				if (info.name === 0) {
					return
				}
				this.checkinInfo.splice(info.name, 1)
				this.updateCheckinInfo(this.checkinInfo)
			},
			// #endif
			async confirmOrder() {
				//小程序创建的订单，先在后台创建订单，创建成功后跳转至支付页面
				if (this.order.orderSource === 'MINI_APP') {
					if (!this.order.orderId) {
						let createOrderRes = await uni.$http.post('/hotelOrder', this.order)
						if (createOrderRes.data.code !== 200) {
							uni.$showMsg('订单创建失败，请重试')
							return
						}
						this.updateOrder(createOrderRes.data.data)
					}
					this.confirmDone = true
					this.title = '订单支付'
				} else {
					//pms预定订单，若未支付跳转至支付页面，若已支付跳转至入住页面
					if (this.order.paymentStatus !== 'PAID') {
						this.confirmDone = true
						this.title = '订单支付'
					} else {
						uni.navigateTo({
							url: '/subpkg_checkin/checkin/checkin'
						})
					}
				}
			},
			async pay() {
				console.log("pay start");

				// #ifdef MP-WEIXIN
				let res = await uni.$http.post('/hotelOrder/payment', {
					openid: this.userInfo.openid,
					orderId: this.order.orderId,
					platform: 'WECHAT',
					hotelId: this.currentHotel.hotelId
				})
				if (res.data.code == 200) {
					res.data.data.package = res.data.data.packageStr
					try {
						let paymentResult = await wx.requestPayment(res.data.data)
						console.log("payment result:", paymentResult)
						if (paymentResult.errMsg === 'requestPayment:ok') {
							uni.$showMsg("支付成功")
							uni.redirectTo({
								url: '/subpkg_checkin/checkin/checkin'
							})
						}
					} catch {
						uni.$http.post(`/hotelOrder/cancelPayment/${this.order.id}`)
					}
				} else {
					uni.showModal({
						content: '房间已被占用，请重新选房',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/subpkg_checkin/selectRoom/selectRoom?roomType=' +
										this.order.roomType
								})
							}
						}
					})
				}
				// #endif

				// #ifdef MP-ALIPAY
				if (Number(this.order.deposit) === 0) {
					await this.aliPaymentNormal()
				} else {
					await this.aliPaymentFreeze()
				}
				// #endif
			},
			// #ifdef MP-ALIPAY
			onSwipeStart() {
				this.swipeIndex = ""
			},
			onSwipeEnd(arg1, arg2) {
				console.log(arg1, arg2);
				let index = arg2.target.dataset.item
				if (arg1.swiped) {
					this.swipeIndex = index
				}
			},
			deleteGuestAli() {
				this.checkinInfo.splice(this.swipeIndex, 1)
				this.updateCheckinInfo(this.checkinInfo)
			},
			async aliPaymentNormal() {
				// 申请获取预付号
				let alipayRes = await uni.$http.post('/hotelOrder/alipayPrepay', {
					openid: this.userInfo.openid,
					orderId: this.order.orderId,
					platform: 'ALIPAY',
					hotelId: this.currentHotel.hotelId
				})
				// console.log("获取预付号",alipayRes.data)
				if (!alipayRes.data.success) {
					console.log("获取预付号失败");
					uni.showModal({
						content: '房间已被占用，请重新选房',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/subpkg_checkin/selectRoom/selectRoom?roomType=' +
										this.order.roomType
								})
							}
						}
					})
					return
				}

				// 根据预付号发起支付
				let tradeNo = alipayRes.data.data.tradeNo
				let tradeRes = await my.tradePay({
					tradeNO: tradeNo
				})
				// console.log("tradeRes 交易支付结果",tradeRes.resultCode);

				if (tradeRes.resultCode === "6001") {
					console.log("支付未完成。");
					uni.$http.post(`/hotelOrder/cancelPayment/${this.order.id}`)
				}

				if (tradeRes.resultCode === "6002") {
					// 网络连接出错
					uni.showModal({
						title: "网络连接出错",
						content: "网络连接出错，请检查网络连接后重试。",
					});
					uni.$http.post(`/hotelOrder/cancelPayment/${this.order.id}`)
				}

				// 顾客支付后，查询支付状态
				if (["9000", "6004", "8000"].includes(tradeRes.resultCode)) {
					// 顾客支付订单后，查询支付宝侧的订单支付状态，只有TRADE_SUCCESS才为支付成功
					let tradeStatus = await uni.$http.post('/hotelOrder/queryAlipayTradeStatus', {
						tradeNo: tradeNo,
						hotelId: this.currentHotel.hotelId
					})
					// console.log("tradeStatus", tradeStatus);
					if (tradeStatus.data.success && tradeStatus.data.data.tradeStatus === "TRADE_SUCCESS") {
						uni.$showMsg("支付成功")
						uni.navigateTo({
							url: '/subpkg_checkin/checkin/checkin'
						})
					} else {
						uni.$http.post(`/hotelOrder/cancelPayment/${this.order.id}`)
					}
				}
			},
			async aliPaymentFreeze() {
				// 申请获取签名字符串
				let alipayRes = await uni.$http.post('/hotelOrder/alipayFreezeFund', {
					orderId: this.order.orderId,
					hotelId: this.currentHotel.hotelId
				})
				console.log("签名字符串", alipayRes.data)

				if (!alipayRes.data.success) {
					console.log("获取签名字符串失败");
					uni.showModal({
						content: '房间已被占用，请重新选房',
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/subpkg_checkin/selectRoom/selectRoom?roomType=' +
										this.order.roomType
								})
							}
						}
					})
					return
				}

				// 根据签名字符串发起授权
				let orderString = alipayRes.data.data
				let tradeRes = await my.tradePay({
					orderStr: orderString
				})
				// console.log("tradeRes 授权结果",tradeRes.resultCode);

				if (tradeRes.resultCode === "6001") {
					console.log("支付未完成。");
					uni.$http.post(`/hotelOrder/cancelPayment/${this.order.id}`)
				}

				if (tradeRes.resultCode === "6002") {
					// 网络连接出错
					uni.showModal({
						title: "网络连接出错",
						content: "网络连接出错，请检查网络连接后重试。",
					});
					uni.$http.post(`/hotelOrder/cancelPayment/${this.order.id}`)
				}

				// 顾客授权后，查询授权状态
				if (["9000", "6004", "8000"].includes(tradeRes.resultCode)) {
					// 顾客授权后，查询授权状态，只有AUTHORIZED（已授权状态：授权成功，可以进行转支付或解冻操作）才算成功
					let tradeStatus = await uni.$http.post('/hotelOrder/queryFreezeStatus', {
						orderId: this.order.orderId,
						hotelId: this.currentHotel.hotelId
					})
					// console.log("tradeStatus", tradeStatus);
					if (tradeStatus.data.success && tradeStatus.data.data === "AUTHORIZED") {
						uni.$showMsg("支付成功")
						uni.navigateTo({
							url: '/subpkg_checkin/checkin/checkin'
						})
					} else {
						uni.$http.post(`/hotelOrder/cancelPayment/${this.order.id}`)
					}
				}
			}
			// #endif
		},
		async onLoad() {
			let res = await uni.$http.post('/roomType', {
				roomType: this.order.roomType,
				hotelId: this.currentHotel.hotelId,
				pageNo: 1,
				pageSize: 999
			})
			this.roomPicPath = IMG_BASE_URL + '/' + res.data.data.records[0].roomPicPath
			this.roomTypeName = res.data.data.records[0].roomTypeName
			this.unitPrice = res.data.data.records[0].unitPrice
			this.startDate = moment(new Date(this.order.startTime)).format('MM月DD日')
			this.startDay = getDay(new Date(this.order.startTime).getDay())
			this.endDate = moment(new Date(this.order.endTime)).format('MM月DD日')
			this.endDay = getDay(new Date(this.order.endTime).getDay())
		},
		// #ifdef MP-WEIXIN
		onShareAppMessage(info) {
			return {
				title: '源享住',
				path: 'pages/login/login',
				imageUrl: "/static/logo.png"
			}
		}
		// #endif
	}
</script>

<style lang="scss">
	page {
		background-color: #EFEFF4;
	}

	.room-type-item {
		border-radius: 30rpx;
		background-color: #FFFFFF;
		margin: 20rpx;
		padding: 40rpx 20rpx;
		display: flex;
		background: #FFFFFF;
		border-radius: 10rpx;

		.room-type-item-middle {
			margin-left: 30rpx;
			display: flex;
			flex-direction: column;
			width: 200rpx;

			.room-type-item-middle-text {
				font-size: 40rpx;
				font-weight: bold;
				color: #333333;
			}

			.room-type-item-middle-bottom {
				margin-top: 40rpx;
				font-size: 25rpx;

				text {
					margin-right: 20rpx;
					color: #666666
				}
			}
		}

		.room-type-item-right {
			width: 25%;
			margin-left: 20rpx;

			.room-type-item-right-text {
				margin-left: 60rpx;
				margin-top: 40rpx;
			}

			text {
				font-size: 40rpx;
				font-weight: bold;
				color: #FF5C58
			}
		}
	}

	.checkin-date-info {
		border-radius: 30rpx;
		background-color: #FFFFFF;
		margin: 20rpx 20rpx;
		padding: 20rpx;
		display: flex;
		background: #FFFFFF;
		border-radius: 10rpx;

		.date-selector {
			margin: 20rpx;
			display: flex;
			width: 70vw;

			.date-item {
				width: 35vw;

				.date-info {
					display: flex;
				}
			}
		}

		.day-num {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
	}

	.guest-info {
		display: flex;
		flex-direction: column;
		align-items: center;
		height: 220rpx;
		width: 100%;
		margin-top: 40rpx;

		.swipe-item {
			background-color: #ffffff;
			text-indent: 1em;
			position: relative;
			height: 100%;
			color: #333333;
		}

		.swipe-item::after {
			content: "";
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 1px;
			max-height: 1px;
			min-height: 1px;
			transform: scaleY(0.5);
			background-color: #eeeeee;
		}

		.u-form {
			background-color: #FFFFFF;

			.u-form-item {
				line-height: 70rpx;

				.u-form-item__body {
					margin-left: 32rpx;
					border-bottom: 2rpx solid #E5E5E5;
				}

				.u-form-item__body__left__content__label {
					font-size: 36rpx;
					color: #666666;
				}
			}
		}
	}

	.u-swipe-action {
		.u-swipe-action-item {
			margin-top: 40rpx;

			.u-form {
				background-color: #FFFFFF;

				.u-form-item {
					line-height: 70rpx;

					.u-form-item__body {
						margin-left: 32rpx;
						border-bottom: 2rpx solid #E5E5E5;
					}

					.u-form-item__body__left__content__label {
						font-size: 36rpx;
						color: #666666;
					}
				}
			}
		}
	}


	.add-guest-btn-container {
		margin: 30rpx;
		padding-bottom: 160rpx;
	}

	.confirm-btn-container {
		margin: 30rpx;
		padding-bottom: 100rpx;
		transform: translateY(-160rpx);

		.u-button__text {
			font-size: 30rpx !important;
		}
	}

	.paymentArea {
		position: fixed;
		bottom: 30rpx;
		height: 110rpx;
		display: flex;
		background-color: #EFEFF4;
		z-index: 99;

		.completeBtn {
			width: 50vw;

			.u-button {
				height: 110rpx;
				color: #ffffff;
				background-color: #F78203;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 35rpx !important;
			}
		}

		.paymentArea--left {
			.price {
				display: block;
				margin-left: 20rpx;
				width: 50vw;
				line-height: 60rpx;
				font-size: 36rpx;
				font-weight: bold;

				text {
					&:nth-child(2) {
						color: #FF5C58;
					}
				}
			}

			.deposit {
				display: block;
				margin-left: 20rpx;
				width: 50vw;
				line-height: 40rpx;
				font-size: 24rpx;
				color: #666666;
			}
		}

		.deposit {
			display: block;
		}
	}
</style>