<template>
	<view>
		<view class="top">
			<!-- #ifdef MP-WEIXIN -->
			<NavigateBar title="我的订单" control="back" bgcolor="#9e97c3"></NavigateBar>
			<!-- #endif -->
			<!-- #ifdef MP-ALIPAY -->
			<NavigateBar title="我的订单" bgcolor="#9e97c3"></NavigateBar>
			<!-- #endif -->
		</view>
		<view v-if="roomTypePicPath">
			<view class="top-background">
				<view class="room-type-item">
					<view class="room-type-item-left">
						<u-image :src="roomTypePicPath" width="200rpx" height="200rpx" radius="10"></u-image>
					</view>
					<view class="room-type-item-middle">
						<view class="room-type-item-middle-text">
							<u-text :text="roomInfo" color="#333333" size="32rpx" bold></u-text>
						</view>
						<!-- <view class="room-type-item-middle-bottom">
							<u-text :text="roomArea" color="#666666"></u-text>
						</view> -->
					</view>
					<view class="room-type-item-right">
						<view class="room-type-item-right-text">
							<u-text :text="'￥'+unitPrice" color="#FF5C58" align="right" size="24px" bold></u-text>
						</view>
					</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="start.date" color="#333333" size="14" bold></u-text>
							<u-text :text="start.day" 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="end.date" color="#333333" size="14" bold></u-text>
							<u-text :text="end.day" color="#333333" size="14" bold></u-text>
						</view>
					</view>
				</view>
				<view class="day-num">
					<view>
						<u-text :text="dayNumText" color="#333333" size="15" bold></u-text>
					</view>
					<view>
						<u-text :text="breakfastNumText" color="#333333" size="15" bold></u-text>
					</view>
				</view>
			</view>
			<view class="guest-info">
				<u-form v-for="info in guestInfos" :key="info.name" labelPosition="left" labelWidth="240rpx"
					labelAlign="left">
					<u-form-item label="住客姓名" prop="name">
						<u-text :text="info.name" color="#333333" bold size="16"></u-text>
					</u-form-item>
					<u-form-item label="联系电话" prop="phone">
						<u-text :text="info.phone" color="#333333" bold size="16"></u-text>
					</u-form-item>
					<u-form-item label="离店时间">
						<u-text :text="endTime" color="#333333" bold size="16"></u-text>
					</u-form-item>
				</u-form>
			</view>
			<view class="end-time-tip">
				<u-text :text="endTimeTip" align="center"></u-text>
			</view>
			<view class="btn-area">
				<button v-if="fromExtend == true" class="btn" hover-class="btn-hover" @click="showCalendar">续住</button>
				<button v-else class="btn" hover-class="btn-hover" @click="confirmCheckout">退房</button>
			</view>
			<view>
				<u-calendar :show="calendarShow" mode="single" title="选择离店日期" @confirm="confirmEndTime"
					@close="calendarShow=false" :minDate="minDate" :defaultDate="minDate" color="#9e97c3"></u-calendar>
			</view>
		</view>
		<view v-else>
			<view class="not-reservation">
				<u-text class="tip" text="您还未入住！" align="center"></u-text>
				<u-text v-if="fromExtend" class="tip" text="若已退房或房间到期,请至前台办理" align="center"></u-text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getDay
	} from '../../utils/commonUtils.js'
	import {
		IMG_BASE_URL
	} from "../../config.js"
	import moment from 'moment'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import NavigateBar from "../../components/navigateBar/navigate-bar.vue";
	export default {
		components: {
			NavigateBar
		},
		data() {
			return {
				roomTypePicPath: '',
				roomInfo: '',
				unitPrice: '',
				roomArea: '',
				start: {},
				end: {},
				dayNumText: '',
				guestInfos: [],
				calendarShow: false,
				minDate: '',
				order: {},
				dayNum: '',
				newOrderId: '',
				fromExtend: true,
				newEndTime: '',
				checkinInfo: {},
				extendButtonLoading: false,
				extendButtonLoadingText: '办理中',
				endTimePickerShow: false,
				maxDate: 0,
				oldEndTime: '',
				needAuthPay: false,
				breakfastNum: 0,
				orderId: '',
				endTime: '',
				canExtend: false,
				checkinInfoId: ''
			};
		},
		computed: {
			...mapState('m_user', ['userInfo']),
			...mapState('m_business', ['currentHotel']),
			breakfastNumText() {
				return this.breakfastNum ? `含${this.breakfastNum}早` : '不含早'
			},
			endTimeTip() {
				let text
				if (this.fromExtend) {
					text = '续住'
				} else {
					text = '退房'
				}
				return '请在 ' + this.currentHotel.checkoutTime + ' 前办理' + text + '，逾期请至前台办理'
			}
		},
		methods: {
			...mapMutations('m_business', ['updateCheckinInfo']),
			confirmCheckout() {
				uni.showModal({
					title: '您确定退房吗？',
					success: (res) => {
						if (res.confirm) {
							this.checkout()
						}
					}
				})
			},
			async checkout() {
				let res = await uni.$http.post(`/scm/checkout/${this.checkinInfoId}`);
				if (res.data.success === true) {
					this.updateCheckinInfo({})
					uni.$showMsg('退房办理成功！')
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/home/home'
						})
					}, 1000)
				} else {
					uni.$showMsg('退房失败，请至前台办理')
				}
			},
			async queryCanExtend() {
				let res = await uni.$http.get(`/scm/canExtend/${this.orderId}`)
				if (res.data.data == true) {
					this.canExtend = true
				} else {
					this.canExtend = false
				}
			},
			showCalendar() {
				if (!this.canExtend) {
					uni.$showMsg('不满足续住条件，请至前台办理')
					return
				}
				this.calendarShow = true
			},
			async extend() {
				let res = await uni.$http.post(`/scm/extend/${this.newOrderId}`);
				if (res.data.success === true) {
					this.updateCheckinInfo({})
					uni.$showMsg('续住办理成功！')
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/home/home'
						})
					}, 2000)
				} else {
					uni.$showMsg('续住办理失败')
				}
			},
			async confirmEndTime(e) {
				this.newEndTime = e[0]
				this.dayNum = (new Date(e[0]).getTime() - new Date(this.minDate).getTime()) / (24 * 60 * 60 * 1000) + 1
				uni.showModal({
					title: '确认续住' + this.dayNum + '天吗？',
					success: (res) => {
						if (res.confirm) {
							this.calendarShow = false
							this.createExtendOrder()
						}
					}
				})
			},
			async createExtendOrder() {
				let info = {
					id: this.checkinInfoId,
					dayNum: this.dayNum
				}
				let createRes = await uni.$http.post('/scm/extend/orderId', info)
				if (createRes.data.code === 200) {
					let resData = createRes.data.data
					this.newOrderId = resData.orderId
					this.needAuthPay = resData.needAuthPay
					this.pay(this.newOrderId)
				} else {
					uni.$showMsg('订单不满足续住条件，请至前台办理')
				}
			},
			async pay(orderId) {
				console.log("pay start");

				// #ifdef MP-WEIXIN
				let res = await uni.$http.post('/order/payment/weChat', {
					openid: this.userInfo.openid,
					orderId: orderId,
				})
				res.data.data.package = res.data.data.packageStr
				let paymentResult = await wx.requestPayment(res.data.data)
				console.log("payment result:", paymentResult)
				if (paymentResult.errMsg === 'requestPayment:ok') {
					uni.$showMsg("支付成功")
					this.extend()
				}
				// #endif

				// #ifdef MP-ALIPAY
				if (!this.needAuthPay) {
					await this.aliPaymentNormal(orderId)
				} else {
					await this.aliPaymentFreeze(orderId)
				}
				// #endif
			},
			async getCheckinInfo() {
				let res = await uni.$http.get(`/user/checkinInfo/${this.currentHotel.hotelId}`);
				if (res.data.code == 200) {
					let checkinInfo = res.data.data
					console.log(checkinInfo)
					if (checkinInfo) {
						this.roomTypePicPath = IMG_BASE_URL + '/' + checkinInfo.roomPicPath
						this.roomInfo = checkinInfo.roomTypeName + checkinInfo.room
						this.unitPrice = checkinInfo.unitPrice
						this.breakfastNum = checkinInfo.breakfastNum
						this.endTime = moment(checkinInfo.endTime).format('M月DD日 HH:mm')
						this.orderId = checkinInfo.orderId
						this.checkinInfoId = checkinInfo.id
						let guest = {
							name: checkinInfo.name,
							phone: checkinInfo.phone
						}
						// if (order) {
						// 	this.order = order
						// 	this.roomTypePicPath = IMG_BASE_URL + '/' + order.roomPicPath
						// 	this.roomInfo = order.roomTypeName + order.room
						// 	this.unitPrice = '￥' + order.unitPrice
						// } else {
						// 	let roomInfoRes = await uni.$http.post('/roomInfo', {
						// 		hotelId: this.checkinInfo.hotelId,
						// 		room: this.checkinInfo.room,
						// 		pageNo: 1,
						// 		pageSize: 1
						// 	})
						// 	console.log('roominfo', roomInfoRes)
						// 	let roomTypeRes = await uni.$http.post('/roomType', {
						// 		roomType: roomInfoRes.data.data.records[0].roomType,
						// 		pageNo: 1,
						// 		pageSize: 1
						// 	})
						// 	let roomType = roomTypeRes.data.data.records[0]
						// 	this.roomTypePicPath = IMG_BASE_URL + '/' + roomType.roomPicPath
						// 	this.roomInfo = roomType.roomTypeName + this.checkinInfo.room
						// 	this.unitPrice = '￥' + roomType.unitPrice
						// }
						this.guestInfos.push(guest)

						let originEndTime = new Date(checkinInfo.endTime);
						this.newEndTime = new Date(originEndTime.valueOf() + 24 * 60 * 60 * 1000)
						this.oldEndTime = checkinInfo.endTime

						this.start.date = moment(checkinInfo.startTime).format('MM月DD日')
						this.start.day = getDay(new Date(checkinInfo.startTime).getDay())
						this.end.date = moment(checkinInfo.endTime).format('MM月DD日')
						this.end.day = getDay(new Date(checkinInfo.endTime).getDay())

						this.dayNumText = '共' + checkinInfo.dayNum + '晚'

						//设置日历
						let endDate = new Date(checkinInfo.endTime)
						endDate.setDate(endDate.getDate() + 1)
						this.minDate = moment(new Date(endDate)).format('YYYY-MM-DD')
					} else {
						this.checkinInfo = {}
					}
				} else {
					// #ifdef MP-WEIXIN
					uni.$showMsg('查询失败！')
					// #endif
				}
			},
			// #ifdef MP-ALIPAY
			async aliPaymentNormal(orderId) {
				let alipayRes = await uni.$http.post('/hotelOrder/alipayPrepay', {
					openid: this.userInfo.openid,
					orderId: orderId,
					platform: 'ALIPAY',
					hotelId: this.currentHotel.hotelId
				})
				// console.log("获取预付号",alipayRes.data.data)
				let tradeNo = alipayRes.data.data.tradeNo
				let tradeRes = await my.tradePay({
					tradeNO: tradeNo
				})
				// console.log("tradeRes 交易支付结果",tradeRes.resultCode);

				if (tradeRes.resultCode === "6002") {
					// 网络连接出错
					uni.showModal({
						title: "网络连接出错",
						content: "网络连接出错，请检查网络连接后重试。",
					});
				}

				// 顾客支付后，查询支付状态
				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("支付成功")
						this.extend()
					}
				}
			},
			async aliPaymentFreeze(orderId) {
				// 申请获取签名字符串
				let alipayRes = await uni.$http.post('/hotelOrder/alipayFreezeFund', {
					orderId: orderId,
					hotelId: this.currentHotel.hotelId
				})
				// console.log("签名字符串", alipayRes.data)

				if (!alipayRes.data.success) {
					console.log("获取签名字符串");
					uni.showModal({
						title: "网络连接出错。",
						content: "网络连接出错，请检查网络连接后重试。",
					});
					return
				}

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

				if (tradeRes.resultCode === "6002") {
					// 网络连接出错
					uni.showModal({
						title: "网络连接出错",
						content: "网络连接出错，请检查网络连接后重试。",
					});
				}

				// 顾客授权后，查询授权状态
				if (["9000", "6004", "8000"].includes(tradeRes.resultCode)) {
					// 顾客授权后，查询授权状态，只有AUTHORIZED（已授权状态：授权成功，可以进行转支付或解冻操作）才算成功
					let tradeStatus = await uni.$http.post('/hotelOrder/queryFreezeStatus', {
						orderId: orderId,
						hotelId: this.currentHotel.hotelId
					})
					// console.log("tradeStatus", tradeStatus);
					if (tradeStatus.data.success && tradeStatus.data.data === "AUTHORIZED") {
						uni.$showMsg("支付成功")
						this.extend()
					}
				}
			}
			// #endif
		},
		async onLoad(options) {
			await this.getCheckinInfo()
			this.fromExtend = options.fromExtend == 'true'
			if (this.fromExtend) {
				await this.queryCanExtend()
			}
		},
		// #ifdef MP-WEIXIN
		onShareAppMessage(info) {
			return {
				title: '源享住',
				path: 'pages/login/login',
				imageUrl: "/static/logo.png"
			}
		}
		// #endif
	}
</script>

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

		.top-background {
			background-color: #9e97c3;
			overflow: hidden;

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

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

					.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-right: 20rpx;

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

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

	}

	.checkin-date-info {
		transform: translateY(-100rpx);
		border-radius: 30rpx;
		background-color: #FFFFFF;
		margin: 20rpx;
		padding: 20rpx;
		display: flex;
		background: #FFFFFF;
		border-radius: 10rpx;
		box-shadow: 0rpx 8rpx 11rpx 2rpx rgba(79, 121, 225, 0.19);

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

			.date-item {
				width: 35vw;

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

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

	.u-form {
		transform: translateY(-100rpx);
		background-color: #FFFFFF;

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

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

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

	.btn-area {
		transform: translateY(-60rpx);
		display: flex;
		justify-content: space-evenly;

		.btn {
			color: #9e97c3;
			border: 1rpx solid #9e97c3;
			background-color: #FFFFFF;
			font-weight: bold;
			font-size: 33rpx;
			width: 250rpx;
		}

		.btn-hover {
			color: #FFFFFF;
			background-color: #9e97c3;
		}
	}


	.not-reservation {
		margin-top: 40%;
	}

	.end-time-tip {
		transform: translateY(-100rpx);
	}
</style>