<template>
	<view class="content">
		<!-- 切换栏 -->
		<scroll-view :scroll-x="true" class="inv-h-w">
			<view :class="['inv-h',Inv==6?'inv-h-se':'']" @click="changeTab(6)">全部</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==0?'inv-h-se':'']" @click="changeTab(0)">已取消</view>
			<view :class="['inv-h',Inv==4?'inv-h-se':'']" @click="changeTab(4)">待结账</view>
			<view :class="['inv-h',Inv==5?'inv-h-se':'']" @click="changeTab(5)">已完成</view>
		</scroll-view>
		<!-- 订单样式 -->
		<view class="room-kuang">
			<view class="room-xinxi" v-for="(item,index) in troom" :key="index">
				<view @click="navigateToOrderMark(item.id)">
				<image class="room-image" :src="item.roomTypeMasterImg"></image>
				<view class="room-name">{{item.roomTypeName}}</view>
				<view class="room-time">{{item.enableStartTime|snippet}}-{{item.enableEndTime|snippet}}</view>
				<view class="room-order">订单号：{{item.id}}</view>
				<view class="room-type">
					<text v-if="item.orderStatu==0">已取消</text>
					<text v-if="item.orderStatu==1">待支付</text>
					<text v-if="item.orderStatu==2">待入住</text>
					<text v-if="item.orderStatu==3">已入住</text>
					<text v-if="item.orderStatu==4">
						待结账
					</text>
					<text v-if="item.orderStatu==5">已完成</text>
				</view>
				<view class="room-price">￥{{item.payAmount}}</view>
				</view>
				<uni-countdown v-if="item.orderStatu == 1" class="room-count" color="#FF5733" :show-day="false" :second="timeupSecond" @timeup="timeup(item.createTime)" />
				<text v-if="item.orderStatu == 1" class="room-count-txt">之后取消</text>
				<view class="room-button" v-if="item.orderStatu != 4 && item.orderStatu != 2 && item.orderStatu != 3">
					<text v-if="item.orderStatu == 0" @click="openDel(item.id,'warn')">删除</text>
					<text v-if="item.orderStatu == 1" @click="openQu(item.id,'warn')">取消订单</text>
					<text v-if="item.orderStatu == 5" @click="openDel(item.id,'warn')">删除</text>
					<!-- <text v-if="item.orderStatu == 2">取消订单</text> -->
					<!-- <text v-if="item.orderStatu == 3" @click="navigateToXuzhu">续住</text> -->
				</view>
				<view class="room-button2" :class="{'room-button3': item.orderStatu == 1 || item.orderStatu == 4}">
					<text v-if="item.orderStatu == 0" @click="navigateToZaici(item.enableStartTime,item.enableEndTime,item.roomTypeId)">再次预定</text>
					<text v-if="item.orderStatu == 1" @click="getOrderPay(item.id)">支付</text>
					<text v-if="item.orderStatu == 4" @click="navigateToJiezhang(item.id)">去处理</text>
					<text v-if="item.orderStatu == 5" @click="navigateToWanchengZaici(item.roomTypeId)">再次预定</text>
					<text v-if="item.orderStatu == 2" @click="openRu(item.id,'warn')">办理入住</text>
					<text v-if="item.orderStatu == 3" @click="openTui(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>
	/**
	 * 获取任意时间
	 */
	function getDate(date, AddDayCount = 0) {
		if (!date) {
			date = new Date()
		}
		if (typeof date !== 'object') {
			date = date.replace(/-/g, '/')
		}
		const dd = new Date(date)
	
		dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
	
		var a = new Array("日", "一", "二", "三", "四", "五", "六");  
		var week = new Date().getDay();    
		var week2 = new Date().getDay()+1;    
		const y = dd.getFullYear()
		const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期，不足10补0
		const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
		const h = dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours()
		const f = dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes()
		const s = dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds()
		return {
			fullDate: y + '-' + m + '-' + d,
			fullDate2: y + '-' + m + '-' + d+' '+h+':'+f+':'+s,
			fullTime: m + '月' + d + '日',
			year: y,
			month: m,
			date: d,
			day: dd.getDay(),
			sWeek:"周"+ a[week],
			eWeek:"周"+ a[week2]
		}
	}
	// 导入图片
	import room1 from '../../static/index/room_image.svg'
	import room2 from '../../static/index/room_image.svg'
	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:'',
			}
		},
		filters:{
			//字过长变为...
			snippet: function(value) {
				if(value.length>=10) {
					return value.slice(0, 10);
				} else {
					return value
				}
			},
		},
		onShow() {
			// 模拟从后台拿到的数据
			var room = []
			// list数组中为每一项添加双向绑定的属性---这个属性要在页面显示(onShow)添加
			room.forEach(el => el.isChecked = false);
			this.room = room;
			this.troom = room;//真实数据赋值给页面数据
			this.changeTab(this.Inv)
		},
		onLoad(option) {
			this.Inv=option.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:{
			// 订单列表
			getOrderPage() {
				  let _self = this
				  var Inv2=this.Inv
				  _self.troom = []
				  _self.room = []
				  if (this.Inv==6) {
					  Inv2=''
				  }
				  this.$axios.get("/hotel/ihotel-api/ihotel/hotelOrder/user/order/page?curPage=1&pageSize=100&statu="+Inv2,
				  {
					  headers:{
						  'user_token':localStorage.getItem('token')
					  }
				  }).then(res => {
					res = res.data
					if (res.success) {
						// console.log(res)
					  res.data.list.forEach(data => {
						_self.troom.push(data)
						_self.room.push(data)
					  })
					} else {
					  console.log('获取订单列表失败')
					}
				  });
			},
			//待确认的弹框操作
			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) {
				this.order_txt_id=id
				this.msgType2 = type
				this.order_txt2='确定取消订单？'
				this.$refs.popup_order2.open()
			},
			// 支付订单
			getOrderPay(id) {
				  let _self = this
				  this.$axios.get(`/hotel/ihotel-api/ihotel/hotelOrder/user/order/pay/${id}`,
				  {
					  headers:{
						  'user_token':localStorage.getItem('token')
					  }
				  }).then(res => {
					res = res.data
					if (res.success) {
						if(res.data.payAmount==0) {
							uni.navigateTo({
								url: '../zhifuchenggong/zhifuchenggong?orderId='+res.data.orderId
							})
						} else {
							window.location.href = res.data.payUrl;
						}
						
					} else {
						this.order_txt=res.message
						this.$refs.popup_order.open()
						console.log('支付失败')
					}
				  });
			},
			// 办理退房
			getOrderReturn(order_txt_id) {
				let _self = this
				this.$axios.defaults.headers.common['user_token'] = localStorage.getItem('token');
				this.$axios.put(`/hotel/ihotel-api/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(`/hotel/ihotel-api/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(`/hotel/ihotel-api/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 _self = this
				this.$axios.defaults.headers.common['user_token'] = localStorage.getItem('token');
				this.$axios.put(`/hotel/ihotel-api/ihotel/hotelOrder/user/order/cancel/${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()
					}
				});
			},
			// 订单取消再次预订
			navigateToZaici(enableStartTime,enableEndTime,roomTypeId){
				uni.navigateTo({
					url:"../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:"../order_mark/order_mark?orderId="+id
				})
			},
			/*
			  * @Explain：选项卡点击切换
			  */
			changeTab(Inv) {
				console.log(Inv)
				var that = this;
				this.Inv =Inv
				var arr = [];
				this.getOrderPage(this.Inv)
				that.room.map(item => {//遍历真实数据，拿到所需要的数据放在页面数据tlist中，展示在页面上
					if(item.orderStatu == this.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: "../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>