<template>
	<view class="content">
		<!-- 切换栏 -->
		<scroll-view :scroll-x="true" class="inv-h-w">
			<view :class="['inv-h',Inv==0?'inv-h-se':'']" @click="changeTab(0)">全部</view>
			<view :class="['inv-h',Inv==1?'inv-h-se':'']" @click="changeTab(1)">待支付</view>
			<view :class="['inv-h',Inv==2?'inv-h-se':'']" @click="changeTab(2)">已支付</view>
			<view :class="['inv-h',Inv==3?'inv-h-se':'']" @click="changeTab(3)">已入住</view>
			<view :class="['inv-h',Inv==4?'inv-h-se':'']" @click="changeTab(4)">已取消</view>
			<view :class="['inv-h',Inv==7?'inv-h-se':'']" @click="changeTab(7)">退款中</view>
			<view :class="['inv-h',Inv==5?'inv-h-se':'']" @click="changeTab(5)">已退款</view>
			<view :class="['inv-h',Inv==6?'inv-h-se':'']" @click="changeTab(6)">已退房</view>
		</scroll-view>
		<!-- 订单样式 -->
		<view class="room-kuang">
			<view v-if="Inv == 2" class="cancel-rule">取消规则：未办理入住的订单在09月06号之前可以办理退款，09月06号凌晨后均不允许退款操作。</view>
			<view class="room-xinxi" v-for="(item, index) in troom" :key="index">
				<!-- <view @click="navigateToOrderMark(item.id)"> -->
				<view>
					<image class="room-image" v-if="item.h_type.indexOf('标准') !== -1" src="../../static/index/std.jpg"></image>
					<image class="room-image" v-if="item.h_type.indexOf('高级') !== -1" src="../../static/index/adv.jpg"></image>
					<image class="room-image" v-if="item.h_type.indexOf('豪华') !== -1" src="../../static/index/lux.jpg"></image>
					<view class="room-name">{{ item.h_type }}</view>
					<view class="room-time">{{item.live_time|snippet}}～{{item.end_time|snippet}}</view>
					<view class="room-order">订单号：{{item.order_num}}</view>
					<view class="room-type">
						<text v-if="item.status==1">待支付</text>
						<text v-else-if="item.status==2">已支付</text>
						<text v-else-if="item.status==3">已入住</text>
						<text v-else-if="item.status==4">已取消</text>
						<text v-else-if="item.status==5">已退款</text>
						<text v-else-if="item.status==6">已退房</text>
						<text v-else="item.status==7">退款中</text>
					</view>
					<view class="room-price">￥{{ item.pay_account }}</view>
				</view>
				<!-- <uni-countdown v-if="item.status == 0" class="room-count" color="#FF5733" :show-day="false" :second="timeupSecond"
					@timeup="timeup(item.createTime)" />
				<text v-if="item.status == 0" class="room-count-txt">之后取消</text> -->
				<view class="room-button3" v-if="item.status == 2">
					<text v-if="item.status == 2" @click="openQu(item.order_num,'warn')">取消订单</text>
					<!-- <text v-else-if="item.status == 0" @click="openDel(item.id,'warn')">删除</text> -->
					<!-- <text v-else="item.status == 5" @click="openDel(item.id,'warn')">删除</text> -->
					<!-- <text v-else-if="item.status == 2">取消订单</text> -->
					<!-- <text v-else-if="item.status == 3" @click="navigateToXuzhu">续住</text> -->
				</view>
				<view :class="{'room-button3': item.status == 1}">
					<text v-if="item.status == 1" @click="getOrderPay(item.h_type, item.live_time, item.end_time)">支付</text>
					<!-- <text v-else-if="item.status == 0" @click="navigateToZaici(item.enableStartTime,item.enableEndTime,item.roomTypeId)">再次预定</text>
					<text v-else-if="item.status == 4" @click="navigateToJiezhang(item.id)">去处理</text>
					<text v-else-if="item.status == 5" @click="navigateToWanchengZaici(item.roomTypeId)">再次预定</text>
					<text v-else="item.status == 3" @click="openTui(item.id,'warn')">退房</text> -->
					<!-- <text v-else-if="item.status == 2" @click="openRu(item.id,'warn')">办理入住</text> -->
				</view>
				<view class="room-line" v-if="index<(troom.length-1)"></view>
			</view>
		</view>
		<!-- 提示时弹框 -->
		<uni-popup ref="popup_order2" type="dialog">
			<uni-popup-dialog :type="msgType2" cancelText="关闭" confirmText="确定" :content='order_txt2' @confirm="dialogConfirm"
				@close="dialogClose"></uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="popup_order" type="dialog">
			<uni-popup-dialog :type="msgType" cancelText="关闭" :content='order_txt'></uni-popup-dialog>
		</uni-popup>
		<!-- 办理续住弹窗 -->
		<uni-popup ref="popup_xuzhu" type="dialog" :mask-click="false">
			<view class="popup_bg_xu">
				<text class="popup_title">办理续住</text>
				<text class="popup_error" @click="popupXuzhuClose"></text>
				<text class="popup_xu_line"></text>
				<!-- 时间选择 -->
				<view class="select-time-xu" @click="openXuCalendar">
					<view class="select-time-one-xu">
						<text class="select-list">周四入住</text>
						<text class="select-list-time">07月21日</text>
					</view>
					<view class="select-center">
						<view class="select-line1"></view>
						<view class="select-circle">1晚</view>
						<view class="select-line2"></view>
					</view>
					<view class="select-time-one-xu">
						<text class="select-list">周五离店</text>
						<text class="select-list-time">07月22日</text>
					</view>
				</view>
				<text class="popup_xu_txt">注：办理续住最多7天，如超过7天需要重新预定</text>
				<!-- 支付框 -->
				<view class="fukuan">
					<view class="fu-price"><text style="font-size: 28rpx;">总计：</text>¥20.00</view>
					<view class="fu-zhifu">立即支付</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="popup_xu" :mask-click="true">
			<uni-calendar :selected="infoXu.selected" class="uni-calendar--hook" :clear-date="true" :date="infoXu.date" :insert="infoXu.insert"
				:lunar="infoXu.lunar" :startDate="infoXu.startDate" :endDate="infoXu.endDate" :range="infoXu.range" @change="changeXu" />
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				Inv: 6,
				room: [],
				troom: [],
				timeupSecond: null,
				//续住里选择器
				infoXu: {
					lunar: true,
					range: true,
					insert: true,
					selected: [],
					startDate: '',
					date: '',
					endDate: '',
					order_txt: '', //提交订单时信息
				},
				msgType: 'warn',
				msgType2: 'warn',
				order_txt: '', //
				order_txt2: '', //
				tankuang: false, //弹框是否确定
				order_txt_id: '',
				cardNumber: ''
			}
		},
		filters: {
			//字过长变为...
			snippet: function(value) {
				if (value.length >= 10) {
					return value.slice(0, 10);
				} else {
					return value
				}
			},
		},
		onLoad(option) {
			this.Inv = option.Inv;
			// 获取用户信息
			this.getUserInfo()
		},
		onShow() {
			// 模拟从后台拿到的数据
			var room = []
			// list数组中为每一项添加双向绑定的属性---这个属性要在页面显示(onShow)添加
			room.forEach(el => el.isChecked = false);
			this.room = room;
			this.troom = room; //真实数据赋值给页面数据
			this.changeTab(this.Inv)
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			clearInterval(this.timer);
		},
		mounted() {},
		onReady() {
			this.$nextTick(() => {
				this.showCalendar = true
			})
			// TODO 模拟请求异步同步数据
			setTimeout(() => {
				// console.log('date:'+getDate(new Date()).fullDate)
				// console.log('startDate:'+getDate(new Date()).fullDate)
				// console.log('endDate:'+getDate(new Date(),6).fullDate)
				this.infoXu.date = getDate(new Date()).fullDate
				this.infoXu.startDate = getDate(new Date()).fullDate
				this.infoXu.endDate = getDate(new Date(), 6).fullDate
			}, 2000)
		},
		methods: {
			/**
			 * 调起支付
			 */
			onBridgeReady() {
				var that = this;
				// 在这里可以使用WeixinJSBridge对象进行支付调用等操作
				// 调用支付接口
				if (typeof WeixinJSBridge !== 'undefined') {
					WeixinJSBridge.invoke('getBrandWCPayRequest', that.payData,
						function(res) {
							if (res.err_msg == "get_brand_wcpay_request:ok") {
								// 使用以上方式判断前端返回,微信团队郑重提示：
								//res.errMsg将在用户支付成功后返回ok，但并不保证它绝对可靠。
								uni.showModal({
									title: '提示',
									content: '支付成功',
									showCancel: false,
									success: (res) => {
										if (res.confirm) {
											uni.navigateTo({
												url: "/pages/my_orderlist/my_orderlist?Inv=2"
											})
										}
									}
								});
							} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
								uni.showToast({
									title: '支付取消',
									icon: 'success'
								});
							} else {
								uni.showModal({
									title: '提示',
									content: res.errMsg,
									showCancel: false
								})
							}
						});
				}
			},
			// 支付订单
			getOrderPay(hType, stime, etime) {
				let that = this
				that.$myRequest({
					method: 'POST',
					url: '/hotelReservation/zhotel/apporder_pay.action',
					data: {
						'card_number': that.cardNumber,
						'h_type': hType,
						'live_time': stime.substring(0, 10),
						'end_time': etime.substring(0, 10)
					},
					headers: {
						'Content-Type': 'application/json'
					}
				}).then(res => {
					let data = res.data
					if (data.code === 200) {
						let d = data.data;
						that.payData = {
							"appId": d.appId,
							"nonceStr": d.nonceStr,
							"paySign": d.paySign,
							"package": "prepay_id=" + d.prepay_id,
							"signType": d.signType,
							"timeStamp": d.timeStamp
						}

						if (typeof WeixinJSBridge === 'undefined') {
							if (document.addEventListener) {
								document.addEventListener('WeixinJSBridgeReady', that.onBridgeReady, false);
							} else if (document.attachEvent) {
								document.attachEvent('WeixinJSBridgeReady', that.onBridgeReady);
								document.attachEvent('onWeixinJSBridgeReady', ththatis.onBridgeReady);
							}
						} else {
							that.onBridgeReady();
						}
					} else {
						that.msgType = 'warn'
						that.order_txt = data.message
						that.$refs.popup_order.open()
					}
				});
			},
			// 获取用户信息
			getUserInfo() {
				var tempCardNumber = this.$utils.getEncryptedData('cardNumber')
				if (this.$utils.isEmpty(tempCardNumber)) {
					uni.showToast({
						title: '用户卡号为空'
					});
					return;
				}

				this.cardNumber = tempCardNumber;
			},
			// 订单列表
			getOrderPage() {
				let that = this
				var Inv2 = that.Inv
				that.troom = []
				that.room = []
				if (that.Inv == 0) {
					Inv2 = 'null'
				}
				that.$myRequest({
					url: '/hotelReservation/zhotel/appqueryOrder.action?card_number=' + that.cardNumber + '&state=' + Inv2
				}).then(res => {
					// console.log(res.data);
					var data = res.data
					if (data.code === 200) {
						data.data.forEach(item => {
							that.room.push(item)
							that.troom.push(item)
						})
					} else {
						that.msgType = 'warn'
						that.order_txt = data.message
						that.$refs.popup_order.open()
					}
				});
			},
			// 待确认的弹框操作
			dialogConfirm() {
				this.$refs.popup_order2.close()
				this.tankuang = true
				if (this.tankuang == true) {
					if (this.order_txt2 == '确定删除？') {
						this.getOrderDelete(this.order_txt_id)
					} else if (this.order_txt2 == '确定退房？') {
						this.getOrderReturn(this.order_txt_id)
					} else if (this.order_txt2 == '确定入住？') {
						this.getOrderHold(this.order_txt_id)
					} else if (this.order_txt2 == '确定取消订单？') {
						this.getOrderCancel(this.order_txt_id)
					}
				}
			},
			// 提示时弹框
			dialogClose() {
				this.$refs.popup_order2.close()
			},
			// 删除弹框
			openDel(id, type) {
				this.order_txt_id = id
				this.msgType2 = type
				this.order_txt2 = '确定删除？'
				this.$refs.popup_order2.open()
			},
			// 退房弹框
			openTui(id, type) {
				this.order_txt_id = id
				this.msgType2 = type
				this.order_txt2 = '确定退房？'
				this.$refs.popup_order2.open()
			},
			// 入住弹框
			openRu(id, type) {
				this.order_txt_id = id
				this.msgType2 = type
				this.order_txt2 = '确定入住？'
				this.$refs.popup_order2.open()
			},
			// 取消订单弹框
			openQu(id, type) {
				// console.log(id, type);
				this.order_txt_id = id
				this.msgType2 = type
				this.order_txt2 = '确定取消订单？'
				this.$refs.popup_order2.open()
			},
			// 办理退房
			getOrderReturn(order_txt_id) {
				let _self = this
				this.$axios.defaults.headers.common['user_token'] = localStorage.getItem('token');
				this.$axios.put(`/hotelReservation/zhotel/ihotel/hotelOrder/user/order/return/${this.order_txt_id}`, ).then(res => {
					res = res.data
					if (res.success) {
						this.order_txt = '退房成功'
						this.$refs.popup_order.open()
						this.getOrderPage()
					} else {
						this.order_txt = res.message
						this.$refs.popup_order.open()
					}

				});
				this.tankuang == false
			},
			// 办理入住
			getOrderHold(order_txt_id) {
				let _self = this
				this.$axios.defaults.headers.common['user_token'] = localStorage.getItem('token');
				this.$axios.put(`/hotelReservation/zhotel/ihotel/hotelOrder/user/order/hold/${this.order_txt_id}`, ).then(res => {
					res = res.data
					if (res.success) {
						this.order_txt = '办理入住成功'
						this.$refs.popup_order.open()
						this.getOrderPage()
					} else {
						this.order_txt = res.message
						this.$refs.popup_order.open()
					}
				});
			},
			// 删除订单
			getOrderDelete(order_txt_id) {
				let _self = this
				this.$axios.defaults.headers.common['user_token'] = localStorage.getItem('token');
				this.$axios.delete(`/hotelReservation/zhotel/ihotel/hotelOrder/user/order/${this.order_txt_id}`, ).then(res => {
					res = res.data
					if (res.success) {
						this.order_txt = '删除订单成功'
						this.$refs.popup_order.open()
						this.getOrderPage()
					} else {
						this.order_txt = res.message
						this.$refs.popup_order.open()
					}
				});
				this.tankuang == false
			},
			// 待支付取消订单
			getOrderCancel(order_txt_id) {
				let that = this
				// that.$axios.defaults.headers.common['user_token'] = that.$utils.getEncryptedData('token');
				that.$myRequest({
					url: '/hotelReservation/zhotel/apprefund.action?order_num=' + that.order_txt_id
				}).then(res => {
					// console.log(res.data);
					if (res.data.code === 200) {
						that.order_txt = '退款成功'
						that.$refs.popup_order.open()
						that.getOrderPage()
					} else {
						that.order_txt = res.data.message
						that.$refs.popup_order.open()
					}
				});
			},
			// 订单取消再次预订
			navigateToZaici(enableStartTime, enableEndTime, roomTypeId) {
				uni.navigateTo({
					url: "/pages/order_room/order_room?enableStartTime=" + enableStartTime + "&enableEndTime=" + enableEndTime + "&startTime=" +
						enableStartTime.substring(5, 7) + '月' + enableStartTime.substring(8, 10) + '日' + "&endTime=" + enableEndTime.substring(5, 7) +
						'月' + enableEndTime.substring(8, 10) + '日' + "&roomTypeId=" + roomTypeId
				})
			},
			// 订单已完成再次预订
			navigateToWanchengZaici(roomTypeId) {
				uni.navigateTo({
					url: '../order_room/order_room?roomTypeId=' + roomTypeId
				})
			},
			// 处理结账
			navigateToJiezhang(id) {
				uni.navigateTo({
					url: "/pages/order_mark/order_mark?orderId=" + id
				})
			},
			/*
			 * @Explain：选项卡点击切换
			 */
			changeTab(Inv) {
				var that = this;
				that.Inv = Inv
				var arr = [];
				// 订单列表
				that.getOrderPage(that.Inv)
				that.room.map(item => { //遍历真实数据，拿到所需要的数据放在页面数据tlist中，展示在页面上
					if (item.orderStatu == that.Inv) {
						arr.push(item);
					}
				})
				that.troom = arr;
				// if(this.Inv == 6){//获取全部数据
				// 	that.troom = that.room;
				// }
				// 滚动到顶部
				uni.pageScrollTo({
					duration: 0, //过渡时间必须为0，否则运行到手机会报错
					scrollTop: 0 //滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离（如res.top - data.top）
				})
			},
			// 倒计时
			timeup(createTime) {
				var that = this;
				/**setInterval间歇调用 */
				that.timer = setInterval(function() {
					//订单下单时间
					var buy_time = createTime;
					//计算剩余下单时间
					var time = (new Date(buy_time).getTime() + 10 * 60 * 1000) - (new Date().getTime());
					if (time > 0) {
						//计算剩余的分钟
						var minutes = parseInt(time / 1000 / 60 % 60, 10);
						//计算剩余的秒数
						var seconds = parseInt(time / 1000 % 60, 10);
						that.timeupSecond = parseInt(time / 1000);
						// console.log(that.timeupSecond)
						//判断分钟和秒数小于10要在前面加个0.
						if (minutes < 10) {
							minutes = '0' + minutes;
						}
						if (seconds < 10) {
							seconds = '0' + seconds;
						}
						var timer = minutes + ":" + seconds;
					}
				}, 1000);

				if (that.timeupSecond == 0) {
					uni.showToast({
						title: '时间到'
					})
					// 订单列表
					this.getOrderPage()
				}

				// this.timeupSecond = 0
			},
			// 跳转到订单详情
			navigateToOrderMark(id) {
				// console.log(id)
				uni.navigateTo({
					url: "/pages/order_mark/order_mark?orderId=" + id,
				})
			},
			// 办理续住弹窗
			navigateToXuzhu() {
				this.$refs.popup_xuzhu.open()
			},
			popupXuzhuClose() {
				this.$refs.popup_xuzhu.close()
			},
			// 续住里日期选择器弹窗
			openXuCalendar() {
				this.$refs.popup_xu.open()
			},
			changeXu(e) {
				console.log('1change 返回:', e)
				// 模拟动态打卡
				if (this.infoXu.selected.length > 5) return
				this.infoXu.selected.push({
					date: e.range.before,
					info: '到店'
				})
				this.infoXu.selected.push({
					date: e.range.after,
					info: '离店'
				})
			},

		},
	}
</script>

<style>
	@import url(./css/my_orderlist.css);
</style>